Arith: the Metal arithmetic deviations and the profile's float-function and NaN-encoding fields go

DriverDeviation::MetalFloatFunctions, MetalCanonicalNans, MetalFloatDenormals,
MetalUnaryDenormals, MetalMinMax, MetalHalfFma, MetalPackConversions, MetalHalfArithmetic,
MetalNanMoves and MetalHalfConversion, with their VkProperty values and codec tags, were never
taken: Device::from_queries enables no Metal* property, and no committed profile carries one.
Their forms go, and so do the two profile fields each left with one reachable value:
- ProfileFields::float_functions and FloatFunctions (only Native was reachable): the device's
  functions are never Metal's own. Gone with it: pipeline::EntryMath (public), the entry-math
  argument of PrecisionNote::of_float_operator and of_math_call, libm's Mode and its
  device_answers and device_near_equivalent, spirv's ProductForm (a product is an OpFMul, its
  negative-zero Fma form gone), and arith's OpNotes, MetalOwn and metal_functions_in (a call's
  notes are a BTreeSet<PrecisionNote>).
- ProfileFields::nan_encoding and NanEncoding (only Native was reachable): NanAnswer's
  device_answers and nan::encoding go; every NaN Metal answers is noted NativeNanEncoding.
- Denormals: denormal.rs keeps covered() alone (Covered, device_flushes, unary_kept and
  moves_sign go); every f32 denormal left to the device is noted DeviceDenormals.
- MinMax: Metal's minimum and maximum family is the device's NMin, NMax and NClamp, noted
  NativeMinMax (device_min_max goes).
- MetalHalfFma: its arm and test go.
- Pack conversions: every air.pack and air.unpack is noted DevicePackConversion
  (pack::measured and ArithPlan::metal_packs go).
- Half arithmetic: the device's 16-bit half + - * is taken only under the 16-bit float controls;
  F16Basis goes (f16_arithmetic answers a bool), and so do ArithPlan::f16_arith and the
  FastMathRewrites note of the measured form left to the device's compiler.
- NaN moves: a widening's, a negation's and a magnitude's NaN is the device's, noted (moved_nan,
  moves_nan, nan::moves_answered, FloatFacts::nan_moves and ArithPlan's nan_moves and
  held_nan_moves go). A half texel's write to a 32-bit float format notes DeviceNanEncoding on
  every device (texture::half_write_nans' Wide class goes; HeapNanFamilies' NAN_WIDE family
  now holds no deviation).
- Half conversion: every half the module rounds through the device's conversion is noted
  NativeHalfConversion; texture::half_texels (a sample of a 32-bit float texel) and
  half_texel_nans (a 32-bit float or packed small float class) lose their MetalHalfConversion
  exceptions, so both note those classes on every profile. Gone with it, the analyses only the
  measured facts read: narrow::round_measured (round serves) with the
  measured roundings the builder and the IR carried, narrow::rounds_unmeasured,
  narrow::moves_unfolded with the merges module, and the stored texels the texture writes
  recorded for it.
compile.rs's half-rounding block keeps converts, widens, the controlled and fused roundings and
their three notes; the MetalNanMoves, MetalHalfConversion, MetalPackConversions and
MetalHalfArithmetic requirements go.

Notes: the precision-note catalogue loses no entry. Every note the deleted forms withheld is
still raised, now on every device (NativeNanEncoding, DeviceDenormals, NativeMinMax,
DevicePackConversion, NativeHalfConversion, HalfTexelConversion, DeviceNanEncoding, NativeDot,
NativeMix); their docs and docs/HOWTO.md lose the measured exceptions, and the docs of a device
whose functions are Metal's own go from math.rs, arith and artifact.rs.

Validation: c3/bound.rs asks the product's notes of an operation (AirOp::product_notes), part of
how C3 decides a near-equivalent; it passed an EntryMath the product read only for the
unreachable form, so it drops the argument and its answers are unchanged.
fast_trig_within_apples_bound's doc loses the MoltenVK clause.

Tests: each deleted form's tests go with it (the_maths_functions_are_the_device_s, the member
format version 486 round trip, a_measured_half_sum_requires_the_arithmetic_fact_alone,
a_merge_of_a_select_is_followed_through_struct_members, the device_answers asserts), with the
hand-set profile fields only they used (FloatFacts' nans, device_denormals, unary_denormals,
native_min_max, nan_moves). The rest assert the note on every profile: engine_arith,
engine_float_call_notes (its note class is the fma route alone), engine_native_half,
engine_metal_denormals, engine_tiny_products, engine_rate_map, engine_opencl_mode,
engine_texture, engine_extended_range's heap test, from_queries, arith's and narrow's tests.

SEMANTICS_VERSION 2238, ARTIFACT_FORMAT_VERSION 576 (placeholders; main renumbers). SEMANTICS:
the notes and keys of the same input change form. ARTIFACT: the codec loses ten DriverDeviation
and eight VkProperty tags and EntryMath. RUNTIME_VERSION stays: the pinned sources' edits
(device/profile.rs, device/derive.rs, device/requirements.rs, lower/arith/pack.rs and a doc in
bind/heap.rs) remove forms no profile reached, so no run changes; runtime-sources.sha256 takes
the new hash. api_signatures is blessed; docs/REFUSALS.md and the coverage are unchanged.

Consumer check (consumer-uses.sh, consumer development c8407fb6fc, 58 refs): EntryMath,
of_float_operator, of_math_call, MetalCanonicalNans, MetalFloatDenormals, MetalFloatFunctions,
MetalHalfArithmetic, MetalHalfFma, MetalMinMax, MetalNanMoves, MetalPackConversions,
MetalUnaryDenormals, FloatFunctions and NanEncoding 0 hits (code). MetalHalfConversion: 0 on
development; used in crates/reims-vgpu-vulkan/src/gpu/rgbx.rs on three of the consumer's
steelbrain/* branches (gaugetick, recnil-r4, refdump), a crate its development no longer has.

Verified: m3-max-61298 at this tree (WIP arith 10, msi-laptop): fmt, clippy (all features,
--cfg m2v_gpu and --cfg m2v_cpu_icd) and Rustdoc rc 0 (61293, on the tree before, failed clippy
on three unused imports, which this tree removes); nextest over metal2vulkan,
metal2vulkan-conformance, metal2vulkan-validation and metal2vulkan-runtime, 5876 run, 5874
passed, 25 skipped, 2 failed: the render key test
(the_old_render_descriptor_key_keeps_its_value), left unpinned until the next named pin, and
golden_hashes_match_the_table, whose 29536 stale cells are all under a changed profile
fingerprint (0 new, 0 gone, 0 under a changed fixture source): the profile lost two fields, so
every key changed and the table is re-blessed on development.

Rebased onto development d10a14d5af: the SEMANTICS placeholder is one above its 2235 in stack order
(ARTIFACT_FORMAT_VERSION is already above its 574). The checks above ran at the old base acc706ca47;
the rebased stack's tip is checked by m3-max-61756 (msi-laptop), at the stack rebased on d6d56b8a7c
(tip 5c74fad38d, whose diff from its base is this stack's diff from d10a14d5af): fmt, clippy (all
features, --cfg m2v_gpu, --cfg m2v_cpu_icd) and Rustdoc green; nextest of metal2vulkan,
metal2vulkan-validation, metal2vulkan-conformance and metal2vulkan-runtime ran 5877 tests, 5870
passed. Of the 7 failures, the old render descriptor key's test is unpinned; golden_hashes and
engine inventory parts 4, 5, 7 and 8 are bless due (the profiles' fingerprints changed); and
metal::state's encoder_raster_state_needs_its_features fails the same way at development d10a14d5af
itself (m3-max-61802, where runtime-floor gained depthBiasClamp in a529fb658e), as inventory parts
3, 4, 5 and 8 do there. The stack as rebased on 72e1754218 (tip 090d544208: the same product
changes, without the test-only push sweep fix) played 36 distinct streams over 61 runs on five nodes
with 0 refused (player m3-max-61537; plays m3-max-61548, 61549, 61550, 61559 and 61569).
This commit is contained in:
Anees Iqbal committed 2026-11-20 22:07:19 -08:00
1 parent 5db3215260
commit efa911bc00
59 files changed
+753 -3362

No files matched your search

@@ -1 +1 @@
4a5b4059ae00eeaa7edcf46e3651cf2ed4066b64c22c11d81c0deef1bf89909a
9c0db9f87ef306400bae2334e3749350c1a68c875d2a5d5b1f5e9ffb93c17e7a
+11 -20
View File
@@ -34,7 +34,7 @@ use crate::case::BufferResource;
use crate::observation_contract::{value_difference, ValueDifference};
use base64::Engine as _;
use metal2vulkan::device::{DeviceProfile, FloatWidth};
use metal2vulkan::pipeline::{EntryMath, PrecisionNote};
use metal2vulkan::pipeline::PrecisionNote;
use metal2vulkan_air::intrinsics::AirIntrinsic;
use metal2vulkan_air::ir::{BinOp, FastMath};
use msl::{Admits, Expr, Format, Math, Prim};
@@ -302,25 +302,20 @@ impl AirOp {
/// The precision notes the product's lowering of this operation on `format` records under
/// `math` on profile `profile`: the product's own answer (`PrecisionNote::of_float_operator`,
/// or `PrecisionNote::of_math_call` of the call's name as [`AirIntrinsic::parse`] decodes it).
/// Under fast math Metal's calls and operators carry every fast-math flag (`fast`), and the
/// entry's module is a fast one ([`EntryMath::Fast`]); otherwise they carry none, a division
/// without them is Metal's precise one, which records nothing, and the module keeps NaNs
/// ([`EntryMath::Precise`]). An error where the product does not lower the operation as a float
/// operation.
/// Under fast math Metal's calls and operators carry every fast-math flag (`fast`); otherwise
/// they carry none, and a division without them is Metal's precise one. An error where the
/// product does not lower the operation as a float operation.
pub fn product_notes(
&self,
format: Format,
math: Math,
profile: &DeviceProfile,
) -> Result<BTreeSet<PrecisionNote>, String> {
let (fmf, entry) = match math {
Math::Fast => (
FastMath::ALL
.iter()
.fold(FastMath::NONE, |all, (flag, _)| all.union(*flag)),
EntryMath::Fast,
),
Math::Precise => (FastMath::NONE, EntryMath::Precise),
let fmf = match math {
Math::Fast => FastMath::ALL
.iter()
.fold(FastMath::NONE, |all, (flag, _)| all.union(*flag)),
Math::Precise => FastMath::NONE,
};
let notes = match self {
AirOp::Binop(op) => PrecisionNote::of_float_operator(
@@ -331,12 +326,9 @@ impl AirOp {
},
fmf,
profile,
entry,
),
AirOp::Call(name) => match AirIntrinsic::parse(name) {
Some(AirIntrinsic::Math(call)) => {
PrecisionNote::of_math_call(call, fmf, profile, entry)
}
Some(AirIntrinsic::Math(call)) => PrecisionNote::of_math_call(call, fmf, profile),
_ => None,
},
};
@@ -359,8 +351,7 @@ impl std::fmt::Display for AirOp {
/// Metal's (a near-equivalent): a float division, a square root or remainder, and a function the
/// product computes with a division of its own (fast `float` `tanh` and `atan2`). Whether the
/// product records it is the product's answer ([`AirOp::product_notes`]) on the row's venue profile
/// `profile`: on a device whose `float` functions are Metal's own, an operation that is Metal's own
/// under fast math records none there.
/// `profile`.
///
/// The device's transcendentals (`DeviceTranscendentals`) are the device's own answer, which the
/// user accepts within Apple's bound, so they are no near-equivalent.
@@ -1,10 +1,10 @@
//! Fast `sin`, `cos` and `tan` on `[-pi, pi]` keep the device's own instruction, and on a device
//! whose functions are Metal's (MoltenVK) fast `sinpi`, `cospi` and `tanpi` keep the device's `Sin`
//! and `Cos` around their exact reduction: a near-equivalent of Metal's answer, accepted by the
//! user's standing sign-off only where the device answers within Apple's fast-math bound (MSL Table
//! 8.2: `sin` and `cos` within `2^-13` absolute on `[-pi, pi]`, `sinpi` and `cospi` on `[-1, 1]`,
//! `tan` as `sin(x) * (1 / cos(x))` and `tanpi` as `tan(x * pi)`). This test holds that condition
//! to the committed evidence instead of to prose. Every committed Vulkan and MoltenVK row of the
//! Fast `sin`, `cos` and `tan` on `[-pi, pi]` keep the device's own instruction, and fast `sinpi`,
//! `cospi` and `tanpi` keep the device's `Sin` and `Cos` around their exact reduction: a
//! near-equivalent of Metal's answer, accepted by the user's standing sign-off only where the
//! device answers within Apple's fast-math bound (MSL Table 8.2: `sin` and `cos` within `2^-13`
//! absolute on `[-pi, pi]`, `sinpi` and `cospi` on `[-1, 1]`, `tan` as `sin(x) * (1 / cos(x))` and
//! `tanpi` as `tan(x * pi)`). This test holds that condition to the committed evidence instead of
//! to prose. Every committed Vulkan and MoltenVK row of the
//! fast math-library probe case (1,024 operands under Metal's default fast math; words `32t` to
//! `32t + 4` are the fast `sin`, `cos`, `tan`, and `sincos` of operand `t`, and words `32t + 26`
//! to `32t + 28` its fast `sinpi`, `cospi`, and `tanpi`) is judged by C3's bound check
+2 -2
View File
@@ -440,8 +440,8 @@ pub(crate) const FILTERED: u32 = 2;
/// `DriverDeviation::MetalHalfStorageWrites`.
pub(crate) const NAN_SIXTEEN: u32 = 1;
/// The bit of `SpecKey::HeapNanFamilies` of a 32-bit float format: its written `half` NaN is
/// Metal's on a device of `DriverDeviation::MetalNanMoves`.
/// The bit of `SpecKey::HeapNanFamilies` of a 32-bit float format: its written `half` NaN is the
/// device's widening's.
pub(crate) const NAN_WIDE: u32 = 2;
/// The bit of `SpecKey::HeapNanFamilies` of a packed small float format (`RG11B10Float`,
+3 -5
View File
@@ -1047,16 +1047,14 @@ codec_enum! {
InterpolateAtOffsetCentered, SimdgroupLockstep, MetalSampler, StorageImageSampleCount(f0),
DepthResolveMode(f0), StencilResolveMode(f0), IndependentResolveNone, IndependentResolve,
VariableSampleLocations, SampleLocationSampleCount(f0), ColorAttachmentSampleCount(f0, f1),
MetalHalfFma, MetalFloatDenormals,
MetalCenterVaryings, MetalMinMax,
MetalHalfArithmetic, MetalHalfStorageWrites, MetalHalfStorageNans,
MetalCenterVaryings, MetalHalfStorageWrites, MetalHalfStorageNans,
MetalFragmentSimdgroups, MetalVertexSimdgroups,
MetalHalfTexelWrites, MetalNormStorageWrites, DeviceSampling,
MetalDepth16Stores, MetalDepth16BiasedStores, MetalInterpolation, MetalFirstVertexIndices,
MetalFullQuads, ProvokingVertexModePerPipeline,
MetalNormalizedVertexFetch, MetalAlphaCoverage, InterpolateAtOffsetFromSevenSixteenths,
MetalNanMoves, MetalPackConversions, MetalHalfConversion, MetalSmallFloatNans,
MetalUnaryDenormals, SubgroupGeometryStage,
MetalSmallFloatNans,
SubgroupGeometryStage,
}
VkLimit {
MaxComputeWorkGroupSize(f0), MaxComputeWorkGroupCount(f0), MaxComputeWorkGroupInvocations,
+2 -2
View File
@@ -61,7 +61,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 = 2237;
pub const SEMANTICS_VERSION: u32 = 2238;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
@@ -71,7 +71,7 @@ pub const SEMANTICS_VERSION: u32 = 2237;
/// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag
/// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that
/// bumps it says what changed; this comment keeps no history.
pub const ARTIFACT_FORMAT_VERSION: u32 = 575;
pub const ARTIFACT_FORMAT_VERSION: u32 = 576;
/// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding
/// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle
-10
View File
@@ -821,16 +821,6 @@ fn the_version_485_member_round_trips() {
assert_ne!(encode(&key), encode(&SpecKey::NearestPixelSampler(slot)));
}
/// The member format version 486 appends encodes and decodes as itself: the measured unary
/// operations' kept denormals, a property a module requires.
#[test]
fn the_version_486_member_round_trips() {
use crate::device::requirements::VkProperty;
let p = VkProperty::MetalUnaryDenormals;
assert_eq!(decode::<VkProperty>(&encode(&p)), Ok(p));
assert_ne!(encode(&p), encode(&VkProperty::MetalSmallFloatNans));
}
/// The member format version 535 appends encodes and decodes as itself: a kernel's image-only
/// fact.
#[test]
+2 -4
View File
@@ -16,8 +16,8 @@ use crate::device::metal::MetalDeviceProperties;
use crate::device::policy::DevicePolicy;
use crate::device::profile::{
BufferAccess, CubeGradientRoute, CubeGradients, DescriptorCaps, DeviceProfile, EnabledCaps,
FloatFunctions, FormatTable, FragmentCaps, FunctionStorage, HandleDomain, ImageCaps,
Independence, LeafCaps, NanEncoding, PointerDomain, ProfileFields, Robustness,
FormatTable, FragmentCaps, FunctionStorage, HandleDomain, ImageCaps, Independence, LeafCaps,
PointerDomain, ProfileFields, Robustness,
};
use crate::device::requirements::{
ApiVersion, FloatControl, FloatWidth, FormatUsage, ResolveMode, SubgroupOp, VkExtension,
@@ -331,8 +331,6 @@ fn derive_fields(desc: &DeviceDescription, policy: &DevicePolicy) -> ProfileFiel
// so the extended dynamic states a pipeline makes are exactly what it requires.
dynamic_vertex_stride: has(VkFeature::ExtendedDynamicState),
enabled: enabled_caps(desc),
float_functions: FloatFunctions::Native,
nan_encoding: NanEncoding::Native,
// The planes of a two-plane YCbCr texture read in place on every device.
ycbcr_in_place: true,
// The floor: no Vulkan query states how much a thread holds.
-69
View File
@@ -226,27 +226,13 @@ impl DeviceProfile {
.enabled
.properties
.contains(&VkProperty::SimdgroupLockstep),
DriverDeviation::MetalFloatFunctions => f.float_functions == FloatFunctions::Metal,
DriverDeviation::MetalCanonicalNans => f.nan_encoding == NanEncoding::MetalCanonical,
DriverDeviation::MetalSampler => {
f.enabled.properties.contains(&VkProperty::MetalSampler)
}
DriverDeviation::MetalHalfFma => {
f.enabled.properties.contains(&VkProperty::MetalHalfFma)
}
DriverDeviation::MetalFloatDenormals => f
.enabled
.properties
.contains(&VkProperty::MetalFloatDenormals),
DriverDeviation::MetalCenterVaryings => f
.enabled
.properties
.contains(&VkProperty::MetalCenterVaryings),
DriverDeviation::MetalMinMax => f.enabled.properties.contains(&VkProperty::MetalMinMax),
DriverDeviation::MetalHalfArithmetic => f
.enabled
.properties
.contains(&VkProperty::MetalHalfArithmetic),
DriverDeviation::MetalHalfStorageWrites => f
.enabled
.properties
@@ -298,25 +284,10 @@ impl DeviceProfile {
.enabled
.properties
.contains(&VkProperty::MetalAlphaCoverage),
DriverDeviation::MetalNanMoves => {
f.enabled.properties.contains(&VkProperty::MetalNanMoves)
}
DriverDeviation::MetalPackConversions => f
.enabled
.properties
.contains(&VkProperty::MetalPackConversions),
DriverDeviation::MetalHalfConversion => f
.enabled
.properties
.contains(&VkProperty::MetalHalfConversion),
DriverDeviation::MetalSmallFloatNans => f
.enabled
.properties
.contains(&VkProperty::MetalSmallFloatNans),
DriverDeviation::MetalUnaryDenormals => f
.enabled
.properties
.contains(&VkProperty::MetalUnaryDenormals),
}
}
@@ -477,14 +448,6 @@ pub struct ProfileFields {
pub dynamic_vertex_stride: bool,
/// The enabled capability sets `Requirements` are checked against.
pub enabled: EnabledCaps,
/// Which functions the device's `GLSL.std.450` instructions and `OpFDiv` of `float` compute:
/// Metal's own, in the math mode Metal's compile of the module takes, or the device's. The
/// module takes the device's instructions on either; the notes it records differ.
pub float_functions: FloatFunctions,
/// Which NaN the device's `float` and `half` arithmetic answers: Metal's canonical NaN, measured,
/// or the device's own, which the module records where Metal answers a NaN. Either way the
/// translation leaves every NaN's bits to the device.
pub nan_encoding: NanEncoding,
/// Whether a two-plane YCbCr texture's planes may be read in place
/// (`bind::YCbCrInPlace`): on a device whose GPU reads the planes' memory with no bus between
/// (`VkPhysicalDeviceType` integrated or CPU), a texture slot whose function reads such a
@@ -581,38 +544,6 @@ impl FunctionStorage {
}
}
/// Which functions a device's `GLSL.std.450` instructions and `OpFDiv` of `float` compute
/// ([`ProfileFields::float_functions`]), decided by the driver's measured deviation
/// [`DriverDeviation::MetalFloatFunctions`]. Either way the module takes the device's
/// instructions.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FloatFunctions {
/// Metal's own, in the math mode Metal compiles the module with: fast where the entry
/// declares no `SignedZeroInfNanPreserve`, precise where it declares one, and precise
/// `tanh` and `atan2` either way. The division likewise: Metal's fast division and
/// reciprocal in a fast-math module, its correctly rounded ones otherwise. A call that is
/// Metal's own in the entry's mode records no note there.
Metal,
/// The device's, within Vulkan's precision table, taken as they are, each kind recorded with
/// its bound.
Native,
}
/// Which NaN a device's `float` and `half` arithmetic answers ([`ProfileFields::nan_encoding`]),
/// decided by the driver's measured deviation [`DriverDeviation::MetalCanonicalNans`]. The
/// translation selects no NaN under either: every NaN's bits are the device's.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NanEncoding {
/// Metal's canonical NaN, `0x7FC00000` (`0x7E00` as `half`), for every NaN result of the
/// arithmetic and of the functions whose NaN Metal canonicalizes, measured: such a result
/// records nothing.
MetalCanonical,
/// The device's own, unmeasured, noted `PrecisionNote::NativeNanEncoding` with its bound.
Native,
}
/// What the consumer enabled, as the capability vocabulary `Requirements` uses
/// ([`DeviceProfile::enabled`]). Selection reads the typed caps above; the finalize check
/// (`requirements ⊆ profile`) reads these.
@@ -638,27 +638,6 @@ pub enum VkProperty {
/// `framebuffer*ColorSampleCounts` are the counts every format of a kind takes; one format
/// may take more.
ColorAttachmentSampleCount(vk::Format, u32),
/// The device's `GLSL.std.450 Fma` on 16-bit floats is Metal's own `half` `fma` (the
/// driver's measured deviation
/// [`DriverDeviation::MetalHalfFma`](crate::error::DriverDeviation::MetalHalfFma)). No Vulkan
/// query reports it. A module whose `half` fused multiply-add takes that instruction requires
/// it; without it, the fused multiply-add is a 16-bit `OpFmaKHR` under the 16-bit float
/// controls, or the device's `float` `Fma` rounded to `half`
/// (`PrecisionNote::NativeFma`).
MetalHalfFma,
/// The device's `float` arithmetic, comparisons, `Ldexp`, `Sqrt`, `InverseSqrt`, `Trunc` and
/// `RoundEven` read an `f32` denormal operand as the zero of its sign and flush a denormal
/// result, as Metal does
/// (the driver's measured deviation
/// [`DriverDeviation::MetalFloatDenormals`](crate::error::DriverDeviation::MetalFloatDenormals)).
/// No Vulkan query reports it: `DenormFlushToZero` makes only the results' flush a
/// requirement, the operands' remains the device's choice. A module that leaves such an
/// operation's denormals to the device, recording no `PrecisionNote::DeviceDenormals` for it,
/// requires it; without it, they are the device's own, and the module records that note. So
/// does a module whose entry declares the 16-bit float controls, on every device, as a driver
/// may keep `f32` denormals there (NVIDIA's on the RTX 3090 and the RTX 5080 Laptop GPU); it
/// requires no such property.
MetalFloatDenormals,
/// The device reads a center-sampled varying of a multisampled pipeline at the pixel center
/// in every fragment invocation, a sample-rate one's included, as Metal does (the driver's
/// measured deviation
@@ -669,24 +648,6 @@ pub enum VkProperty {
/// pixel form, requires it; without it, their pixel form is `InterpolateAtOffset` at offset
/// 0, which requires [`VkProperty::InterpolateAtOffsetCentered`].
MetalCenterVaryings,
/// The device's `GLSL.std.450` `NMin`, `NMax` and `NClamp` on 32-bit floats are Metal's own
/// `fmin`, `fmax` and `clamp` (the driver's measured deviation
/// [`DriverDeviation::MetalMinMax`](crate::error::DriverDeviation::MetalMinMax)). No Vulkan
/// query reports it. Every `float` or `half` minimum, maximum or clamp takes those
/// instructions: a module that does requires it, and without it the module records
/// `PrecisionNote::NativeMinMax`.
MetalMinMax,
/// The device's 16-bit `OpFAdd` and `OpFSub` decorated `NoContraction`, and its 16-bit
/// `Fma(a, b, -0.0)` decorated `NoContraction`, are Metal's own `half` `+`, `-` and `*` (the
/// driver's measured deviation
/// [`DriverDeviation::MetalHalfArithmetic`](crate::error::DriverDeviation::MetalHalfArithmetic)).
/// No Vulkan query reports it. A module whose `half` `+`, `-` or `*` takes those instructions
/// requires it; without it, the module takes them under the 16-bit float controls, or
/// computes in `float` and rounds the result to `half` as every `half` rounds. A module that
/// reads a `half` from its bits by the device's widening, outside the 16-bit float controls,
/// requires it too: the measurement reads every `half` through that widening, denormals
/// included; without it the module records `PrecisionNote::NativeHalfConversion`.
MetalHalfArithmetic,
/// The device stores every `float` but a NaN that a shader writes to a half-float storage
/// image as Metal stores a kernel's write, rounded toward zero (the driver's measured
/// deviation
@@ -803,34 +764,6 @@ pub enum VkProperty {
/// requires it, where no module does (the coverage is the pipeline's multisample state);
/// without it, the pipeline's fragment stage records that note.
MetalAlphaCoverage,
/// The device's widening and narrowing between 16- and 32-bit floats, and its `OpFNegate`
/// and `FAbs`, answer Metal's NaN bits (the driver's measured deviation
/// [`DriverDeviation::MetalNanMoves`](crate::error::DriverDeviation::MetalNanMoves)). No Vulkan
/// query reports it: Vulkan states no NaN's bits. A module that reads a `half` from its bits or
/// encodes one to them, widens a `half` to `float`, negates a `float` or takes the magnitude
/// of a `float` or `half`, and records no
/// [`PrecisionNote::NativeNanEncoding`](crate::pipeline::PrecisionNote::NativeNanEncoding)
/// for it requires it.
MetalNanMoves,
/// The device's conversions of the packed normalized formats measured to answer Metal's
/// (the driver's measured deviation
/// [`DriverDeviation::MetalPackConversions`](crate::error::DriverDeviation::MetalPackConversions)).
/// No Vulkan query reports it: Vulkan leaves the conversions' rounding to the device. A
/// module that converts one of those forms and records no
/// [`PrecisionNote::DevicePackConversion`](crate::pipeline::PrecisionNote::DevicePackConversion)
/// for it requires it.
MetalPackConversions,
/// The device's conversion of a 32-bit float to 16 bits answers Metal's `half(float)` where
/// the module converts a `float` it holds, and Metal's own `half` texel where the `float` is
/// an image instruction's texel (the driver's measured deviation
/// [`DriverDeviation::MetalHalfConversion`](crate::error::DriverDeviation::MetalHalfConversion)).
/// No Vulkan query reports it: without the float controls Vulkan leaves the conversion's
/// rounding to the device. A module that rounds a `half` through that conversion in those
/// forms alone (a texel's value among them: one the module decodes itself, or a merge of
/// texels) records no
/// [`PrecisionNote::NativeHalfConversion`](crate::pipeline::PrecisionNote::NativeHalfConversion)
/// and requires it.
MetalHalfConversion,
/// The device stores a NaN a shader writes to a packed small float storage image
/// (`B10G11R11_UFLOAT_PACK32`) as Metal stores it, a `float`'s or a `half`'s widened (the
/// driver's measured deviation
@@ -839,15 +772,6 @@ pub enum VkProperty {
/// [`PrecisionNote::DeviceNanEncoding`](crate::pipeline::PrecisionNote::DeviceNanEncoding)
/// for it and requires it.
MetalSmallFloatNans,
/// The device's `float` `OpFNegate` and `FAbs` keep an `f32` denormal and its `Floor` and
/// `Ceil` read one as the zero of its sign, as Metal's `-x`, `fabs`, `floor` and `ceil` do (the
/// driver's measured deviation
/// [`DriverDeviation::MetalUnaryDenormals`](crate::error::DriverDeviation::MetalUnaryDenormals)).
/// Vulkan lets a device keep or flush them. A module that leaves those operations' denormals to
/// the device records no
/// [`PrecisionNote::DeviceDenormals`](crate::pipeline::PrecisionNote::DeviceDenormals) for
/// them and requires it.
MetalUnaryDenormals,
/// `GLSL.std.450 InterpolateAtOffset` at offset `v` reads Metal's `interpolate_at_offset` at
/// `v + 7/16`, measured from the pixel's upper-left corner: a device whose description reports
/// a MoltenVK driver, whose SPIRV-Cross hands the instruction to Metal so at any release
@@ -134,12 +134,6 @@ entry:
!5 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"gid"}
"#;
/// On every committed profile `Device::from_queries` derives, a kernel's `float` product beside a
/// `half` one ([`MIXED_PRODUCTS`]) records `PrecisionNote::DeviceDenormals` and requires no
/// `VkProperty::MetalFloatDenormals`, whether its entry declares the 16-bit float controls (where
/// the device computes the `half` product in 16 bits) or not: no Vulkan query states that a
/// device reads an `f32` denormal as Metal does, and a driver may keep one under the 16-bit
/// controls, so the note is static.
/// A device whose `maxPushConstantsSize` is below the 256 bytes of the push window every stage is
/// lowered for is below the floor: `Unsupported{PushWindow}`, needing `MaxPushConstantsSize` 256.
/// The descriptions below it are committed apart (`validation/profiles/below-floor/`, this test's
@@ -180,9 +174,13 @@ fn a_push_window_below_256_bytes_is_below_the_floor() {
}
}
/// On every committed profile `Device::from_queries` derives, a kernel's `float` product beside a
/// `half` one ([`MIXED_PRODUCTS`]) records `PrecisionNote::DeviceDenormals`, whether its entry
/// declares the 16-bit float controls (where the device computes the `half` product in 16 bits) or
/// not: no Vulkan query states that a device reads an `f32` denormal as Metal does, and a driver
/// may keep one under the 16-bit controls, so the note is static.
#[test]
fn from_queries_records_the_device_denormals_of_a_float_product() {
use crate::device::requirements::VkProperty;
use crate::pipeline::artifact::PrecisionNote;
use crate::pipeline::testing::{compile, llvm_assemble_text, AssembleError};
let bc = match llvm_assemble_text(MIXED_PRODUCTS) {
@@ -204,10 +202,6 @@ fn from_queries_records_the_device_denormals_of_a_float_product() {
a.precision.contains(&PrecisionNote::DeviceDenormals),
"{stem}"
);
assert!(
!(a.requirements.properties).contains(&VkProperty::MetalFloatDenormals),
"{stem}"
);
compiled += 1;
}
assert!(compiled >= 10, "{compiled} profiles compiled the kernel");
+1 -117
View File
@@ -501,16 +501,6 @@ pub enum DriverDeviation {
/// an Apple GPU runs a Metal simdgroup (`VkProperty::SimdgroupLockstep`). Unmeasured, a kernel
/// that needs that order takes emulated simdgroups, exact.
SimdgroupLockstep,
/// The device computes each `GLSL.std.450` function and `OpFDiv` of `float` as Metal's own,
/// in the math mode Metal compiles the module with (`FloatFunctions::Metal`). Unmeasured, the
/// module takes the device's instructions all the same, each kind recorded with its bound
/// (`PrecisionNote::NativeTranscendentals`, and `NativeDivision`, `NativeDot` and `NativeMix`
/// for a division, a `dot` and a `mix`).
MetalFloatFunctions,
/// The device's `float` and `half` arithmetic answers Metal's canonical NaN
/// (`NanEncoding::MetalCanonical`). The module leaves every NaN's bits to the device either
/// way; unmeasured, a NaN Metal answers records `PrecisionNote::NativeNanEncoding`.
MetalCanonicalNans,
/// The device samples, filters and converts texels through Metal's own sampler
/// (`VkProperty::MetalSampler`), an 8-bit sRGB texel's decode included. Unmeasured, every
/// sample, gather, comparison and level query is the device's own sampler's all the same
@@ -527,23 +517,6 @@ pub enum DriverDeviation {
/// two tangents: an `x` or `z` face's gradient reaches it as Metal's own, a `y` face's `z`
/// tangent is lost. Unmeasured, as [`DriverDeviation::CubeGradientRoute`].
GraphicsCubeGradientTangents,
/// The device's `GLSL.std.450 Fma` on 16-bit floats is Metal's own `half` `fma`, which
/// rounds the exact `a * b + c` once (`VkProperty::MetalHalfFma`). Where the profile also has
/// `shaderFloat16`, a `half` fused multiply-add converts its operands (each a `half`, so
/// exactly) to 16 bits, takes the device's `Fma` and widens its result. Unmeasured, it takes
/// `OpFmaKHR` on 16 bits where the profile has `shaderFmaFloat16` and rounds to `half` under
/// the 16-bit float controls, and elsewhere the device's `float` `Fma` rounded to `half`,
/// recorded as `PrecisionNote::NativeFma`.
MetalHalfFma,
/// The device's `float` arithmetic reads an `f32` denormal operand as the zero of its sign
/// and flushes a denormal result to one, as Metal does (`VkProperty::MetalFloatDenormals`):
/// `OpFAdd`, `OpFSub`, `OpFMul`, `OpFmaKHR`, `OpDot`, the comparisons, and `GLSL.std.450`'s
/// `Ldexp`, `Sqrt`, `InverseSqrt`, `Trunc` and `RoundEven`. Measured in entries that declare
/// no float-controls mode: in an entry that declares the 16-bit float controls a driver may
/// keep them, and no query tells which, so there they are the device's own on every device.
/// Unmeasured, or in such an entry, such operands and results are the device's own, recorded
/// as `PrecisionNote::DeviceDenormals`.
MetalFloatDenormals,
/// The device reads a center-sampled varying (a smooth input decorated neither `Centroid`
/// nor `Sample`) of a multisampled pipeline at the pixel center in every fragment
/// invocation, a sample-rate one's included, as Metal reads it
@@ -554,37 +527,6 @@ pub enum DriverDeviation {
/// that reads from the center (`VkProperty::InterpolateAtOffsetCentered`), and a function that
/// runs per sample is refused elsewhere.
MetalCenterVaryings,
/// The device's `GLSL.std.450` `NMin`, `NMax` and `NClamp` on 32-bit floats are Metal's own
/// `fmin`, `fmax` and `clamp` (`VkProperty::MetalMinMax`): a NaN operand loses, two NaNs and a
/// tie answer the second operand's bits, an `f32` denormal compares as a zero but is returned
/// itself, and `clamp(x, lo, hi)` is `fmin(fmax(x, lo), hi)`, in every math mode, of every
/// operand class, and of every `half` held widened. Metal's `fmin`, `fmax`, `min3`, `max3`,
/// `clamp` and `saturate` on `float` and `half` are those instructions on every profile: where
/// the profile takes it the module requires the property, and unmeasured it records
/// `PrecisionNote::NativeMinMax`.
MetalMinMax,
/// The device's 16-bit `OpFAdd` and `OpFSub` decorated `NoContraction`, and its 16-bit
/// `Fma(a, b, -0.0)` decorated `NoContraction`, are Metal's own `half` `+`, `-` and `*`
/// (`VkProperty::MetalHalfArithmetic`), with operands narrowed from `float` and the result
/// widened back: the exact result rounded once to nearest even on the `half` grid, `half`
/// denormals kept, an exact zero sum `+0` unless both addends are `-0`, and every NaN result
/// `0x7E00`, in every math mode. Where the profile also has `shaderFloat16`, a `half` `fadd`,
/// `fsub` or `fmul` converts its operands (each a `half`, so exactly) to 16 bits, takes that
/// kept instruction and widens its result; one whose flags carry `contract` and `reassoc` takes
/// the instruction undecorated instead, the AIR's own contraction, outside the measurement
/// (Metal's fast compile folds its conversions away, `PrecisionNote::FastMathRewrites`), and
/// requires nothing for it. Unmeasured, it takes the same instruction under the
/// 16-bit float controls that make it Metal's by the Vulkan spec (`QuantizeForm::Controlled`),
/// and elsewhere computes the result in `float` and rounds it to `half` as every `half`
/// rounds (`narrow::round`, noted `NativeHalfConversion` or `NativeHalfQuantize` where that
/// rounding is not Metal's). The measurement reads every `half` through the device's
/// widening (`x + -0` of every `x`), exact but for a NaN, denormals included: a module that
/// reads a `half` from its bits by that widening (every profile with `shaderFloat16` does)
/// requires the property for its denormals, and records `PrecisionNote::NativeNanEncoding`
/// for its NaNs' bits but where the profile takes [`MetalNanMoves`].
///
/// [`MetalNanMoves`]: DriverDeviation::MetalNanMoves
MetalHalfArithmetic,
/// The device stores every `float` but a NaN that a shader writes to a half-float storage
/// image (`R16Float`, `RG16Float`, `RGBA16Float`; a storage texel buffer of one too) as Metal
/// stores a kernel's write (`VkProperty::MetalHalfStorageWrites`): rounded toward zero, a
@@ -710,71 +652,13 @@ pub enum DriverDeviation {
/// alpha records no `PrecisionNote::DeviceAlphaCoverage` and requires the property.
/// Unmeasured, such a pipeline's fragment stage records the note.
MetalAlphaCoverage,
/// The device's operations that move a `float` or `half` NaN, rather than compute one, answer
/// Metal's bits (`VkProperty::MetalNanMoves`): its widening of a 16-bit float to 32 bits
/// (`OpFConvert`) answers `0x7FC00000` for every `half` NaN, as Metal's `float(half)` does;
/// its narrowing of a 32-bit float to 16 bits answers Metal's `half` NaN, and its narrowing of
/// such a widening, moved through the registers (selects, phis, a function's `float`
/// variable), which the driver's compiler folds, the `half`'s own bits, as Metal's moves of a
/// `half` keep them; its `OpFNegate` and `FAbs` of a `float` keep a NaN's payload with the sign
/// flipped or cleared, as Metal's `fneg` and `fabs` do; and its `FAbs` of a `half` held
/// widened answers the canonical NaN, as Metal's `half` `fabs` does. Where the profile takes
/// it, a module that reads a `half` from its bits or encodes one to them, a `half`'s widening
/// to `float` and a `half` `fabs` record no `PrecisionNote::NativeNanEncoding` and the module
/// requires the property, but where the module carries a widened `half` out of the registers
/// (a store to a stage output or another variable, a call, a group, atomic or image operation)
/// or reads its bits before narrowing it, or holds a `float` NaN constant other than
/// `0x7FC00000`, which the measurement does not cover (`narrow::moves_unfolded`): there each
/// records the note. A `float` `fneg` and `fabs` record none and require the property. A `half`
/// `fneg` records the note on every profile: the device negates the held `float`, whose NaN
/// keeps its flipped sign unless the driver's compiler moves the negation onto the `half`.
/// Unmeasured, each records it.
MetalNanMoves,
/// The device's conversions of Metal's packed normalized formats outside the four
/// `GLSL.std.450` names in `float` answer Metal's codes and values
/// (`VkProperty::MetalPackConversions`): `unpack_unorm565_to_float` and
/// `pack_float_to_unorm565`, and the `half` forms of `unorm4x8`, `snorm4x8` and `unorm10a2`
/// (both ways), `unorm565` (both ways) and `unorm2x16` and `snorm2x16` (packing). The module
/// takes each as it does on every profile (the format's `GLSL.std.450` instruction, or its
/// definition on the format's fields, around a `half`'s widening or rounding); where the
/// profile takes this deviation, each records no `PrecisionNote::DevicePackConversion` and
/// the module requires the property. The sRGB format, `unorm10a2` in `float`, `snorm10a2`, and
/// the `half` unpacks of `unorm2x16` and `snorm2x16` stay noted. Unmeasured, each records it.
MetalPackConversions,
/// The device's conversion of a 32-bit float to 16 bits, `OpFConvert` (MSL's `half(x)`
/// through MoltenVK), answers Metal's (`VkProperty::MetalHalfConversion`): Metal's
/// `half(float)` (to nearest even on the `half` grid, `half` denormals kept, infinity from
/// 65520 up) of every `float` a function converts, whatever instruction computed it, and,
/// where the `float` is an image instruction's texel, Metal's own `half` result of that access,
/// into which Metal's compiler folds the conversion. Where the profile takes it, a module whose
/// every `half` rounding through that conversion (`QuantizeForm::Converted`) is a conversion of
/// a `float` the function holds (an AIR `fptrunc` or `air.convert` from `float`) or of a
/// texel's value (an image instruction's texel, one the module decodes itself, or a merge of
/// them, whose `half` the access's own texel notes state against Metal's) records no
/// `PrecisionNote::NativeHalfConversion` and requires the property. A `half` a function or an
/// operation computes in `float` and rounds
/// keeps the note on every profile: Metal computes it otherwise (its `half` `tanh` answers 7
/// of the 65,536 `half`s otherwise than the nearest even `half` of its `float` `tanh`, which the
/// device's conversion answers). Unmeasured, each records it.
MetalHalfConversion,
/// The device stores the NaN a shader writes to a packed small float storage image
/// (`B10G11R11_UFLOAT_PACK32`, Metal's `RG11B10Float`) as Metal stores the same write: a
/// `float` texel's NaN, whatever its sign and payload, and a `half` texel's, handed to the
/// device widened (`VkProperty::MetalSmallFloatNans`). Where the profile takes it, a write that
/// may reach such an image records no `PrecisionNote::DeviceNanEncoding` for it and the module
/// requires the property; with [`DriverDeviation::MetalNanMoves`], whose widening of a `half`
/// answers Metal's, a widened `half` written there moves its NaN as measured
/// (`lower::arith::narrow::moves_unfolded`). Unmeasured, the write records the note.
/// requires the property. Unmeasured, the write records the note.
MetalSmallFloatNans,
/// The device's `float` negation, absolute value, floor and ceiling (`OpFNegate`, `FAbs`,
/// `Floor` and `Ceil`) read an `f32` denormal as Metal does (`VkProperty::MetalUnaryDenormals`):
/// a negation and an absolute value move the sign bit alone, keeping the denormal, and a floor
/// and a ceiling read it as the zero of its sign (`floor(-2^-149)` is `-0`, `ceil(2^-149)` is
/// `+0`). Where the profile takes it, those operations record no
/// `PrecisionNote::DeviceDenormals` and the module requires the property. A texel centre's
/// `floor` stays noted where its address mode parts texel -1 from texel 0: Metal's sampler
/// reads its coordinate unflushed. Unmeasured, each records the note.
MetalUnaryDenormals,
}
/// One device capability a refusal can name.
+3 -15
View File
@@ -118,7 +118,6 @@ use std::collections::{BTreeMap, BTreeSet};
use crate::air::abi::{ImageblockArg, ImageblockKind, ParamBinding, ParamRole};
use crate::air::intrinsics::{Imageblock, PackDir, PackFormat};
use crate::air::ir::{Call, Const, Value};
use crate::device::profile::FloatFunctions;
use crate::device::requirements::{FormatUsage, VkFeature};
use crate::error::{
Attachment, Capability, DescriptorError, Error, Feature, MetalAnswer, RuntimeInput, Unsupported,
@@ -878,20 +877,9 @@ pub(super) fn select_texel(
slot.staged = true;
slot.stored |= store;
let (offset, leaf) = (slot.offset, slot.leaf);
// The device's conversion, but a `float` one of a format `GLSL.std.450` names on a device
// whose `float` functions are Metal's (Metal's own `pack_float_to_*` and `unpack_*_to_float`,
// as `air.pack`'s strategy notes it); a `half` load rounds the unpacked `float` once more.
if let Some(n) = norm {
let dir = match store {
true => PackDir::Pack,
false => PackDir::Unpack,
};
let own = cx.profile.fields().float_functions == FloatFunctions::Metal
&& (store || !n.half)
&& pack::instruction(n.norm.format, dir).is_some();
if !own {
cx.precision.insert(PrecisionNote::DevicePackConversion);
}
// The device's conversion; a `half` load rounds the unpacked `float` once more.
if norm.is_some() {
cx.precision.insert(PrecisionNote::DevicePackConversion);
}
imageblock::place_region(cx, cell_bytes)?;
let coord = imageblock::operand(cx, coord)?;
+31 -92
View File
@@ -1,81 +1,19 @@
//! How Metal reads `f32` denormals, per operation, against the device: where the device reads them
//! as Metal does, an `f32` denormal operand as the zero of its sign and a denormal result flushed
//! to one (`DriverDeviation::MetalFloatDenormals`, a measured driver fact), or, for a negation, an
//! absolute value, a floor and a ceiling, as Metal's (`DriverDeviation::MetalUnaryDenormals`),
//! the module leaves them to it and requires the property; elsewhere they are the device's own,
//! noted (`PrecisionNote::DeviceDenormals`). Only `float` operations are listed: a widened `half` is
//! never an `f32` denormal, and Metal's `bfloat` and `double` environments are not measured.
//! How Metal reads `f32` denormals, per operation, against the device: Metal reads an `f32`
//! denormal operand as the zero of its sign and flushes a denormal result to one, where the device
//! keeps or flushes them by its own float controls, noted (`PrecisionNote::DeviceDenormals`). Only
//! `float` operations are listed: a widened `half` is never an `f32` denormal, and Metal's `bfloat`
//! and `double` environments are not measured.
use crate::device::DeviceProfile;
use crate::error::DriverDeviation;
use crate::lower::arith::math::FloatFn;
/// Whether profile `p`'s device reads the denormals of the operations [`Covered::Deviation`]
/// names as Metal does: an `f32` denormal operand as the zero of its sign, a denormal result
/// flushed to one (`DriverDeviation::MetalFloatDenormals`, a measured driver fact). Elsewhere
/// they are the device's own (`PrecisionNote::DeviceDenormals`).
pub fn device_flushes(p: &DeviceProfile) -> bool {
p.takes_driver_deviation(DriverDeviation::MetalFloatDenormals)
}
/// Whether profile `p`'s device reads the denormals of the operations [`Covered::Unary`] names as
/// Metal does: a negation and an absolute value keep one, a floor and a ceiling read one as the
/// zero of its sign (`DriverDeviation::MetalUnaryDenormals`, a measured driver fact). Elsewhere
/// they are the device's own (`PrecisionNote::DeviceDenormals`).
pub fn unary_kept(p: &DeviceProfile) -> bool {
p.takes_driver_deviation(DriverDeviation::MetalUnaryDenormals)
}
/// Where an operation the device computes reads its `f32` denormals as Metal does.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Covered {
/// On a device with the measured deviation ([`device_flushes`]); elsewhere they are the
/// device's own.
Deviation,
/// On a device with the measured deviation of the sign moves and the floor and ceiling
/// ([`unary_kept`]); elsewhere they are the device's own. `Floor` and `Ceil` of a denormal
/// give `-1` and `1` on NVIDIA's 615.71.09 and on lavapipe, where Metal reads the operand as a
/// zero (`floor(-2^-149)` is `-0`, `ceil(2^-149)` is `+0`), and RADV and ANV flush a negated
/// one, which Metal keeps.
Unary,
/// On no device measured: the device's own on every profile (a quotient).
Never,
}
impl Covered {
/// Whether a device whose readings `flushes` ([`device_flushes`]) and `unary`
/// ([`unary_kept`]) state reads an operation of this class's denormals as Metal does.
pub fn holds(self, flushes: bool, unary: bool) -> bool {
match self {
Covered::Deviation => flushes,
Covered::Unary => unary,
Covered::Never => false,
}
}
}
/// Whether float function `op` moves its operand's sign bit alone, keeping a denormal where Metal's
/// does on a device measured to ([`Covered::Unary`]): `fabs`. Its notes otherwise follow the
/// device's own functions (`function_notes`).
pub fn moves_sign(op: FloatFn) -> bool {
op == FloatFn::Abs
}
/// Where the device's instruction for float function `op` (on `float` lanes, where the lowering
/// leaves `op` to it) reads `f32` denormals as Metal, which reads each `float` operand of these
/// as the zero of its sign and flushes a denormal result (the denormal probes, `nan_denormals`
/// and `nan_denormals_fast`, every lane). `None` for a function whose lowering reads its
/// denormals as Metal does itself (`FloatFn::metal_denormals`) or whose reading is not measured.
///
/// | function | where the device's reading is Metal's |
/// |---|---|
/// | `floor`, `ceil` | the unary deviation |
/// | `trunc`, `rint` | the deviation |
/// | `sqrt`, `rsqrt`, `fast::rsqrt` | the deviation |
/// | `dot` | the deviation |
/// | `fma`, `llvm.fmuladd` (`OpFmaKHR`) | the deviation |
/// | `fast::atan2` | the deviation |
/// | `ldexp` on `float` | the deviation |
/// Whether Metal's reading of the `f32` denormals of float function `op` (on `float` lanes, where
/// the lowering leaves `op` to the device's instruction) is measured: Metal reads each `float`
/// operand of these as the zero of its sign and flushes a denormal result (the denormal probes,
/// `nan_denormals` and `nan_denormals_fast`, every lane), where the device's reading is its own,
/// noted `DeviceDenormals`. False for a function whose lowering reads its denormals as Metal does
/// itself (`FloatFn::metal_denormals`) or whose reading is not measured. The functions: `floor`,
/// `ceil`, `trunc`, `rint`, `sqrt`, `rsqrt`, `fast::rsqrt`, `dot`, `fma` and `llvm.fmuladd`
/// (`OpFmaKHR`), `fast::atan2`, and `ldexp` on `float`.
///
/// `fast::atan2(y, x)` reads a denormal `y` or `x` as the zero of its sign and answers no denormal
/// (an Apple M3 Max under macOS 27.0.1: every pair of 28 patterns, in entries with and without fast
@@ -84,26 +22,27 @@ pub fn moves_sign(op: FloatFn) -> bool {
/// past `2^126`; a denormal quotient reaches the fast `atan`, which reads it as a zero.
///
/// `ldexp` on `float` (`math::ldexp_bits`) reads a denormal operand and rounds a result below
/// `2^-126` by the device's `float` multiply, which the deviation covers: a denormal operand times
/// `2^-126` by the device's `float` multiply: a denormal operand times
/// `2^64`, and a normal times `2^-126`.
///
/// `trunc` and `rint` (`Trunc`, `RoundEven`) of a denormal answer the zero of its sign on every
/// venue measured, as Metal does (the probes' words, both modes, all seven venues), but Vulkan
/// states no sign for a flushed denormal, so only the deviation covers them.
pub fn coverage(op: FloatFn) -> Option<Covered> {
/// states no sign for a flushed denormal, so the device's is noted.
pub fn covered(op: FloatFn) -> bool {
use FloatFn as F;
Some(match op {
F::Floor | F::Ceil => Covered::Unary,
F::Trunc
| F::Rint
| F::Sqrt
| F::Rsqrt
| F::FastRsqrt
| F::Dot
| F::Fma
| F::MulAdd
| F::FastAtan2 { .. }
| F::Ldexp => Covered::Deviation,
_ => return None,
})
matches!(
op,
F::Floor
| F::Ceil
| F::Trunc
| F::Rint
| F::Sqrt
| F::Rsqrt
| F::FastRsqrt
| F::Dot
| F::Fma
| F::MulAdd
| F::FastAtan2 { .. }
| F::Ldexp
)
}
+27 -135
View File
@@ -14,16 +14,11 @@
//! (`PrecisionNote::NativeTranscendentals`). No routine computes Metal's answer where the device
//! 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.
//! values `GLSL.std.450` leaves undefined, by the device's comparisons.
//!
//! Precise `fmod` keeps its routine: the device's form, `OpFRem` (`x - y · trunc(x / y)` at the
//! device's precision), Vulkan leaves unbounded once the quotient passes `2^24`, where Metal's is
//! exact. Where the device is Metal's own, a precise module's `OpFRem` is Metal's `fmod`, and takes
//! no routine ([`Fun::device_answers`]).
//! exact.
pub(crate) mod fmod;
@@ -39,36 +34,17 @@ use crate::spirv::ir::{BinOp, Contraction, ConvOp, Type};
/// The quiet NaN Metal answers at precise `fmod`'s domain errors ([`E::metal_nan`]).
pub(crate) const METAL_NAN: u32 = 0x7FC0_0000;
/// A math mode: Metal's precise functions (MSL Table 8.1) or its fast ones (Table 8.2).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Mode {
Precise,
Fast,
}
/// The mode Metal compiles the `float` functions of an entry in on a device whose functions are
/// Metal's (MoltenVK: `MVKDevice::getMTLCompileOptions` under its default on-demand fast math):
/// precise where the entry declares a `SignedZeroInfNanPreserve` execution mode of any width
/// (`declared`, the widths [`super::ArithPlan::modes`] holds), fast otherwise.
pub fn module_mode(declared: &std::collections::BTreeSet<u8>) -> Mode {
if declared.is_empty() {
Mode::Fast
} else {
Mode::Precise
}
}
/// A function of Metal's math library on `float` operands, as a call of a float function takes it
/// ([`uses`]): one whose answer the device's instruction may give otherwise than Metal, beyond
/// Vulkan's precision table, or a part of one.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Fun {
/// Metal's `atan` in a mode: within 5 ulp in both (Tables 8.1 and 8.2).
Atan(Mode),
/// Metal's `asin` in a mode: within 4 ulp precise, 5 fast.
Asin(Mode),
/// Metal's `acos` in a mode: within 4 ulp precise, 5 fast.
Acos(Mode),
/// Metal's `atan`, precise or fast: within 5 ulp in both (Tables 8.1 and 8.2).
Atan,
/// Metal's `asin`, precise or fast: within 4 ulp precise, 5 fast.
Asin,
/// Metal's `acos`, precise or fast: within 4 ulp precise, 5 fast.
Acos,
/// The generic part of Metal's precise `atan2(y, x)` (within 6 ulp): finite nonzero normal
/// operands, whose special values `math::atan2_special` answers around it.
Atan2,
@@ -94,13 +70,12 @@ pub enum Fun {
/// 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`]).
SinPi(Mode),
/// fast function is its precise one.
SinPi,
/// Metal's `cospi`, as [`Fun::SinPi`].
CosPi(Mode),
CosPi,
/// Metal's `tanpi`, as [`Fun::SinPi`].
TanPi(Mode),
TanPi,
/// Metal's precise `sqrt`: correctly rounded (MSL Tables 8.1 and 8.3).
Sqrt,
/// Metal's precise `rsqrt`: correctly rounded (Tables 8.1 and 8.3).
@@ -174,88 +149,6 @@ pub enum Fun {
}
impl Fun {
/// Whether a device whose `float` functions are Metal's answers `self` with its own
/// instruction as Metal's function in an entry whose functions Metal compiles in mode
/// `module`: the instruction is Metal's function in that mode, and `atan2` is always the
/// precise one (SPIRV-Cross emits `precise::atan2` whatever the flags). The precise-only
/// functions (`sin`, `cos`, `tan`, `sqrt`, `rsqrt`, and `fmod`, whose fast calls are their own
/// functions) are Metal's only in a precise module. Metal's fast `sin`, `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
/// either mode, within Apple's fast bound (MSL Table 8.2) and off Metal's own form
/// ([`Fun::device_near_equivalent`]).
///
/// `exp2` and `log2` are Metal's in either mode (Metal's fast ones are its precise ones), and
/// so is `tanh` (SPIRV-Cross emits `precise::tanh` whatever the flags); `powr` and the other
/// hyperbolic functions, `exp` and `log` only in a precise module. No `GLSL.std.450`
/// instruction reaches Metal's `exp10` and `log10`, but Metal's own compositions of its `exp2`
/// and `log2` do, in either mode (`math::exp10`, `math::log10`). Its reciprocal is the
/// device's `1 / y` in a fast-math module, where Metal
/// compiles the division with its fast reciprocal, and not in a precise one, whose quotient is
/// correctly rounded. The device's instruction on a `half` held as `float` is its `float`
/// function, never Metal's `half` form.
pub fn device_answers(self, module: Mode) -> bool {
match self {
Fun::FastSin
| Fun::FastCos
| 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
| Fun::Cos
| Fun::Tan
| Fun::Sqrt
| Fun::Rsqrt
| Fun::Fmod
| Fun::Powr
| Fun::Exp
| Fun::Log
| Fun::Sinh
| Fun::Cosh
| Fun::Asinh
| Fun::Acosh
| Fun::Atanh => module == Mode::Precise,
// Metal's fast `asinh` and `acosh` are the device's `Asinh` and `Acosh` in a fast-math
// module.
Fun::Recip | Fun::FastAsinh | Fun::FastAcosh => module == Mode::Fast,
Fun::HalfAtan
| Fun::HalfAtan2
| Fun::HalfTan
| Fun::HalfSin
| Fun::HalfCos
| Fun::HalfAsinh
| Fun::HalfExp
| Fun::HalfLog
| Fun::HalfPowr
| Fun::HalfSinh
| Fun::HalfCosh
| Fun::HalfTanh => false,
Fun::Atan2 | Fun::Exp2 | Fun::Log2 | Fun::Tanh | Fun::Exp10 | Fun::Log10 => true,
}
}
/// Whether the device answers the function, where it does ([`Fun::device_answers`]), by a
/// near-equivalent of Metal's function rather than by Metal's function itself: Metal's fast
/// `sinpi`, `cospi`, and `tanpi`, which the device answers by its `Sin` and `Cos` of
/// `float(π) r`, within Apple's fast bound but off Metal's own forms (case f6524207 differs at
/// 175, 102, and 264 of its 1,024 lanes through MoltenVK). Every other function the device
/// answers is Metal's own, word for word (`DriverDeviation::MetalFloatFunctions`).
pub fn device_near_equivalent(self) -> bool {
matches!(
self,
Fun::SinPi(Mode::Fast) | Fun::CosPi(Mode::Fast) | Fun::TanPi(Mode::Fast)
)
}
/// Whether the call takes the device's instruction for the function: every function but
/// precise `fmod`, whose routine computes Metal's exact remainder ([`fmod`]). Its
/// precision is Vulkan's (`PrecisionNote::NativeTranscendentals`).
@@ -264,8 +157,7 @@ impl Fun {
}
/// Whether Metal's answer to the function is the one right value at every operand, so that
/// the routine's answer, and the device's where it is Metal's own ([`Fun::device_answers`]), is
/// Metal's on every device in either math mode: precise `fmod`, which Metal documents exact
/// the routine's answer is Metal's on every device in either math mode: precise `fmod`, which Metal documents exact
/// (MSL Table 8.1 for `float`, Table 8.3 for `half`), and which its routine computes.
pub fn correctly_rounded(self) -> bool {
self == Fun::Fmod
@@ -312,27 +204,27 @@ pub fn uses(op: FloatFn, f: Form) -> &'static [Fun] {
}
}
match crate::lower::arith::math::half_form(op, f) {
FloatFn::Atan => &[Fun::Atan(Mode::Precise)],
FloatFn::FastAtan => &[Fun::Atan(Mode::Fast)],
FloatFn::Asin => &[Fun::Asin(Mode::Precise)],
FloatFn::FastAsin => &[Fun::Asin(Mode::Fast)],
FloatFn::Acos => &[Fun::Acos(Mode::Precise)],
FloatFn::FastAcos => &[Fun::Acos(Mode::Fast)],
FloatFn::Atan => &[Fun::Atan],
FloatFn::FastAtan => &[Fun::Atan],
FloatFn::Asin => &[Fun::Asin],
FloatFn::FastAsin => &[Fun::Asin],
FloatFn::Acos => &[Fun::Acos],
FloatFn::FastAcos => &[Fun::Acos],
FloatFn::Atan2 => &[Fun::Atan2],
// `atan(y · rcp(x))`, Metal's fast `atan` of its fast quotient.
FloatFn::FastAtan2 { .. } => &[Fun::Atan(Mode::Fast), Fun::Recip],
FloatFn::FastAtan2 { .. } => &[Fun::Atan, Fun::Recip],
FloatFn::Sin => &[Fun::Sin],
FloatFn::Cos => &[Fun::Cos],
FloatFn::Tan => &[Fun::Tan],
FloatFn::FastSin => &[Fun::FastSin],
FloatFn::FastCos => &[Fun::FastCos],
FloatFn::FastTan => &[Fun::FastTan],
FloatFn::SinPi => &[Fun::SinPi(Mode::Precise)],
FloatFn::CosPi => &[Fun::CosPi(Mode::Precise)],
FloatFn::TanPi => &[Fun::TanPi(Mode::Precise)],
FloatFn::FastSinPi => &[Fun::SinPi(Mode::Fast)],
FloatFn::FastCosPi => &[Fun::CosPi(Mode::Fast)],
FloatFn::FastTanPi => &[Fun::TanPi(Mode::Fast)],
FloatFn::SinPi => &[Fun::SinPi],
FloatFn::CosPi => &[Fun::CosPi],
FloatFn::TanPi => &[Fun::TanPi],
FloatFn::FastSinPi => &[Fun::SinPi],
FloatFn::FastCosPi => &[Fun::CosPi],
FloatFn::FastTanPi => &[Fun::TanPi],
FloatFn::Sqrt => &[Fun::Sqrt],
FloatFn::Rsqrt => &[Fun::Rsqrt],
FloatFn::Fmod => &[Fun::Fmod],
@@ -405,7 +297,7 @@ impl Lib {
}
/// Metal's precise `fmod` of `x` and `y` (`float` lanes of form `f`) by its routine, one call
/// per lane; `None` where the module takes the device's `OpFRem` ([`Fun::device_answers`]).
/// per lane; `None` where the module defines no routine ([`Lib::instructions`]).
pub fn fmod(
&self,
fb: &mut FunctionBuilder<'_>,
+30 -51
View File
@@ -178,8 +178,8 @@ fn ldexp(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, k: Value) -> BResult<V
/// `x`'s exponent field from 1 to 254, and at 0 and below is the device's product of `x` scaled
/// to the field `max(e + k + 126, 1)` and `2^-126`, which rounds a result below `2^-126` once to a
/// denormal or flushes it as the device does. Metal flushes both a denormal operand and a denormal
/// result: the device's multiply reads them so where it takes `DriverDeviation::MetalFloatDenormals`
/// (`denormal::coverage`); elsewhere they are noted `PrecisionNote::DeviceDenormals`.
/// result: the device's multiply reads them by its own float controls, noted
/// `PrecisionNote::DeviceDenormals` (`denormal::covered`).
fn ldexp_bits(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, k: Value) -> BResult<Value> {
let i = u32_form(f);
let it = ty(fb, i)?;
@@ -784,15 +784,13 @@ pub enum FloatFn {
/// of the `f32` container, so exact for NaNs and zeros on every device. Not on `double`.
CopySign,
// Device precision (`PrecisionNote::DeviceArithmetic`).
/// Metal's precise `sqrt`: correctly rounded (MSL Table 8.1). The device's `Sqrt`, Metal's own
/// where the device's functions are Metal's in a module compiled with precise functions
/// ([`libm`]).
/// Metal's precise `sqrt`: correctly rounded (MSL Table 8.1). The device's `Sqrt`.
Sqrt,
/// `fma` on `double` (`GLSL.std.450 Fma`) and `bfloat` (`narrow::bf16_fma`). `float` and `half`
/// select the correctly rounded [`super::fma`].
Fma,
/// Metal's precise `fmod`: exact (Table 8.1), `fmod(x, ±inf) = x`. On `float` and `half` its
/// routine, but where the device's `OpFRem` is Metal's `fmod` ([`libm::Fun::device_answers`]).
/// routine.
Fmod,
/// `dot`: the device's `OpDot`.
Dot,
@@ -830,27 +828,21 @@ pub enum FloatFn {
/// `air.fast_log10` on `float`: `log2(x) · log10(2)` (MSL Table 8.2), the product rounded:
/// every lane of case f6524207.
FastLog10,
/// Metal's precise `sin`: within 4 ulp (MSL Table 8.1). The device's instruction, Metal's own
/// where the device's functions are Metal's in a module compiled with precise functions
/// ([`libm`]).
/// Metal's precise `sin`: within 4 ulp (MSL Table 8.1). The device's instruction.
Sin,
/// Metal's precise `cos`: within 4 ulp; as [`FloatFn::Sin`].
Cos,
/// `air.fast_sin` on `float`: the device's `Sin`, Metal's `fast::sin` itself where its
/// functions are Metal's in a fast-math module. Metal answers `+0` past `float(π/2) · 2^22` and
/// `air.fast_sin` on `float`: the device's `Sin`. Metal answers `+0` past `float(π/2) · 2^22` and
/// for an infinity or NaN; the device answers its `Sin` there.
FastSin,
/// `air.fast_cos` on `float`: the device's `Cos`; as [`FloatFn::FastSin`].
FastCos,
/// Metal's precise `tan`: within 6 ulp; as [`FloatFn::Sin`].
Tan,
/// `air.fast_tan` on `float`: the device's `Tan`, Metal's `fast::tan` itself where its
/// functions are Metal's in a fast-math module (MSL Table 8.2 defines it as `sin(x) · (1 /
/// cos(x))`).
/// `air.fast_tan` on `float`: the device's `Tan` (MSL Table 8.2 defines Metal's as `sin(x) · (1
/// / cos(x))`).
FastTan,
/// Metal's precise `asin`: within 4 ulp (MSL Table 8.1). The device's instruction, Metal's own
/// where the device's functions are Metal's in a module compiled with precise functions
/// ([`libm`]).
/// Metal's precise `asin`: within 4 ulp (MSL Table 8.1). The device's instruction.
Asin,
/// `air.fast_asin` on `float`: within 5 ulp (Table 8.2); as [`FloatFn::Asin`], in Metal's
/// fast mode.
@@ -865,29 +857,25 @@ pub enum FloatFn {
FastAtan,
/// Metal's precise `sinh`; as [`FloatFn::Exp`].
Sinh,
/// `air.fast_sinh` on `float`: the device's `Sinh`, Metal's `fast::sinh` itself where its
/// functions are Metal's in a fast-math module (MSL Table 8.2 defines it as
/// `air.fast_sinh` on `float`: the device's `Sinh` (MSL Table 8.2 defines Metal's as
/// `(exp(x) - exp(-x)) · 0.5`).
FastSinh,
/// Metal's precise `cosh`; as [`FloatFn::Exp`].
Cosh,
/// `air.fast_cosh` on `float`: the device's `Cosh`; as [`FloatFn::FastSinh`].
FastCosh,
/// Metal's precise `tanh` (within 5 ulp): the device's instruction, Metal's own where its
/// functions are Metal's (SPIRV-Cross emits `precise::tanh` in either mode).
/// Metal's precise `tanh` (within 5 ulp): the device's instruction.
Tanh,
/// `air.fast_tanh` on `float`: the device's `Tanh`. MSL Table 8.2 defines Metal's as the
/// formula `(t - 1) / (t + 1)` with `t = exp(2x)`, which is `NaN` once `t` overflows, where the
/// device's `Tanh` answers `±1`; on a device whose functions are Metal's the instruction is
/// Metal's precise `tanh`. Narrow forms keep [`FloatFn::Tanh`]: the fast-math table is the
/// device's `Tanh` answers `±1`. Narrow forms keep [`FloatFn::Tanh`]: the fast-math table is the
/// single-precision one.
FastTanh,
/// Metal's precise `asinh`; as [`FloatFn::Exp`].
Asinh,
/// `air.fast_asinh` on `float` with every flag: Metal's fast formula
/// `log(x + sqrt(x * x + 1))` (MSL Table 8.2), which is the canonical NaN at `-inf`
/// (`-inf + inf`): the device's `Asinh`, Metal's own in a fast-math module where its functions
/// are Metal's.
/// (`-inf + inf`): the device's `Asinh`.
FastAsinh,
/// Metal's precise `acosh`; as [`FloatFn::Exp`].
Acosh,
@@ -895,8 +883,7 @@ pub enum FloatFn {
FastAcosh,
/// Metal's precise `atanh`; as [`FloatFn::Exp`].
Atanh,
/// `air.fast_atanh` on `float`: the device's `Atanh`, Metal's `fast::atanh` itself where its
/// functions are Metal's in a fast-math module (MSL Table 8.2 defines it as
/// `air.fast_atanh` on `float`: the device's `Atanh` (MSL Table 8.2 defines Metal's as
/// `0.5 · log((1 + x) / (1 - x))`).
FastAtanh,
/// Metal's `sinpi`: within 4 ulp (MSL Table 8.1). The exact reduction around the device's `Sin`
@@ -924,7 +911,7 @@ pub enum FloatFn {
/// Metal composes it.
FastPow,
/// Metal `atan2(y, x)`: C99 Annex F's special values (`atan2_special`) around the generic
/// value, the device's `Atan2` (always `precise::atan2` where its functions are Metal's).
/// value, the device's `Atan2`.
Atan2,
/// `air.fast_atan2` on `float`: `atan(y / x)` turned by `±π` when `x` is below zero, MSL Table
/// 8.2's formula (`fast_atan2`): `0 / 0` and `inf / inf` are NaN, where `atan2` answers C99's
@@ -1038,21 +1025,20 @@ impl FloatFn {
/// the device's denormal mode, or records the device's answer under another note, so it records
/// no `PrecisionNote::DeviceDenormals` of its own: `copysign`, which moves bits, and precise
/// `fmod` on `float`, the remainder's routine, which reads a denormal divisor as a zero on the
/// bits and computes the remainder in integers (`libm::fmod`), or on MoltenVK Metal's own;
/// bits and computes the remainder in integers (`libm::fmod`);
/// `fmin`, `fmax`, `min3`, `max3`, `clamp`, `saturate` and `median3`, the device's `NMin`,
/// `NMax` and `NClamp`, whose comparison of a denormal is Metal's where measured
/// (`DriverDeviation::MetalMinMax`, but in `median3`) and else `PrecisionNote::NativeMinMax`'s
/// `NMax` and `NClamp`, whose comparison of a denormal is within `PrecisionNote::NativeMinMax`'s
/// bound; `round`,
/// whose every denormal operand rounds to a zero, its sign the note's
/// (`PrecisionNote::NativeTranscendentals`); and the device's instructions for Metal's
/// functions: `fabs`, `sign`, `fract` and `fast::sqrt` ([`FloatFn::native_instruction`]), the
/// trigonometric, hyperbolic and arc families in both modes, `sinpi`, `cospi`, and `tanpi`,
/// the exponentials and logarithms, and `pow`, `powr` and `atan2` with their special cases
/// (the device's comparisons around the device's instruction), Metal's own where the device's
/// functions are Metal's, and elsewhere recording the device's denormals with their precision
/// (the device's comparisons around the device's instruction), recording the device's
/// denormals with their precision
/// (`PrecisionNote::NativeTranscendentals`). `fast::atan2` does not: its quotient is the
/// device's division or its product with the device's reciprocal, whose operands and
/// reciprocal `denormal::coverage` reads.
/// reciprocal `denormal::covered` reads.
pub fn metal_denormals(self) -> bool {
use FloatFn as F;
matches!(
@@ -1120,9 +1106,7 @@ impl FloatFn {
}
/// Whether the call takes the device's instruction for one of Metal's functions that no
/// `libm::Fun` names, which is Metal's own function where the device's functions are Metal's
/// (SPIRV-Cross writes Metal's `fabs`, `sign`, `fract` and `sqrt`), and elsewhere answers its
/// special operands as the device does: `fabs` (`FAbs`), `sign` (`FSign`), `fract` and
/// `libm::Fun` names, which answers its special operands as the device does: `fabs` (`FAbs`), `sign` (`FSign`), `fract` and
/// `fast::fract` (`Fract`), and `fast::sqrt` (`Sqrt`, where Metal's is `x · rsqrt(x)`).
pub fn native_instruction(self) -> bool {
matches!(
@@ -1142,8 +1126,7 @@ impl FloatFn {
/// Whether a `half` call on form `f` answers a zero remainder of a nonzero dividend with its
/// `float` function's sign where Metal's `half` function answers another, on every device:
/// `fmod`, whose `float` remainder (the exact remainder's routine, or the device's where its
/// functions are Metal's) keeps the dividend's sign, as C's does, where Metal's `half` `fmod`
/// `fmod`, whose `float` remainder (the exact remainder's routine) keeps the dividend's sign, as C's does, where Metal's `half` `fmod`
/// answers `+0` (`fmod(-2, 0.5)`; `nan_fmod_zero`, `nan_fmod_zero_fast`, with and without
/// fast-math flags) (`PrecisionNote::NativeTranscendentals`).
pub fn half_zero_of_float(self, f: Form) -> bool {
@@ -1174,7 +1157,7 @@ impl FloatFn {
/// Whether the function divides by a device division besides its [`FloatFn::precision`]
/// class (`PrecisionNote::DeviceArithmetic`): `fast_atan2`'s `y / x` (the device's division)
/// and `fast::tanpi`'s quotient where the device's functions are Metal's.
/// and `fast::tanpi`'s quotient.
pub fn divides(self) -> bool {
matches!(self, FloatFn::FastAtan2 { .. } | FloatFn::FastTanPi)
}
@@ -1394,9 +1377,8 @@ fn float_fn_core(
F::Fract => fract_below_one(fb, f, a),
F::FastFract => g1(fb, GlslOp::Fract),
F::Sign => g1(fb, GlslOp::FSign),
// Metal's `clamp(x, +0, 1)`: the device's `NClamp`, Metal's where measured
// (`DriverDeviation::MetalMinMax`), else noted `PrecisionNote::NativeMinMax`, as the
// minimum and maximum functions below.
// Metal's `clamp(x, +0, 1)`: the device's `NClamp`, noted `PrecisionNote::NativeMinMax`, as
// the minimum and maximum functions below.
F::Saturate => {
let (z, one) = (fsplat(fb, f, 0.0)?, fsplat(fb, f, 1.0)?);
glsl(fb, GlslOp::NClamp, &[a, z, one])
@@ -1486,8 +1468,7 @@ fn float_fn_core(
let c = wide_splat(fb, f, k)?;
fb.binary_with(BinOp::FMul, l, c, Contraction::Forbidden)
}
// The device's instructions in both modes, Metal's fast functions where its functions are
// Metal's in a fast-math module (`libm::Fun::device_answers`).
// The device's instructions in both modes.
F::Sin | F::FastSin => g1(fb, GlslOp::Sin),
F::Cos | F::FastCos => g1(fb, GlslOp::Cos),
F::Tan | F::FastTan => g1(fb, GlslOp::Tan),
@@ -1755,8 +1736,7 @@ pub(super) fn fast_powr_special(
/// one, as Metal defines it (`fmin(x - floor(x), 0x1.fffffep-1)`): the largest value below one of
/// the format wherever the difference reaches one (`-1e-10` gives `1 - 2^-24`, not `1`). The
/// bound is an ordered comparison, so a NaN `Fract` is kept, the device's NaN. An infinity, a NaN
/// and an `f32` denormal answer as the device's `Fract` does (`PrecisionNote::NativeTranscendentals`
/// off Metal's own functions).
/// and an `f32` denormal answer as the device's `Fract` does (`PrecisionNote::NativeTranscendentals`).
fn fract_below_one(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult<Value> {
// `floor(x)` of a narrow value is a value of the format: the difference takes the device's
// rounding.
@@ -1859,8 +1839,7 @@ pub(super) type QuotientOf<'a> =
/// `quotient`'s, the device's `OpFDiv`. For a normal `x` no operand of it is a denormal: a nonzero
/// `sinpi` is at least `π 2^-126` in magnitude (`r` is `x` below 1, and a multiple of `2^-23`
/// above); a denormal `x` reaches the first multiply and difference, which read it as the device
/// does: Metal's reading where the profile's functions are Metal's (the deviation, or flushed
/// before), the device's under native device maths (`PrecisionNote::DeviceDenormals`). At a
/// does, under native device maths (`PrecisionNote::DeviceDenormals`). At a
/// quarter turn (`r = ±1/4`, exact like every step before the multiply) the two arms are the sine
/// and cosine of `π/4`, equal in magnitude, so `tanpi` is exactly `±1` with the quotient's sign,
/// whatever the device's `Sin` and `Cos` round them to (on lavapipe they differ by one ulp, and the
@@ -2236,7 +2215,7 @@ pub(super) type AtanOf<'a> = &'a dyn Fn(&mut FunctionBuilder<'_>, Value) -> BRes
/// `atan2` answers `-π`), and `fast::atan2(1, -0)` is `-π/2`.
///
/// Zeros are the device's comparisons, so an `f32` denormal operand is a zero where the device
/// reads it so (`denormal::coverage`), and a denormal quotient is the device's `Atan` of it.
/// reads it so (`denormal::covered`), and a denormal quotient is the device's `Atan` of it.
///
/// The quotient follows the call's fast-math flags. A call that carries every flag (case
/// c11eb8cb, compiled with fast math) divides over the whole range (`fast::atan2(FLT_MAX,
@@ -2245,7 +2224,7 @@ pub(super) type AtanOf<'a> = &'a dyn Fn(&mut FunctionBuilder<'_>, Value) -> BRes
/// `OpFDiv` bound their error. Any other call (`by_reciprocal`; case 6802ab13, compiled without
/// fast math, measured with no flag) multiplies `y` by the device's reciprocal of `x`, as Metal
/// composes it. Beyond `2^126` that reciprocal is an `f32` denormal, the device's to keep or
/// flush (`denormal::coverage`): Metal flushes it, so its quotient is the signed zero, or NaN for
/// flush (`denormal::covered`): Metal flushes it, so its quotient is the signed zero, or NaN for
/// an infinite `y` (`fast::atan2(FLT_MAX, FLT_MAX)` is `+0`, `fast::atan2(inf, FLT_MAX)` is NaN),
/// and so is the device's where it flushes; a device that keeps it answers `atan` of the product
/// (`±π/2` for an infinite `y`). A quotient the device's product makes NaN (an infinite `y` times
File diff suppressed because it is too large. Load diff
+2 -39
View File
@@ -20,10 +20,7 @@
//! these classes.
//!
//! The module leaves every NaN's bits to the device, and records
//! `PrecisionNote::NativeNanEncoding` where Metal answers a NaN the device is not measured to
//! answer: every answer these tables give, but the canonical class of the arithmetic on a device
//! measured to answer Metal's canonical NaN ([`NanEncoding::MetalCanonical`],
//! [`NanAnswer::device_answers`]).
//! `PrecisionNote::NativeNanEncoding` where Metal answers a NaN: every answer these tables give.
//!
//! [`is_nan`] tests a value for a NaN, by `OpIsNan` where the entry declares
//! `SignedZeroInfNanPreserve` for the width, without which a device may assume that no operand is a
@@ -31,8 +28,6 @@
//! float mode reaches: the conversions and functions whose answer at a NaN is a number test so.
use crate::air::ir::{BinOp as AirBin, CastOp, FastMath};
use crate::device::profile::NanEncoding;
use crate::device::DeviceProfile;
use crate::lower::arith::legal::{FloatFmt, Form, Held};
use crate::lower::arith::math::FloatFn;
use crate::lower::arith::narrow::u32_form;
@@ -51,9 +46,7 @@ pub enum NanAnswer {
/// `0x7FC00000` for a result the device computes exactly, passing its operand's NaN on: the
/// widening of a `half` to `float`, which a `half` held widened leaves no device operation at
/// all, and `half` `fneg` and `fabs`, which a device computes on the sign alone. No device's
/// arithmetic answers it, so the canonical-NaN fact does not leave it to the device; where the
/// device's moves of a NaN are measured ([`moves_answered`]), the held `half` is its widening's
/// canonical NaN, so the widening and `fabs` answer it.
/// arithmetic answers it, so it is noted on every device.
CanonicalExact,
/// The canonical NaN with a NaN first operand's sign, and `+` for a NaN of another origin (a
/// domain error): precise `asin`, `atan`, `asinh`, `atanh`.
@@ -71,20 +64,6 @@ pub enum NanAnswer {
BaseToExponentOne,
}
impl NanAnswer {
/// Whether the device is measured to answer this NaN under `encoding`: on a device whose
/// arithmetic answers Metal's canonical NaN ([`NanEncoding::MetalCanonical`]) the canonical
/// class of the arithmetic, which the device fact covers, and not
/// [`NanAnswer::CanonicalExact`]; nothing on another ([`NanEncoding::Native`]). The device's
/// NaN of an answer it is not measured to give is noted `PrecisionNote::NativeNanEncoding`.
pub fn device_answers(self, encoding: NanEncoding) -> bool {
match encoding {
NanEncoding::MetalCanonical => self == NanAnswer::Canonical,
NanEncoding::Native => false,
}
}
}
/// How [`is_nan`] tests a value for a NaN.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NanTest {
@@ -460,19 +439,3 @@ fn flagged_precise(op: FloatFn) -> bool {
F::Sin | F::Cos | F::Tan | F::Asin | F::Acos | F::Atan | F::Asinh | F::Atanh | F::Atan2
)
}
/// The profile's NaN encoding.
pub fn encoding(p: &DeviceProfile) -> NanEncoding {
p.fields().nan_encoding
}
/// Whether profile `p`'s device is measured to answer Metal's NaN where an operation moves a NaN
/// rather than computes one (`DriverDeviation::MetalNanMoves`): its widening of a `half` to
/// `float` ([`NanAnswer::CanonicalExact`]), its `float` `fneg` and `fabs`
/// ([`NanAnswer::Operand`]) and its `half` `fabs` ([`NanAnswer::CanonicalExact`]), each where the
/// module moves its `half` values only as measured (`narrow::moves_unfolded`). A `half` `fneg`,
/// whose held result keeps the operand's NaN with its sign flipped unless the driver's compiler
/// moves the negation onto the `half`, is not among them.
pub fn moves_answered(p: &DeviceProfile) -> bool {
p.takes_driver_deviation(crate::error::DriverDeviation::MetalNanMoves)
}
+19 -379
View File
@@ -21,8 +21,7 @@
//! exact integer round-to-nearest-even of the `f32` bits. Where the device's 16-bit `+ - *`, kept
//! apart, is Metal's `half` arithmetic and the profile has `shaderFloat16`, a `half` `+ - *` is
//! that instruction between exact conversions instead, with no rounding here (`ops::f16_binary`):
//! where it is measured to be (`DriverDeviation::MetalHalfArithmetic`), and under those float
//! controls ([`half_controls`]), which make it so by the Vulkan spec and which the entry then
//! under those float controls ([`half_controls`]), which make it so by the Vulkan spec and which the entry then
//! declares ([`computes_in_16_bits`]), on a driver that folds the conversion's round trip too
//! (NVIDIA's: the fold is the pair's, a 16-bit instruction keeps its rounding); there the emitted
//! module holds every exact `half` at 16 bits, its moves, minimums, maximums and clamps, its
@@ -54,8 +53,6 @@
//! `f32` ([`f64_to_f32_odd`]), and a `bfloat` fused multiply-add corrects its one inexact case
//! ([`bf16_fma`]), so the final rounding is the only one that counts.
mod merges;
use crate::budget::Meter;
use crate::device::profile::Independence;
use crate::device::DeviceProfile;
@@ -67,8 +64,8 @@ use crate::spirv::builder::{FunctionBuilder, NarrowFmt, QuantizeForm};
use crate::spirv::error::{BResult, BuildError, TypeRule};
use crate::spirv::ids::Value;
use crate::spirv::ir::{
BinOp, ConstBits, ConstKind, Constant, ConvOp, ExecMode, GlslOp, Inst, StorageClass,
Terminator, Type, TypedModule, UnOp, ValueOrigin,
BinOp, ConstBits, ConstKind, Constant, ConvOp, ExecMode, GlslOp, Inst, Type, TypedModule, UnOp,
ValueOrigin,
};
/// The unsigned 32-bit integer form with `f`'s lanes.
@@ -179,11 +176,6 @@ pub fn native_rounding(form: QuantizeForm) -> Option<PrecisionNote> {
/// rounded at all (the note's stated bound), and the store's conversion to bits rounds it
/// ([`converted_bits`]).
fn converted(fb: &mut FunctionBuilder<'_>, wide: Form, x: Value) -> BResult<Value> {
converted_pair(fb, wide, x).map(|(_, w)| w)
}
/// [`converted`]'s pair: the narrowing to 16 bits and its widening back.
fn converted_pair(fb: &mut FunctionBuilder<'_>, wide: Form, x: Value) -> BResult<(Value, Value)> {
let e = fb.module().ty(Type::Float { width: 16 })?;
let h = match wide.lanes {
1 => e,
@@ -191,26 +183,7 @@ fn converted_pair(fb: &mut FunctionBuilder<'_>, wide: Form, x: Value) -> BResult
};
let w = ty(fb, wide)?;
let n = fb.convert(ConvOp::FConvert, x, h)?;
Ok((n, fb.convert(ConvOp::FConvert, n, w)?))
}
/// [`round`] of a `float` the function holds to `half` (an AIR `fptrunc` or `air.convert` of a
/// `float`, [`resize`], and a texel's value, [`round_texel`]): the conversion Metal's compiler
/// compiles from the AIR's own, which
/// `DriverDeviation::MetalHalfConversion` measures to be Metal's `half(float)` whatever computed
/// the `float` ([`rounds_unmeasured`]). In [`QuantizeForm::Converted`] the pair's narrowing is
/// recorded as measured (`ModuleBuilder::note_measured_rounding`); every other form rounds as
/// [`round`] does. A `half` an operation or a function computes in `float` is not this form:
/// Metal computes it otherwise (its `half` `tanh`), and it takes [`round`].
pub fn round_measured(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult<Value> {
match (f.held, fb.module().quantize_form()) {
(Held::Float(FloatFmt::Half), QuantizeForm::Converted) => {
let (n, w) = converted_pair(fb, f.with(Held::Float(FloatFmt::F32)), x)?;
fb.module().note_measured_rounding(n);
Ok(w)
}
_ => round(fb, f, x),
}
fb.convert(ConvOp::FConvert, n, w)
}
/// `x` (`f32` lanes of form `wide`) rounded to `half` by the device's conversion to 16 bits and
@@ -349,112 +322,6 @@ pub fn rounds_by_conversion(m: &TypedModule, meter: &mut Meter) -> Result<bool,
Ok(found)
}
/// Whether module `m` rounds a `half` through [`converted`] in a form
/// `DriverDeviation::MetalHalfConversion` does not measure: a conversion pair (an `OpFConvert` of
/// an `f32` to 16 bits whose result another widens back, as [`rounds_by_conversion`] finds them)
/// whose narrowing is neither recorded as measured ([`round_measured`], [`round_texel`]) nor of a
/// texel an image instruction hands back. A texel's pair is one whose `f32` is an image read, fetch, sample or
/// gather's result (or a member of a sparse one's), or a parameter of a function every call of
/// which passes such a texel there (the `half` texel routine, `texture::half`): Metal's compiler
/// folds such a conversion into the image instruction, whose `half` is Metal's own. One pass over
/// the instructions to find each value's definition, two over the conversions, and one over the
/// calls of each routine a pair narrows a parameter of, with a word and a bit per value of the
/// module charged to `meter` while they run.
pub fn rounds_unmeasured(m: &TypedModule, meter: &mut Meter) -> Result<bool, Error> {
let width = |v: Value| -> Option<u8> {
let ty = m.value(v).ok()?.ty;
let ty = match m.types().get(ty).ok()? {
Type::Vector { elem, .. } => *elem,
_ => ty,
};
match m.types().get(ty).ok()? {
Type::Float { width } => Some(*width),
_ => None,
}
};
let words = m.values().len().div_ceil(64);
let bytes = 8 * m.values().len() + 8 * words;
meter.charge(bytes)?;
// Each instruction result's definition.
let mut def: Vec<Option<&Inst>> = vec![None; m.values().len()];
for n in m.blocks().iter().flat_map(|b| &b.insts) {
if let Some(slot) = n.result.and_then(|r| def.get_mut(r.index())) {
*slot = Some(&n.inst);
}
}
let image = |v: Value| -> bool {
let at = |v: Value| def.get(v.index()).copied().flatten();
let direct = |i: Option<&Inst>| {
matches!(
i,
Some(
Inst::ImageFetch { .. }
| Inst::ImageRead { .. }
| Inst::ImageSample { .. }
| Inst::ImageGather { .. }
| Inst::ImageDrefGather { .. }
)
)
};
match at(v) {
Some(Inst::CompositeExtract { composite, .. }) => direct(at(*composite)),
i => direct(i),
}
};
let texel = |v: Value| -> bool {
if image(v) {
return true;
}
let Ok(ValueOrigin::Param { func, index }) = m.value(v).map(|d| d.origin) else {
return false;
};
let mut calls = m
.blocks()
.iter()
.flat_map(|b| &b.insts)
.filter_map(|n| match &n.inst {
Inst::Call { func: f, args } if *f == func => Some(args),
_ => None,
})
.peekable();
calls.peek().is_some()
&& calls.all(|args| args.get(index as usize).is_some_and(|&a| image(a)))
};
let fconverts = || {
m.blocks()
.iter()
.flat_map(|b| &b.insts)
.filter_map(|n| match (&n.inst, n.result) {
(
Inst::Convert {
op: ConvOp::FConvert,
a,
..
},
Some(r),
) => Some((*a, r)),
_ => None,
})
};
// The narrowings some conversion widens back.
let mut widened = vec![0u64; words];
for (a, r) in fconverts() {
if width(a) == Some(16) && width(r) == Some(32) {
set_bit(&mut widened, a);
}
}
let found = fconverts().any(|(a, r)| {
width(a) == Some(32)
&& width(r) == Some(16)
&& has_bit(&widened, r)
&& !m.measured_roundings().contains(&r)
&& !texel(a)
});
drop((def, widened));
meter.release(bytes);
Ok(found)
}
/// An upper estimate of the SPIR-V words of one [`round_texel`] on form `f`: [`round`]'s, and the
/// NaN test's four instructions with their two constants.
pub fn round_texel_words(f: Form) -> u32 {
@@ -479,25 +346,21 @@ pub fn round_texel_words(f: Form) -> u32 {
/// conversion keeps a NaN a NaN, its bits the device's, as the texel's decode is
/// (`PrecisionNote::DeviceNanEncoding`, which the access records). Another form is [`round`]ed.
///
/// A `half` texel rounds as [`round_measured`] rounds a `float` the function holds: in
/// [`QuantizeForm::Converted`] the pair's narrowing is recorded as measured
/// (`ModuleBuilder::note_measured_rounding`), the device's conversion of the texel's `f32` value,
/// which `DriverDeviation::MetalHalfConversion` measures to be Metal's `half(float)` whatever
/// computed it, so the module records no `PrecisionNote::NativeHalfConversion` for it there. That
/// holds for a texel the module decodes itself (`extended_range::decode`) and for a merge of texels
/// (a heap read's phi of its fetch and its decode routine's texel) as for an image instruction's.
/// Where Metal's `half` texel is not that rounding of the texel's value, the access records its
/// A `half` texel rounds as [`round`] rounds a `float` the function holds, in
/// [`QuantizeForm::Converted`] by the device's conversion of the texel's `f32` value, which the
/// module records as `PrecisionNote::NativeHalfConversion`. That holds for a texel the module
/// decodes itself (`extended_range::decode`) and for a merge of texels (a heap read's phi of its
/// fetch and its decode routine's texel) as for an image instruction's. Where Metal's `half` texel
/// is not that rounding of the texel's value, the access records its
/// own note: `PrecisionNote::HalfTexelConversion` (by the bound class at a slot; outright for a
/// heap element and a depth texture) or, for a decoded texel, `PrecisionNote::DevicePackConversion`
/// (whose bound states the `half`'s narrowing against Metal's rounding with ties away from zero).
pub fn round_texel(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult<Value> {
let native = fb.module().native_half();
match f.held {
Held::Float(FloatFmt::Half) if native || fb.module().native_half_nans() => {
round_measured(fb, f, x)
}
Held::Float(FloatFmt::Half) if native || fb.module().native_half_nans() => round(fb, f, x),
Held::Float(FloatFmt::Half) => {
let r = round_measured(fb, f, x)?;
let r = round(fb, f, x)?;
let u = u32_form(f);
let ut = ty(fb, u)?;
let b = fb.convert(ConvOp::Bitcast, x, ut)?;
@@ -947,9 +810,7 @@ fn encode(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult<Value> {
/// device's (the SPIR-V spec's `SignedZeroInfNanPreserve`: "Bit patterns for NaNs might not be
/// preserved"), where Metal moves a `half` NaN with its bits, and a denormal, which the device may
/// flush to the zero of its sign without `DenormPreserve` for 16 bits: kept under the float
/// controls ([`QuantizeForm::Controlled`], [`controlled_modes`]), measured kept on MoltenVK
/// (`DriverDeviation::MetalHalfArithmetic`, whose measurement narrows every `half`), and elsewhere
/// within `PrecisionNote::NativeHalfConversion`'s bound; the module records
/// controls ([`QuantizeForm::Controlled`], [`controlled_modes`]), and elsewhere within `PrecisionNote::NativeHalfConversion`'s bound; the module records
/// `PrecisionNote::NativeNanEncoding` ([`encodes_bits`]). A value that is no `half` value (under
/// native half rounding the device's compiler may fold [`converted`]'s pair and hand `x` on
/// unrounded, as NVIDIA's and lavapipe's do) takes the device's rounding, within
@@ -1046,8 +907,7 @@ fn packed_bits(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult<Value
/// widening does the other way, with the same notes: the module records
/// `PrecisionNote::NativeNanEncoding` (a NaN's bits the device's); under the float controls
/// ([`QuantizeForm::Controlled`]) its entry declares [`controlled_modes`], and elsewhere its
/// denormals are the measured fact's (`DriverDeviation::MetalHalfArithmetic`) or the device's
/// (`PrecisionNote::NativeHalfConversion`). At most three passes over the instructions, with two
/// denormals are the device's (`PrecisionNote::NativeHalfConversion`). At most three passes over the instructions, with two
/// bits per value of the module charged to `meter` while they run.
pub fn encodes_bits(m: &TypedModule, meter: &mut Meter) -> Result<bool, Error> {
let packs = m.blocks().iter().flat_map(|b| &b.insts).any(|n| {
@@ -1418,9 +1278,8 @@ fn unpacked_from_bits(fb: &mut FunctionBuilder<'_>, f: Form, h: Value) -> BResul
/// every `half` NaN to `0x7FC00000` and moves one unwidened with its bits; the module records
/// `PrecisionNote::NativeNanEncoding` ([`widens_bits`]). A denormal "obtained via unpacking an
/// integer into a vector of values with smaller bit width" is kept under `DenormPreserve` for 16
/// bits, which the float controls declare ([`QuantizeForm::Controlled`], [`controlled_modes`]); on
/// MoltenVK the measured `DriverDeviation::MetalHalfArithmetic` reads every `half` through this
/// widening as Metal widens it, and the module requires that fact; elsewhere the device may flush
/// bits, which the float controls declare ([`QuantizeForm::Controlled`], [`controlled_modes`]);
/// elsewhere the device may flush
/// it to the zero of its sign, within `PrecisionNote::NativeHalfConversion`'s bound, which the
/// module records.
fn device_from_bits(fb: &mut FunctionBuilder<'_>, f: Form, h: Value) -> BResult<Value> {
@@ -1470,11 +1329,9 @@ fn device_from_bits(fb: &mut FunctionBuilder<'_>, f: Form, h: Value) -> BResult<
/// [`QuantizeForm::Device`]), or an `OpFConvert` to 32 bits of an `OpBitcast` to a 16-bit float or
/// a vector of them, or of 16-bit floats taken from one by a component extract or a shuffle
/// ([`device_from_bits`]). The module then records `PrecisionNote::NativeNanEncoding` (a NaN's
/// bits the device's) unless the device's moves of a NaN are measured to be Metal's
/// ([`moves_unfolded`]); under the float controls ([`QuantizeForm::Controlled`]) its entry
/// declares [`controlled_modes`], and elsewhere its denormals are the measured fact's
/// (`DriverDeviation::MetalHalfArithmetic`, which measures the conversion, not the unpack) or the
/// device's (`PrecisionNote::NativeHalfConversion`). The device's 16-bit arithmetic and
/// bits the device's); under the float controls ([`QuantizeForm::Controlled`]) its entry
/// declares [`controlled_modes`], and elsewhere its denormals are the device's
/// (`PrecisionNote::NativeHalfConversion`). The device's 16-bit arithmetic and
/// conversions widen what they compute, which no bitcast gives. At most four passes over the
/// instructions, with three bits per value of the module charged to `meter` while they run.
pub fn widens_bits(m: &TypedModule, meter: &mut Meter) -> Result<bool, Error> {
@@ -1567,221 +1424,6 @@ fn has_bit(bits: &[u64], v: Value) -> bool {
.is_some_and(|w| w & (1 << (v.index() % 64)) != 0)
}
/// Whether module `m` moves a `half` NaN where the device's compiler is not measured to fold the
/// widening and the narrowing that hold it (`DriverDeviation::MetalNanMoves`), so that its bits
/// stay the device's. A value a `half` read from its bits widens to ([`widens_bits`]), moved
/// through phis, selects, copies, composites and a function's scalar or vector `float` variable
/// (stored and loaded, which the driver's compiler keeps in the registers), may reach a
/// conversion (its bits, by a bitcast, only as stored to a buffer or to workgroup memory), an
/// arithmetic or comparison instruction, a fused multiply-add, a derivative, a `GLSL.std.450`
/// function other than `FrexpStruct`, `ModfStruct` and `Ldexp`, each of which computes a value
/// whose NaN Metal answers from the widened value's or its own note records, and a store to a
/// buffer or to workgroup memory, which holds a `float` there, and a texture write's store of it
/// as its texel (`TypedModule::stored_texels`), whose stored NaN the write's own notes account for
/// under the format it stores (`lower::texture::half_write_nans` and `half_storage_facts`);
/// anything else (a store to another class, a call, a return, an atomic, a group or another image
/// operation, or its bits read) carries the widened `float` out of the registers or reads its bits
/// before any narrowing. The module holding a 32-bit float constant that is a NaN other than
/// `0x7FC00000`, such as a `half` NaN constant held widened with its payload, which no conversion
/// of the device made, is unfolded too, and so is a module that merges a widened value a select
/// took against a value it does not hold widened with another widened value, member by member
/// where composites carry them (`merges::merges_mixed_selects`), which Metal's compiler does not
/// fold. The measurement covers moves through the registers, and `half` values held as the
/// device's conversions made them. One pass over the constants, then a pass over the instructions
/// per round of the moves' closure and two more, with eight bits per value of the module charged
/// to `meter` while it runs (and the merges' records while they run).
pub fn moves_unfolded(m: &TypedModule, meter: &mut Meter) -> Result<bool, Error> {
let float32 = |ty| matches!(m.types().get(ty), Ok(Type::Float { width: 32 }));
let payload = m.consts().iter().any(|(_, c)| match &c.kind {
ConstKind::Plain(Constant::Scalar { ty, bits }) if float32(*ty) => {
let b = bits.0 as u32;
b & 0x7F80_0000 == 0x7F80_0000 && b & 0x007F_FFFF != 0 && b != 0x7FC0_0000
}
_ => false,
});
if payload {
return Ok(true);
}
let words = m.values().len().div_ceil(64);
// The class of pointer `ptr`, and the type it points to.
let pointer = |ptr| {
m.value(ptr).ok().and_then(|v| match m.types().get(v.ty) {
Ok(Type::Pointer { class, pointee }) => Some((*class, *pointee)),
_ => None,
})
};
// Whether pointer `ptr` is to a function's scalar or vector `float` variable.
let local_float = |ptr| match pointer(ptr) {
Some((StorageClass::Function, pointee)) => {
let lane = match m.types().get(pointee) {
Ok(Type::Vector { elem, .. }) => *elem,
_ => pointee,
};
float32(lane)
}
_ => false,
};
meter.charge(48 * words)?;
let carried = widenings(m, meter).and_then(|mut widened| {
// The widened values' bits, by a bitcast and the moves.
let mut bits = vec![0u64; words];
// The moves' closure: a phi, a select, a copy or a composite of a widened value is one,
// and of its bits.
let mut grew = true;
while grew {
grew = false;
for b in m.blocks() {
for phi in &b.phis {
for set in [&mut widened, &mut bits] {
if !has_bit(set, phi.result)
&& phi.incoming.iter().any(|(v, _)| has_bit(set, *v))
{
set_bit(set, phi.result);
grew = true;
}
}
}
for n in &b.insts {
// A function's `float` variable a widened value is stored to holds one.
if let Inst::Store { ptr, value, .. } = &n.inst {
if has_bit(&widened, *value)
&& local_float(*ptr)
&& !has_bit(&widened, *ptr)
{
set_bit(&mut widened, *ptr);
grew = true;
}
continue;
}
let Some(r) = n.result else { continue };
if let Inst::Load { ptr, .. } = &n.inst {
if has_bit(&widened, *ptr) && !has_bit(&widened, r) {
set_bit(&mut widened, r);
grew = true;
}
continue;
}
if let Inst::Convert {
op: ConvOp::Bitcast,
a,
..
} = &n.inst
{
if has_bit(&widened, *a) && !has_bit(&bits, r) {
set_bit(&mut bits, r);
grew = true;
}
continue;
}
if !moves(&n.inst) {
continue;
}
for set in [&mut widened, &mut bits] {
let mut from = false;
n.inst.for_each_value(|v| from |= has_bit(set, v));
if from && !has_bit(set, r) {
set_bit(set, r);
grew = true;
}
}
}
}
}
// A merge of a widened value a select took against a value it does not hold widened
// (the translation's bounds check selects a read against `0`) with another widened value,
// by a phi or by stores to one function variable, the two in a composite's members too:
// Metal's compiler widens and narrows the NaN there, where it folds each of the two moves
// alone (measured).
if merges::merges_mixed_selects(m, &widened, &local_float, meter)? {
return Ok(true);
}
// Whether pointer `ptr` is to a buffer or to workgroup memory.
let held_as_float = |ptr| {
matches!(
pointer(ptr),
Some((
StorageClass::StorageBuffer
| StorageClass::PhysicalStorageBuffer
| StorageClass::Workgroup,
_
))
)
};
Ok(m.blocks().iter().any(|b| {
let returned = matches!(
b.term,
Terminator::ReturnValue(v) if has_bit(&widened, v) || has_bit(&bits, v)
);
returned
|| b.insts.iter().filter(|n| !moves(&n.inst)).any(|n| {
let (mut from, mut read) = (false, false);
n.inst.for_each_value(|v| {
from |= has_bit(&widened, v);
read |= has_bit(&bits, v);
});
match &n.inst {
Inst::Store { ptr, value, .. } => {
has_bit(&bits, *ptr)
|| (has_bit(&widened, *value)
&& !held_as_float(*ptr)
&& !local_float(*ptr))
|| (has_bit(&bits, *value) && !held_as_float(*ptr))
}
Inst::Load { .. } => false,
Inst::ImageWrite { texel, .. } => {
read || (from
&& !(has_bit(&widened, *texel)
&& m.stored_texels().contains(texel)))
}
Inst::AtomicStore { ptr, .. } => {
from || has_bit(&widened, *ptr) || has_bit(&bits, *ptr)
}
Inst::Convert {
op: ConvOp::Bitcast,
..
} => read,
inst => read || (from && !computes(inst)),
}
})
}))
});
meter.release(48 * words);
carried
}
/// Whether `inst` moves its operands' values into its result unchanged ([`moves_unfolded`]).
fn moves(inst: &Inst) -> bool {
matches!(
inst,
Inst::Select { .. }
| Inst::Unary {
op: UnOp::CopyObject,
..
}
| Inst::CompositeConstruct { .. }
| Inst::CompositeExtract { .. }
| Inst::CompositeInsert { .. }
| Inst::VectorExtractDynamic { .. }
| Inst::VectorInsertDynamic { .. }
| Inst::VectorShuffle { .. }
)
}
/// Whether `inst` computes a value from its operands' in the registers, whose NaN Metal answers
/// from the widened value's or its own note records ([`moves_unfolded`]).
fn computes(inst: &Inst) -> bool {
match inst {
Inst::Convert { op, .. } => *op != ConvOp::Bitcast,
Inst::Glsl { op, .. } => {
!matches!(op, GlslOp::FrexpStruct | GlslOp::ModfStruct | GlslOp::Ldexp)
}
Inst::Unary { .. } | Inst::Binary { .. } | Inst::Fma { .. } | Inst::Derivative { .. } => {
true
}
_ => false,
}
}
/// Whether module `m` computes in 16-bit floats: an `OpFAdd`, `OpFSub`, `OpFMul` or `OpFDiv`, an
/// `OpFmaKHR`, or a `GLSL.std.450 Fma` or `Sqrt` whose result is a 16-bit float or a vector of
/// them, the device's own `half` arithmetic (`super::ops::f16_binary`, `super::fma`,
@@ -1992,8 +1634,6 @@ pub fn resize(fb: &mut FunctionBuilder<'_>, from: Form, to: Form, x: Value) -> B
);
if widening {
Ok(x)
} else if (src, dst) == (FloatFmt::F32, FloatFmt::Half) {
round_measured(fb, to, x)
} else {
round(fb, to, x)
}
@@ -1,350 +0,0 @@
//! The merges of a widened `half` that a select took against a value it does not hold widened
//! with another widened value, followed through the composites that carry them
//! ([`merges_mixed_selects`], `narrow::moves_unfolded`).
//!
//! A select carried inside a composite (a texel read's `{T, i8}`, a struct, an array, a vector)
//! and merged with it is taken for the measured merge of its members: not measured through a
//! composite, but its members' merges are the measured shape once a compiler splits it into them.
//! The analysis therefore asks, member by member, what a value holds: a path of
//! literal indices names a member (a struct's member, an array's element, a matrix's column, a
//! vector's lane), the empty path the value itself. A construct, an insert, an extract and a copy
//! carry each member through unchanged; a select and a phi take each member from their operands.
use super::has_bit;
use crate::budget::Meter;
use crate::error::Error;
use crate::spirv::ids::{BlockId, Value};
use crate::spirv::ir::{Inst, Type, TypedModule, UnOp};
use std::collections::HashMap;
/// The most steps one question of a value's member follows ([`Members::widened_at`],
/// [`Members::mixed_at`]): a bound on the walk. Past it a member counts as widened wherever its
/// value is widened, so a merge is never missed for it.
const STEPS: usize = 256;
/// The most members of one value's type the merge checks look at; a type with more counts as
/// merging wherever two of its incoming values are widened.
const NODES: usize = 256;
/// The bytes one value's record holds while the analysis runs, as the meter charges it: the
/// entry and the map's slack.
const RECORD_BYTES: usize = std::mem::size_of::<(Value, Made<'static>)>() + 16;
/// How module `m`'s value was made, where it carries its operands' members.
enum Made<'a> {
Construct(&'a [Value]),
Insert {
object: Value,
composite: Value,
indices: &'a [u32],
},
Extract {
composite: Value,
indices: &'a [u32],
},
Copy(Value),
Select {
t: Value,
f: Value,
},
Phi(&'a [(Value, BlockId)]),
}
/// The values of a module that carry members, and its widened values.
struct Members<'a> {
m: &'a TypedModule,
made: HashMap<Value, Made<'a>>,
widened: &'a [u64],
}
impl<'a> Members<'a> {
fn new(m: &'a TypedModule, widened: &'a [u64]) -> Members<'a> {
let mut made = HashMap::new();
for b in m.blocks() {
for phi in &b.phis {
made.insert(phi.result, Made::Phi(&phi.incoming));
}
for n in &b.insts {
let Some(r) = n.result else { continue };
let carried = match &n.inst {
Inst::CompositeConstruct { parts } => Made::Construct(parts),
Inst::CompositeInsert {
object,
composite,
indices,
} => Made::Insert {
object: *object,
composite: *composite,
indices,
},
Inst::CompositeExtract { composite, indices } => Made::Extract {
composite: *composite,
indices,
},
Inst::Unary {
op: UnOp::CopyObject,
a,
} => Made::Copy(*a),
Inst::Select { t, f, .. } => Made::Select { t: *t, f: *f },
_ => continue,
};
made.insert(r, carried);
}
}
Members { m, made, widened }
}
/// The type of value `v`.
fn ty(&self, v: Value) -> Option<&'a Type> {
let ty = self.m.value(v).ok()?.ty;
self.m.types().get(ty).ok()
}
/// The lanes of value `v`: a vector's, 1 for a scalar.
fn lanes(&self, v: Value) -> u32 {
match self.ty(v) {
Some(Type::Vector { len, .. }) => u32::from(*len),
_ => 1,
}
}
/// The part of construct `v` (of `parts`) that holds member `path`, and the path inside it:
/// a vector's lane is in the part that supplies it, every other composite's member is its
/// part. `None` for the empty path or one out of range.
fn part(&self, v: Value, parts: &[Value], path: &[u32]) -> Option<(Value, Vec<u32>)> {
let (&first, rest) = path.split_first()?;
if !matches!(self.ty(v), Some(Type::Vector { .. })) {
return Some((*parts.get(first as usize)?, rest.to_vec()));
}
let mut lane = first;
for &p in parts {
let n = self.lanes(p);
if lane < n {
let inside = match matches!(self.ty(p), Some(Type::Vector { .. })) {
true => [&[lane][..], rest].concat(),
false => rest.to_vec(),
};
return Some((p, inside));
}
lane -= n;
}
None
}
/// Whether member `path` of `v` holds a widened value, wholly or in part: the member of a
/// construct's part, an insert's object or composite, an extract's composite, a copy's
/// operand, a select's or a phi's operands, else (a value made otherwise) `v`'s own mark.
fn widened_at(&self, v: Value, path: &[u32]) -> bool {
let mut seen = Vec::new();
let mut steps = STEPS;
self.widened_in(v, path.to_vec(), &mut seen, &mut steps)
}
fn widened_in(
&self,
v: Value,
path: Vec<u32>,
seen: &mut Vec<Value>,
steps: &mut usize,
) -> bool {
let own = has_bit(self.widened, v);
if *steps == 0 {
return own;
}
*steps -= 1;
match self.made.get(&v) {
Some(Made::Construct(parts)) => match self.part(v, parts, &path) {
Some((p, inside)) => self.widened_in(p, inside, seen, steps),
None => own,
},
Some(Made::Insert {
object,
composite,
indices,
}) => {
let inside = path.strip_prefix(*indices).map(<[u32]>::to_vec);
if path.is_empty() {
own
} else if let Some(inside) = inside {
self.widened_in(*object, inside, seen, steps)
} else if indices.starts_with(&path) {
self.widened_in(*object, Vec::new(), seen, steps)
|| self.widened_in(*composite, path, seen, steps)
} else {
self.widened_in(*composite, path, seen, steps)
}
}
Some(Made::Extract { composite, indices }) => {
let full = [&indices[..], &path[..]].concat();
self.widened_in(*composite, full, seen, steps)
}
Some(Made::Copy(a)) => self.widened_in(*a, path, seen, steps),
Some(Made::Select { t, f }) => {
self.widened_in(*t, path.clone(), seen, steps)
|| self.widened_in(*f, path, seen, steps)
}
Some(Made::Phi(incoming)) => {
if seen.contains(&v) {
return false;
}
seen.push(v);
incoming
.iter()
.any(|(i, _)| self.widened_in(*i, path.clone(), seen, steps))
}
None => own,
}
}
/// Whether member `path` of `v` is a select of a widened value against a value it does not
/// hold widened, carried there by constructs, inserts, extracts and copies (a phi carries
/// none: a merge then a select keeps every NaN's bits, measured). A select of composites
/// selects each member: its member `path` is such a select where one operand's member is
/// widened and the other's is not.
fn mixed_at(&self, v: Value, path: &[u32]) -> bool {
let mut steps = STEPS;
let mut at = (v, path.to_vec());
loop {
let (v, path) = at;
if steps == 0 {
return has_bit(self.widened, v);
}
steps -= 1;
at = match self.made.get(&v) {
Some(Made::Select { t, f }) => {
return self.widened_at(*t, &path) != self.widened_at(*f, &path);
}
Some(Made::Construct(parts)) => match self.part(v, parts, &path) {
Some(inside) => inside,
None => return false,
},
Some(Made::Insert {
object,
composite,
indices,
}) => {
let inside = path.strip_prefix(*indices).map(<[u32]>::to_vec);
if let (false, Some(inside)) = (path.is_empty(), inside) {
(*object, inside)
} else if indices.starts_with(&path) {
return false;
} else {
(*composite, path)
}
}
Some(Made::Extract { composite, indices }) => {
(*composite, [&indices[..], &path[..]].concat())
}
Some(Made::Copy(a)) => (*a, path),
Some(Made::Phi(_)) | None => return false,
};
}
}
/// The paths of every member of `v`'s type, itself (the empty path) first: a struct's
/// members, a sized array's elements, a matrix's columns and a vector's lanes, and theirs.
/// `None` past [`NODES`].
fn paths(&self, v: Value) -> Option<Vec<Vec<u32>>> {
let ty = self.m.value(v).ok()?.ty;
let mut out = Vec::new();
let mut open = vec![(ty, Vec::new())];
while let Some((ty, path)) = open.pop() {
if out.len() == NODES {
return None;
}
let types = self.m.types();
let members: Vec<_> = match types.get(ty).ok()? {
Type::Struct { members, .. } => members.to_vec(),
Type::Vector { elem, len } => vec![*elem; usize::from(*len)],
Type::Matrix { col, cols } => vec![*col; usize::from(*cols)],
Type::Array { elem, len, .. } => match self.m.consts().array_len(*len, types) {
Ok(Some(n)) if n as usize <= NODES => vec![*elem; n as usize],
Ok(Some(_)) => return None,
_ => Vec::new(),
},
_ => Vec::new(),
};
for (i, member) in members.into_iter().enumerate().rev() {
open.push((member, [&path[..], &[i as u32]].concat()));
}
out.push(path);
}
Some(out)
}
/// Whether one of `values`, at index `at`, holds a mixed select at a member where another of
/// them holds a widened value: their merge is the measured one. The others are every other
/// index, or with `distinct` every other value (a phi's incoming value twice is no merge with
/// itself). Only widened values take part: a value holding a widened member is widened. A
/// type of more than [`NODES`] members merges wherever two of them are widened.
fn merges(&self, values: &[Value], at: usize, distinct: bool) -> bool {
let Some(&s) = values.get(at).filter(|s| has_bit(self.widened, **s)) else {
return false;
};
let others = || {
values.iter().enumerate().filter(move |&(j, v)| {
has_bit(self.widened, *v) && if distinct { *v != s } else { j != at }
})
};
let Some(paths) = self.paths(s) else {
return others().next().is_some();
};
paths
.iter()
.any(|path| self.mixed_at(s, path) && others().any(|(_, v)| self.widened_at(*v, path)))
}
}
/// Whether module `m` merges a widened value (one of `widened`) that a select took against a value
/// it does not hold widened with another widened value (`narrow::moves_unfolded`): a phi with
/// such a select among its incoming values and another widened one, or a function variable
/// (`local_float`) such a select is stored to and another widened value too, member by member
/// (the module docs). Measured on the M3 Max under macOS 27.0.1 (2026-11-03), every `half` bit
/// pattern widened, moved and narrowed by Metal's compiler, with and without fast math: a merge of
/// `b ? float(h) : 0.0` with `float(h2)`, or with `b ? float(h2) : 0.0`, answers 2045 of the 2046
/// NaNs `0x7E00`, where the select alone, the merge of widened values alone, a select of two
/// widened values merged with a third, the select merged with a constant, a merge then a select,
/// two selects, two merges, the select carried to a later block, and a select of the `half` bits
/// before the widening each keep every NaN's bits. One pass over the instructions to record the
/// values that carry members and the stores, [`RECORD_BYTES`] per instruction and phi charged to
/// `meter` while it runs, then the questions of each phi's and each such variable's values.
pub(super) fn merges_mixed_selects(
m: &TypedModule,
widened: &[u64],
local_float: &dyn Fn(Value) -> bool,
meter: &mut Meter,
) -> Result<bool, Error> {
let records: usize = m
.blocks()
.iter()
.map(|b| b.phis.len() + b.insts.len())
.sum();
let bytes = records.saturating_mul(RECORD_BYTES);
meter.charge(bytes)?;
let members = Members::new(m, widened);
// The widened values stored to each function variable, in order. Each store is one of the
// merged values, where each of a phi's incoming values is: two stores of one select to a
// variable merge it with itself, and a phi's two edges of one value do not.
let mut stores: HashMap<Value, Vec<Value>> = HashMap::new();
for n in m.blocks().iter().flat_map(|b| &b.insts) {
if let Inst::Store { ptr, value, .. } = &n.inst {
if has_bit(widened, *value) && local_float(*ptr) {
stores.entry(*ptr).or_default().push(*value);
}
}
}
let stored = stores
.values()
.any(|values| (0..values.len()).any(|i| members.merges(values, i, false)));
let merged = stored
|| m.blocks().iter().flat_map(|b| &b.phis).any(|phi| {
if !has_bit(widened, phi.result) {
return false;
}
let values: Vec<Value> = phi.incoming.iter().map(|(v, _)| *v).collect();
(0..values.len()).any(|i| members.merges(&values, i, true))
});
drop((members, stores));
meter.release(bytes);
Ok(merged)
}
+2 -7
View File
@@ -285,8 +285,7 @@ pub fn f16_binary_words(f: Form) -> u32 {
/// ([`narrow::round`]), so no conversion barrier and no conversion pair, which a device's compiler
/// spends most on (ANV's register allocation grows with the values the pairs add).
///
/// The instruction is Metal's where the profile takes `DriverDeviation::MetalHalfArithmetic`, and,
/// by the Vulkan spec, in an entry declaring the 16-bit float controls the module's roundings take
/// The instruction is Metal's, by the Vulkan spec, in an entry declaring the 16-bit float controls the module's roundings take
/// ([`narrow::controlled_modes`]): the precision table "for IEEE754 half- (16 bit) and single- (32
/// bit) precision instructions" lists `OpFAdd`, `OpFSub` and `OpFMul` as "Correctly rounded",
/// "according to IEEE 754 roundTiesToEven" under `RoundingModeRTE`, `DenormPreserve` keeps
@@ -300,11 +299,7 @@ pub fn f16_binary_words(f: Form) -> u32 {
/// The instruction takes the AIR's own contraction, as `float` arithmetic does
/// ([`float_binary`]): one whose flags carry both `contract` and `reassoc`
/// (`Contraction::Allowed`) is undecorated, a product a plain `OpFMul`, and the device's compiler
/// groups and fuses it with its neighbours as it chooses. On MoltenVK, Metal's fast and relaxed
/// compiles fold such an operation's narrowings and widening away and answer the `float` sum,
/// difference or product of the widened operands, unrounded (measured with
/// `DriverDeviation::MetalHalfArithmetic`), which selection records as
/// `PrecisionNote::FastMathRewrites`. Any other (`Contraction::Forbidden`) is kept apart: a sum or
/// groups and fuses it with its neighbours as it chooses. Any other (`Contraction::Forbidden`) is kept apart: a sum or
/// difference decorated `NoContraction` (SPIRV-Cross writes its `[[clang::optnone]]` `spvFAdd` or
/// `spvFSub`), a product as `Fma(a, b, -0.0)` decorated `NoContraction`, the product's value
/// whether the device fuses it or not; a `NoContraction` `OpFMul`, which SPIRV-Cross writes as
@@ -40,31 +40,6 @@ pub fn instruction(format: PackFormat, dir: PackDir) -> Option<GlslOp> {
})
}
/// Whether the device's conversion of `format` in direction `dir` on float lanes of `fmt` is one
/// measured to answer Metal's where the profile takes `DriverDeviation::MetalPackConversions`:
/// `unorm.rgb565` in `float`, and in `half` `unorm4x8`, `snorm4x8`, `unorm.rgb10a2` and
/// `unorm.rgb565` both ways and `unorm2x16` and `snorm2x16` packed.
pub fn measured(format: PackFormat, dir: PackDir, fmt: FloatFmt) -> bool {
use PackFormat as F;
match (fmt, dir) {
(FloatFmt::F32, _) => format == F::UnormRgb565,
(FloatFmt::Half, PackDir::Pack) => matches!(
format,
F::Unorm4x8
| F::Snorm4x8
| F::Unorm2x16
| F::Snorm2x16
| F::UnormRgb10a2
| F::UnormRgb565
),
(FloatFmt::Half, PackDir::Unpack) => matches!(
format,
F::Unorm4x8 | F::Snorm4x8 | F::UnormRgb10a2 | F::UnormRgb565
),
_ => false,
}
}
/// The error of a conversion whose format or lanes the emission cannot take (a packed float
/// format to pack to, a lane count not the format's): selection rules both out.
fn unpackable() -> BuildError {
+142 -223
View File
@@ -22,7 +22,7 @@ use super::ops::{self, BitcastPlan, CastKind};
use crate::air::ir::{BinOp as AirBin, FloatPredicate, IntFlags, IntPredicate};
use crate::device::DeviceProfile;
use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder, ProductForm, QuantizeForm};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder, QuantizeForm};
use crate::spirv::error::BResult;
use crate::spirv::ids::{FuncId, GlobalId, TypeId, Value};
use crate::spirv::interp::{run, Buffer, Config, Resources};
@@ -1040,20 +1040,14 @@ fn llvm_fcmp(pred: FloatPredicate, a: f64, b: f64) -> bool {
/// A multiply rounded on its own is IEEE's product bit for bit on every pair of the value sets,
/// `-0.0` operands, zero products of either sign, denormals, overflow, infinities, and NaNs
/// included, on `float` scalars and vectors and on `double`, in either of its forms (`OpFMul`, and
/// `Fma(a, b, -0.0)` where SPIRV-Cross renders the SPIR-V).
/// included, on `float` scalars and vectors and on `double`.
#[test]
fn a_multiply_without_contraction_is_the_product() {
for (form, bits, vals, lanes) in [ProductForm::Multiply, ProductForm::NegativeZeroFma]
.into_iter()
.flat_map(|form| {
[
(form, 32u8, f32_values(), 1u8),
(form, 32, f32_values(), 4),
(form, 64, f64_values(), 1),
]
})
{
for (bits, vals, lanes) in [
(32u8, f32_values(), 1u8),
(32, f32_values(), 4),
(64, f64_values(), 1),
] {
let f = vec(float(bits), lanes);
let cases: Vec<Case> = pairs(&vals, &vals)
.into_iter()
@@ -1064,13 +1058,10 @@ fn a_multiply_without_contraction_is_the_product() {
})
.collect();
check(
&format!("fmul without contraction f{bits} x{lanes} as {form:?}"),
&format!("fmul without contraction f{bits} x{lanes}"),
&[f, f],
f,
&|fb, x| {
fb.module().product_form(form);
ops::float_binary(fb, AirBin::FMul, f, Contraction::Forbidden, x[0], x[1])
},
&|fb, x| ops::float_binary(fb, AirBin::FMul, f, Contraction::Forbidden, x[0], x[1]),
&cases,
&|c| {
let r = |l: usize| {
@@ -1088,13 +1079,12 @@ fn a_multiply_without_contraction_is_the_product() {
}
}
/// An `f32` product by a constant with `-0.0` components is IEEE's product bit for bit in every
/// [`ProductForm`] (a NaN's bits aside), as `OpFMul` with the constant on either side, with and
/// without contraction, and as `OpVectorTimesScalar` by a `-0.0` scalar or of a constant vector,
/// and in every form no product the module emits has a `-0.0` component in a constant factor: it
/// multiplies by `+0.0` there and negates.
/// An `f32` product by a constant with `-0.0` components is IEEE's product bit for bit (a NaN's
/// bits aside), as `OpFMul` with the constant on either side, with and without contraction, and
/// as `OpVectorTimesScalar` by a `-0.0` scalar or of a constant vector, and no product the module
/// emits has a `-0.0` component in a constant factor: it multiplies by `+0.0` there and negates.
#[test]
fn a_product_by_a_negative_zero_factor_keeps_its_sign_in_every_form() {
fn a_product_by_a_negative_zero_factor_keeps_its_sign() {
const NZ: u64 = 0x8000_0000;
const TWO: u64 = 0x4000_0000;
#[derive(Clone, Copy, Debug)]
@@ -1144,76 +1134,72 @@ fn a_product_by_a_negative_zero_factor_keeps_its_sign_in_every_form() {
.count()
};
let vals = f32_values();
for form in [ProductForm::Multiply, ProductForm::NegativeZeroFma] {
for contract in [Contraction::Forbidden, Contraction::Allowed] {
for (lanes, shape, c) in factors {
let what = format!("{form:?} {contract:?} {shape:?} x{lanes} by {c:x?}");
let x_lanes = match shape {
Shape::OfConstant => 1,
_ => lanes,
};
let input = vec(float(32), x_lanes);
let out = vec(float(32), lanes);
let body = |fb: &mut FunctionBuilder<'_>, xs: &[Value]| -> BResult<Value> {
fb.module().product_form(form);
let f32_ty = fb.module().ty(Type::Float { width: 32 })?;
let parts = c
.iter()
.map(|bits| {
fb.module().constant(Constant::Scalar {
ty: f32_ty,
bits: ConstBits(*bits),
})
})
.collect::<BResult<Vec<_>>>()?;
let k = if parts.len() == 1 {
parts[0]
} else {
let ty = fb.module().ty(Type::Vector {
elem: f32_ty,
len: parts.len() as u8,
})?;
fb.module().constant(Constant::Composite {
ty,
parts: parts.into(),
})?
};
let k = fb.module().const_value(k)?;
let (op, a, b) = match shape {
Shape::Mul { left: false } => (BinOp::FMul, xs[0], k),
Shape::Mul { left: true } => (BinOp::FMul, k, xs[0]),
Shape::ByScalar => (BinOp::VectorTimesScalar, xs[0], k),
Shape::OfConstant => (BinOp::VectorTimesScalar, k, xs[0]),
};
fb.binary_with(op, a, b, contract)
};
let m = kernel_with(&[input], out, &body, true, false)
.unwrap_or_else(|e| panic!("{what}: build: {e:?}"));
assert_eq!(negative_factors(&m), 0, "{what}: a -0.0 factor");
let cases: Vec<Case> = vals
for contract in [Contraction::Forbidden, Contraction::Allowed] {
for (lanes, shape, c) in factors {
let what = format!("{contract:?} {shape:?} x{lanes} by {c:x?}");
let x_lanes = match shape {
Shape::OfConstant => 1,
_ => lanes,
};
let input = vec(float(32), x_lanes);
let out = vec(float(32), lanes);
let body = |fb: &mut FunctionBuilder<'_>, xs: &[Value]| -> BResult<Value> {
let f32_ty = fb.module().ty(Type::Float { width: 32 })?;
let parts = c
.iter()
.map(|x| vec![vec![*x; usize::from(x_lanes)]])
.collect();
let factor = |l: usize| f32::from_bits(c[if c.len() == 1 { 0 } else { l }] as u32);
check_module(
&what,
m,
&[input],
out,
&cases,
&|case| {
let x = |l: usize| {
f32::from_bits(case[0][if x_lanes == 1 { 0 } else { l }] as u32)
};
Some(
(0..usize::from(lanes))
.map(|l| u64::from((x(l) * factor(l)).to_bits()))
.collect(),
)
},
&|g, w| g == w || (is_nan(out, g) && is_nan(out, w)),
);
}
.map(|bits| {
fb.module().constant(Constant::Scalar {
ty: f32_ty,
bits: ConstBits(*bits),
})
})
.collect::<BResult<Vec<_>>>()?;
let k = if parts.len() == 1 {
parts[0]
} else {
let ty = fb.module().ty(Type::Vector {
elem: f32_ty,
len: parts.len() as u8,
})?;
fb.module().constant(Constant::Composite {
ty,
parts: parts.into(),
})?
};
let k = fb.module().const_value(k)?;
let (op, a, b) = match shape {
Shape::Mul { left: false } => (BinOp::FMul, xs[0], k),
Shape::Mul { left: true } => (BinOp::FMul, k, xs[0]),
Shape::ByScalar => (BinOp::VectorTimesScalar, xs[0], k),
Shape::OfConstant => (BinOp::VectorTimesScalar, k, xs[0]),
};
fb.binary_with(op, a, b, contract)
};
let m = kernel_with(&[input], out, &body, true, false)
.unwrap_or_else(|e| panic!("{what}: build: {e:?}"));
assert_eq!(negative_factors(&m), 0, "{what}: a -0.0 factor");
let cases: Vec<Case> = vals
.iter()
.map(|x| vec![vec![*x; usize::from(x_lanes)]])
.collect();
let factor = |l: usize| f32::from_bits(c[if c.len() == 1 { 0 } else { l }] as u32);
check_module(
&what,
m,
&[input],
out,
&cases,
&|case| {
let x =
|l: usize| f32::from_bits(case[0][if x_lanes == 1 { 0 } else { l }] as u32);
Some(
(0..usize::from(lanes))
.map(|l| u64::from((x(l) * factor(l)).to_bits()))
.collect(),
)
},
&|g, w| g == w || (is_nan(out, g) && is_nan(out, w)),
);
}
}
}
@@ -2690,28 +2676,6 @@ fn half_nan_answers_follow_the_measured_states() {
] {
assert_eq!(cast_answer(op, from, to), None, "{op:?} {from:?} {to:?}");
}
use crate::device::profile::NanEncoding;
assert!(A::Canonical.device_answers(NanEncoding::MetalCanonical));
for a in [
A::CanonicalExact,
A::Operand,
A::OperandSign,
A::DomainSign,
A::BaseToExponentOne,
] {
assert!(!a.device_answers(NanEncoding::MetalCanonical), "{a:?}");
}
// A device not measured to answer Metal's canonical NaN answers none of Metal's NaNs.
for a in [
A::Canonical,
A::CanonicalExact,
A::Operand,
A::OperandSign,
A::DomainSign,
A::BaseToExponentOne,
] {
assert!(!a.device_answers(NanEncoding::Native), "{a:?}");
}
}
/// The float facts of a profile whose `float` fused multiply-add is `OpFmaKHR`, whose `half` one
@@ -2721,25 +2685,17 @@ const KHR_FACTS: super::FloatFacts = super::FloatFacts {
float: super::fma::Route::Khr,
half: super::fma::Route::Native,
},
metal_functions: false,
device_denormals: false,
unary_denormals: false,
nans: crate::device::profile::NanEncoding::Native,
native_min_max: false,
nan_moves: false,
};
/// `ldexp` on `float` is lowered on the bits ([`math::ldexp_bits`]), which answer a NaN operand
/// itself, bit for bit, as Metal does (`NanAnswer::Operand`): no NaN of the device's reaches the
/// result, so the call records no `NativeNanEncoding` and leaves no NaN answer to the device, on a
/// device of either NaN encoding. A `half` `ldexp` multiplies, so its NaN is the device's product's
/// where Metal answers its canonical `half` NaN, and stays noted on a device not measured to answer
/// that.
/// result, so the call records no `NativeNanEncoding` and leaves no NaN answer to the device. A
/// `half` `ldexp` multiplies, so its NaN is the device's product's where Metal answers its canonical
/// `half` NaN, noted.
#[test]
fn float_ldexp_answers_metals_nan_itself() {
use super::nan::NanAnswer as A;
use crate::air::ir::FastMath;
use crate::device::profile::NanEncoding;
use crate::pipeline::artifact::PrecisionNote;
let form = |fmt| Form {
held: Held::Float(fmt),
@@ -2750,133 +2706,96 @@ fn float_ldexp_answers_metals_nan_itself() {
let every = FastMath::ALL
.iter()
.fold(FastMath::NONE, |a, (b, _)| a.union(*b));
for nans in [NanEncoding::Native, NanEncoding::MetalCanonical] {
let facts = super::FloatFacts { nans, ..KHR_FACTS };
for fmf in [FastMath::NONE, every] {
let call = super::float_call(FloatFn::Ldexp, false, fmf, form(FloatFmt::F32), facts)
.expect("float ldexp");
assert_eq!(call.nan, None, "{nans:?} {fmf:?}");
let noted = (call.notes.always.iter())
.chain(&call.notes.unless_metal_fast)
.any(|n| matches!(n, PrecisionNote::NativeNanEncoding));
assert!(!noted, "{nans:?} {fmf:?}: {:?}", call.notes);
}
let half = super::float_call(
FloatFn::Ldexp,
false,
FastMath::NONE,
form(FloatFmt::Half),
facts,
)
.expect("half ldexp");
assert_eq!(half.nan, Some(A::Canonical), "{nans:?}");
if nans == NanEncoding::Native {
assert!(
half.notes
.always
.contains(&PrecisionNote::NativeNanEncoding),
"{:?}",
half.notes
);
}
let facts = KHR_FACTS;
for fmf in [FastMath::NONE, every] {
let call = super::float_call(FloatFn::Ldexp, false, fmf, form(FloatFmt::F32), facts)
.expect("float ldexp");
assert_eq!(call.nan, None, "{fmf:?}");
let noted = (call.notes.iter()).any(|n| matches!(n, PrecisionNote::NativeNanEncoding));
assert!(!noted, "{fmf:?}: {:?}", call.notes);
}
let half = super::float_call(
FloatFn::Ldexp,
false,
FastMath::NONE,
form(FloatFmt::Half),
facts,
)
.expect("half ldexp");
assert_eq!(half.nan, Some(A::Canonical));
assert!(
half.notes.contains(&PrecisionNote::NativeNanEncoding),
"{:?}",
half.notes
);
}
/// Precise `pow` on `float` leaves its NaNs to the device (the device's `Pow`, and the device's sum
/// of NaN operands), where Metal's NaN is measured: the canonical NaN, but a NaN base to the
/// exponent one, which is the base itself. It records `NativeNanEncoding` as fast `pow` and `atan2`
/// do, on a device whose arithmetic answers Metal's canonical NaN too (its sum of `pow(NaN, 1)`'s
/// operands is that NaN, not the base), and never `DeviceNanEncoding`, which is for a NaN Metal
/// do, and never `DeviceNanEncoding`, which is for a NaN Metal
/// answers no NaN of (fast `sin` and `cos`).
#[test]
fn precise_pow_notes_its_measured_nan_as_the_devices() {
use super::nan::NanAnswer as A;
use crate::air::ir::FastMath;
use crate::device::profile::NanEncoding;
use crate::pipeline::artifact::PrecisionNote;
let f = Form {
held: Held::Float(FloatFmt::F32),
lanes: 1,
};
for nans in [NanEncoding::Native, NanEncoding::MetalCanonical] {
let facts = super::FloatFacts { nans, ..KHR_FACTS };
let call =
super::float_call(FloatFn::Pow, false, FastMath::NONE, f, facts).expect("float pow");
assert_eq!(call.nan, Some(A::BaseToExponentOne), "{nans:?}");
assert!(
call.notes
.always
.contains(&PrecisionNote::NativeNanEncoding),
"{nans:?}: {:?}",
call.notes
);
let every_note = call
.notes
.always
let facts = KHR_FACTS;
let call = super::float_call(FloatFn::Pow, false, FastMath::NONE, f, facts).expect("float pow");
assert_eq!(call.nan, Some(A::BaseToExponentOne));
assert!(
call.notes.contains(&PrecisionNote::NativeNanEncoding),
"{:?}",
call.notes
);
let every_note = call.notes.iter();
assert!(
!every_note
.clone()
.any(|n| *n == PrecisionNote::DeviceNanEncoding),
"{:?}",
call.notes
);
let sin = super::float_call(FloatFn::Sin, true, FastMath::NONE, f, facts).expect("fast sin");
assert_eq!(sin.nan, None);
assert!(
sin.notes
.iter()
.chain(&call.notes.unless_metal_fast);
assert!(
!every_note
.clone()
.any(|n| *n == PrecisionNote::DeviceNanEncoding),
"{nans:?}: {:?}",
call.notes
);
let sin =
super::float_call(FloatFn::Sin, true, FastMath::NONE, f, facts).expect("fast sin");
assert_eq!(sin.nan, None, "{nans:?}");
assert!(
sin.notes
.always
.iter()
.chain(&sin.notes.unless_metal_fast)
.any(|n| *n == PrecisionNote::DeviceNanEncoding),
"{nans:?}: {:?}",
sin.notes
);
}
.any(|n| *n == PrecisionNote::DeviceNanEncoding),
"{:?}",
sin.notes
);
}
/// Class E: Metal's `float` `fneg` and `fabs` flip or clear the sign bit alone, a NaN's payload and
/// a denormal kept (`nan_signbits`, `nan_signbits_fast`). The lowering takes the device's
/// `floor`, `ceil` and `fabs` on `float` leave their denormals to the device, noted
/// `DeviceDenormals`, but where the profile takes `DriverDeviation::MetalUnaryDenormals`
/// (`denormal::Covered::Unary`, `denormal::moves_sign`); `trunc` follows the other deviation
/// alone, in either mode.
/// `floor`, `ceil`, `trunc` and `fabs` on `float` leave their denormals to the device, noted
/// `DeviceDenormals`, in either mode (class E's `fabs` keeps a denormal on Metal).
#[test]
fn unary_denormals_follow_their_deviation() {
fn unary_denormals_are_the_device_s() {
use crate::air::ir::FastMath;
use crate::pipeline::artifact::PrecisionNote;
let f = Form {
held: Held::Float(FloatFmt::F32),
lanes: 1,
};
for unary in [false, true] {
// A profile that takes the unary deviation (MoltenVK on an Apple9 GPU) takes
// `MetalFloatFunctions` too: its `fabs` is one of Metal's functions.
let facts = super::FloatFacts {
unary_denormals: unary,
metal_functions: unary,
..KHR_FACTS
};
for op in [FloatFn::Floor, FloatFn::Ceil, FloatFn::Abs, FloatFn::Trunc] {
for fast in [false, true] {
let call = super::float_call(op, fast, FastMath::NONE, f, facts)
.unwrap_or_else(|| panic!("{op:?}: no float call"));
assert_eq!(
call.notes.always.contains(&PrecisionNote::DeviceDenormals),
!(unary && op != FloatFn::Trunc),
"{op:?}, fast {fast}, unary {unary}"
);
}
for op in [FloatFn::Floor, FloatFn::Ceil, FloatFn::Abs, FloatFn::Trunc] {
for fast in [false, true] {
let call = super::float_call(op, fast, FastMath::NONE, f, KHR_FACTS)
.unwrap_or_else(|| panic!("{op:?}: no float call"));
assert!(
call.notes.contains(&PrecisionNote::DeviceDenormals),
"{op:?}, fast {fast}"
);
}
}
}
/// `OpFNegate` and `FAbs` on every format, whose NaN is the device's: a `float` `fabs` answers
/// Metal's operand NaN by none of its own, noted `NativeNanEncoding` (and a `half` one Metal's
/// canonical NaN, class D), and off Metal's own functions records the device's precision and
/// denormals.
/// canonical NaN, class D), and records the device's precision and denormals.
#[test]
fn float_sign_operations_are_the_device_instructions() {
use super::nan::NanAnswer as A;
@@ -2903,7 +2822,7 @@ fn float_sign_operations_are_the_device_instructions() {
PrecisionNote::NativeTranscendentals,
PrecisionNote::DeviceDenormals,
] {
assert!(call.notes.always.contains(&note), "{note:?} {fmf:?}");
assert!(call.notes.contains(&note), "{note:?} {fmf:?}");
}
}
let call =
@@ -3429,7 +3348,7 @@ fn pi_scaled_functions_reduce_exactly_to_metal_answers() {
/// [`FloatFn::words`] bounds what `sinpi`, `cospi`, and `tanpi` emit on every form: the exact
/// reduction around the device's `Sin` and `Cos`, the axis arms and `tanpi`'s quarter turns
/// included, whether or not the device's functions are Metal's. The module's growth over an
/// included. The module's growth over an
/// identity kernel is charged in full, its constants and the `GLSL.std.450` import included.
#[test]
fn pi_scaled_functions_stay_within_their_word_estimate() {
@@ -215,100 +215,6 @@ fn narrow_members_move_as_bits_through_structs() {
}
}
/// A select of a widened `half` against a value not held widened, merged by an `OpPhi` with
/// another widened `half`, is the merge Metal's compiler does not fold (`narrow::moves_unfolded`),
/// and so it is carried in a struct's member: a phi of structs, one built from the select by a
/// construct or an insert, the other holding a widened `half` in the same member, and a phi of a
/// member extracted from such a struct. Structs that hold the select and the widened `half` in
/// different members, or the select beside a constant, merge nothing of it.
#[test]
fn a_merge_of_a_select_is_followed_through_struct_members() {
use crate::spirv::builder::constructs::{ArmEnd, ArmFn, Merged};
use crate::spirv::ir::Type;
// How the arms hand the phi their values: (then, else) from the select `t`, the widened
// halves `h` and `g`, the constant `one` and a struct type of two `f32` members.
#[derive(Clone, Copy, Debug)]
enum Shape {
Plain,
Struct,
Inserted,
Extracted,
Apart,
Constant,
}
let f = half();
for (shape, unfolded) in [
(Shape::Plain, true),
(Shape::Struct, true),
(Shape::Inserted, true),
(Shape::Extracted, true),
(Shape::Apart, false),
(Shape::Constant, false),
] {
let body = move |fb: &mut FunctionBuilder<'_>, x: &[Value]| -> BResult<Value> {
let (h, g) = (x[0], x[1]);
let f32_ = fb.value_ty(h)?;
let st = fb.module().ty(Type::Struct {
members: vec![f32_, f32_].into(),
layout: None,
})?;
let zero = const_of(fb, f32_, 0)?;
let one = const_of(fb, f32_, u64::from(1.0f32.to_bits()))?;
let c = fb.binary(BinOp::FOrdLessThan, h, g)?;
let d = fb.binary(BinOp::FOrdGreaterThan, h, one)?;
let then: ArmFn<'_, ()> = Box::new(move |fb, _| {
let t = fb.select(d, h, zero)?;
let v = match shape {
Shape::Plain => t,
Shape::Struct | Shape::Apart | Shape::Constant => {
fb.composite_construct(st, &[t, one])?
}
Shape::Inserted => {
let u = fb.undef(st)?;
fb.composite_insert(t, u, &[0])?
}
Shape::Extracted => {
let s = fb.composite_construct(st, &[t, one])?;
fb.composite_extract(s, &[0])?
}
};
Ok(ArmEnd::FallThrough(vec![v]))
});
let other: ArmFn<'_, ()> = Box::new(move |fb, _| {
let v = match shape {
Shape::Plain | Shape::Extracted => g,
Shape::Struct => fb.composite_construct(st, &[g, one])?,
Shape::Inserted => {
let u = fb.undef(st)?;
fb.composite_insert(g, u, &[0])?
}
Shape::Apart => fb.composite_construct(st, &[one, g])?,
Shape::Constant => fb.composite_construct(st, &[one, one])?,
};
Ok(ArmEnd::FallThrough(vec![v]))
});
let Merged(merged) = fb.if_(&mut (), c, then, Some(other))?;
let p = merged[0];
match shape {
Shape::Plain | Shape::Extracted => Ok(p),
// Both members out, so the widened `half` of either reaches the store.
_ => {
let a = fb.composite_extract(p, &[0])?;
let b = fb.composite_extract(p, &[1])?;
fb.select(c, a, b)
}
}
};
let m = kernel_with(&[f, f], f, &body, true, false)
.unwrap_or_else(|e| panic!("{shape:?}: build: {e:?}"));
let budget = crate::budget::Budget::default();
let mut meter = crate::budget::Meter::new(&budget);
let got = super::super::narrow::moves_unfolded(&m, &mut meter)
.unwrap_or_else(|e| panic!("{shape:?}: {e:?}"));
assert_eq!(got, unfolded, "{shape:?}");
}
}
/// One half round trip through its format bits, `to_bits` then `from_bits` (their types and
/// constants shared with the kernel's own load and store), is the device's narrowing and widening
/// alone: at most 40 words. A load also decodes
@@ -2158,35 +2064,31 @@ fn srgb_packs_read_no_table() {
/// `frem`, other formats, and a chunk wider than four lanes never do.
#[test]
fn half_arithmetic_on_the_device_follows_the_profile() {
use super::super::F16Basis;
let mut controlled = 0;
for (stem, p) in committed_profiles().expect("profiles") {
let controls = super::super::narrow::half_controls(&p);
let basis = controls.then_some(F16Basis::Controlled);
for op in [AirBin::FAdd, AirBin::FSub, AirBin::FMul] {
for lanes in 1..=4 {
assert_eq!(
super::super::f16_arithmetic(&p, op, vec(half(), lanes)),
basis,
controls,
"{stem}: {op:?} on {lanes} lanes"
);
}
for f in [vec(half(), 8), float(32), bfloat(), float(64)] {
assert_eq!(
super::super::f16_arithmetic(&p, op, f),
None,
assert!(
!super::super::f16_arithmetic(&p, op, f),
"{stem}: {op:?} on {f:?}"
);
}
}
for op in [AirBin::FDiv, AirBin::FRem] {
assert_eq!(
super::super::f16_arithmetic(&p, op, half()),
None,
assert!(
!super::super::f16_arithmetic(&p, op, half()),
"{stem}: {op:?}"
);
}
controlled += usize::from(basis == Some(F16Basis::Controlled));
controlled += usize::from(controls);
}
assert!(
controlled >= 2,
+1 -4
View File
@@ -99,10 +99,7 @@ pub struct Declared {
/// Declare the plan's module-scope objects: the access family's views, the push block, then
/// every other family's objects.
fn declare(mb: &mut ModuleBuilder, plan: &Plan) -> BResult<Declared> {
// Before any instruction: every multiply the device must round on its own takes the
// profile's form.
mb.product_form(plan.families.arith.product);
// And every `half` rounding's quantize the device's form.
// Before any instruction: every `half` rounding's quantize the device's form.
mb.set_quantize_form(plan.families.arith.quantize);
mb.set_native_half(plan.families.arith.native_half);
mb.set_native_half_nans(plan.families.arith.native_half_nans);
@@ -3046,8 +3046,7 @@ fn names_class(fb: &mut FunctionBuilder<'_>, index: SValue, class: TexelClass) -
/// another class widens them (`reinterpret`), so a store of it moves those bits as the slot's
/// does, a NaN's included. Merged as values, each arm's `half` would be the device's widening of
/// its bits, selected against the zero a null handle reads and merged with the other arms'; Metal's
/// compiler does not fold the widening of such a merge back to the bits (`narrow::moves_unfolded`),
/// and on the Apple M3 Max a NaN's bits became `0x7E00` there. The own arm's bits are its texel's
/// compiler does not fold the widening of such a merge back to the bits, and on the Apple M3 Max a NaN's bits became `0x7E00` there. The own arm's bits are its texel's
/// narrowing (`narrow::to_bits`), the device's conversion of a `half` value, which a store of the
/// merged value took before.
fn read_crossed(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BResult<SValue> {
@@ -3229,8 +3228,6 @@ fn write(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, w: &Write) -> BResul
}
ImageRef::Slot(_) => texel,
};
// The write's notes account for the texel's stored NaN (`moves_unfolded`).
fb.module().note_stored_texel(texel);
let mem = texel_memory(cx, fb, &w.image)?;
// A write to a sparse texture is dropped.
let kept = sparse_writes_kept(cx, fb, &w.image)?;
@@ -3416,7 +3413,6 @@ fn slice<'c>(cx: &mut EmitCx<'c>, fb: &mut FunctionBuilder<'_>, s: &Slice) -> BR
lanes: 4,
};
let texel = to_image(fb, &decl, form, held)?;
fb.module().note_stored_texel(texel);
let ty = vec(fb, u, dims)?;
let delta = if dims == 2 {
fb.composite_construct(ty, &[x, y])?
+18 -62
View File
@@ -1010,8 +1010,7 @@ pub struct TexturePlan {
/// conversion because it stores Metal's half (`MetalHalfStorageWrites`) and its NaN
/// (`MetalHalfStorageNans`), a write that may reach a normalized format, because it stores
/// Metal's codes (`MetalNormStorageWrites`), and a `half` texel's NaN to a 16-bit float format
/// (`MetalHalfTexelWrites`); and a `half` read's NaN of a 32-bit float or packed small float
/// texel (`MetalHalfConversion`, `half_texel_nans`). The module requires them.
/// (`MetalHalfTexelWrites`). The module requires them.
pub storage_properties: BTreeSet<crate::device::requirements::VkProperty>,
}
@@ -1678,10 +1677,7 @@ pub enum OneTexel {
/// none of the families (the slot's `UnmeasuredTexels` specialization), a 16-bit normalized grid
/// (`BicubicTexels::WIDE16`: three steps of each round twice), and a sample of a 32-bit float
/// texel (`BicubicTexels::LINEAR`: Metal rounds toward zero, saturating), tests of the bound
/// format the runtime announces at a draw or dispatch binding such a texture. Not a sample's of a
/// 32-bit float texel on a profile that takes `DriverDeviation::MetalHalfConversion` (the module
/// then requires its property): there the device's `half` of every `float` word a read, sample or
/// gather hands back is measured to be Metal's (`device::driver_facts`). A heap color
/// format the runtime announces at a draw or dispatch binding such a texture. A heap color
/// texture's and a depth texture's access records it outright.
pub(crate) fn half_texels(
cx: &mut SelectCx<'_>,
@@ -1708,22 +1704,9 @@ pub(crate) fn half_texels(
[NoteTest::equal(NoteOn::Unmeasured(index), 1, 1)].into(),
[NoteTest::differ(NoteOn::Bound(index), B::WIDE16, 0)].into(),
];
// A sample of a 32-bit float texel, but on a profile that takes
// `DriverDeviation::MetalHalfConversion`, whose `half` of every `float` word a read, sample or
// gather hands back is measured to be Metal's (the module then requires its property).
// A sample of a 32-bit float texel.
if sample {
match cx
.profile
.takes_driver_deviation(DriverDeviation::MetalHalfConversion)
{
true => {
cx.families
.texture
.storage_properties
.insert(crate::device::requirements::VkProperty::MetalHalfConversion);
}
false => when.push([NoteTest::differ(NoteOn::Bound(index), B::LINEAR, 0)].into()),
}
when.push([NoteTest::differ(NoteOn::Bound(index), B::LINEAR, 0)].into());
}
cx.note_when(PrecisionNote::HalfTexelConversion, when, m)?;
let slot = slot_of(cx, index)?.slot;
@@ -1740,10 +1723,7 @@ pub(crate) fn half_texels(
/// only where the class of the format bound there may hold a NaN (none of `TexelFormat::NAN_FREE`'s
/// families): a test of `SpecKey::BoundTexelFormat`, which the runtime reads from the bound texture
/// and no pipeline's key carries. A normalized, sRGB or extended-range texel decodes to no NaN, so
/// the device's encoding of one cannot show. On a profile that takes
/// `DriverDeviation::MetalHalfConversion` (the module then requires its property), not where the
/// class is a 32-bit float or packed small float one either: the `half` the device makes of such a
/// texel is measured to be Metal's, its NaN `0x7e00` (`device::driver_facts`). Of a heap's element
/// the device's encoding of one cannot show. Of a heap's element
/// or a depth texture, wherever it reads.
pub(crate) fn half_texel_nans(
cx: &mut SelectCx<'_>,
@@ -1753,27 +1733,13 @@ pub(crate) fn half_texel_nans(
) -> Result<(), Error> {
match image {
ImageRef::Slot(index) if !shape.depth => {
use crate::metal::bicubic::BicubicTexels as B;
use crate::metal::texel_format::TexelFormat;
let bound = |mask, bits| NoteTest::equal(NoteOn::Bound(index), mask, bits);
let when = match cx
.profile
.takes_driver_deviation(DriverDeviation::MetalHalfConversion)
{
// A half-float class, and a class of no family.
true => {
cx.families
.texture
.storage_properties
.insert(crate::device::requirements::VkProperty::MetalHalfConversion);
let family = B::LINEAR | B::HALF | TexelFormat::NAN_FREE;
vec![
[bound(family, B::HALF), bound(TexelFormat::PACKED_MASK, 0)].into(),
[bound(family, 0)].into(),
]
}
false => vec![[bound(TexelFormat::NAN_FREE, 0)].into()],
};
let when = vec![[NoteTest::equal(
NoteOn::Bound(index),
TexelFormat::NAN_FREE,
0,
)]
.into()];
cx.note_when(PrecisionNote::DeviceNanEncoding, when, m)
}
_ => {
@@ -2374,10 +2340,7 @@ const NAN_FAMILIES: [(
VkProperty::MetalHalfTexelWrites,
)),
),
(
NAN_WIDE,
Some((DriverDeviation::MetalNanMoves, VkProperty::MetalNanMoves)),
),
(NAN_WIDE, None),
(
NAN_SMALL,
Some((
@@ -2396,15 +2359,14 @@ const NAN_FAMILIES: [(
/// `Private`). The write stores the half widened, its NaN's payload in the significand's top bits,
/// which the device converts: a 16-bit float channel's NaN is Metal's on a device of
/// `DriverDeviation::MetalHalfTexelWrites` (the module requires its property); a 32-bit one's is
/// the widened `float`'s bits as written, Metal's `0x7fc00000` where the device's widening is
/// Metal's (`DriverDeviation::MetalNanMoves`, whose property the module then requires); a packed
/// the widened `float`'s bits as written, the device's widening's; a packed
/// small float one's is Metal's on a device of `DriverDeviation::MetalSmallFloatNans`, which
/// stores every `float` NaN there as Metal does (the module requires its property); and every
/// other float channel's is the device's.
///
/// The write records `PrecisionNote::DeviceNanEncoding` where the stored NaN stays the device's:
/// a 16-bit float channel's on a profile without `DriverDeviation::MetalHalfTexelWrites`, a 32-bit
/// one's without `DriverDeviation::MetalNanMoves`, a packed small float one's without
/// one's, a packed small float one's without
/// `DriverDeviation::MetalSmallFloatNans`, and a float channel's of none of those families (a
/// format that may hold a NaN). A slot whose choice declares no format (or a variant that states
/// none) records it under the format bound there (`m` charged for the clauses), and a heap
@@ -2419,14 +2381,13 @@ pub(super) fn half_write_nans(
) -> Result<(), Error> {
use crate::device::requirements::VkProperty;
use crate::vk::NumericFormat as N;
// Whether the stored NaN is exact (`Exact`), a 16-bit float channel's (`Sixteen`), a 32-bit
// one's (`Wide`) or a packed small float one's (`Small`), each Metal's on its measured
// deviation, or the device's (`Device`).
// Whether the stored NaN is exact (`Exact`), a 16-bit float channel's (`Sixteen`) or a packed
// small float one's (`Small`), each Metal's on its measured deviation, or the device's
// (`Device`).
#[derive(PartialEq)]
enum Stored {
Exact,
Sixteen,
Wide,
Small,
Device,
Bound(u32),
@@ -2440,7 +2401,6 @@ pub(super) fn half_write_nans(
};
match (b.color, b.component_bits, b.packed_bits) {
(Some(N::Sfloat), Some(16), None) => Stored::Sixteen,
(Some(N::Sfloat), Some(32), None) => Stored::Wide,
(Some(N::Sfloat | N::Ufloat), _, _) => Stored::Device,
_ => Stored::Exact,
}
@@ -2492,10 +2452,7 @@ pub(super) fn half_write_nans(
VkProperty::MetalHalfTexelWrites,
)),
),
(
[bound(family, B::LINEAR), bound(packed, 0)].into(),
Some((DriverDeviation::MetalNanMoves, VkProperty::MetalNanMoves)),
),
([bound(family, B::LINEAR), bound(packed, 0)].into(), None),
(
[bound(packed, PackedTexels::SmallFloat.class().0)].into(),
Some((
@@ -2521,7 +2478,6 @@ pub(super) fn half_write_nans(
DriverDeviation::MetalHalfTexelWrites,
VkProperty::MetalHalfTexelWrites,
)),
Stored::Wide => Some((DriverDeviation::MetalNanMoves, VkProperty::MetalNanMoves)),
Stored::Small => Some((
DriverDeviation::MetalSmallFloatNans,
VkProperty::MetalSmallFloatNans,
+25 -84
View File
@@ -555,9 +555,7 @@ pub enum PrecisionNote {
/// NaN operand's answer may be a number there (`precise::sin`, `precise::cos` and
/// `precise::sincos` of a NaN answer `0` on the Apple M3 Max through MoltenVK 1.4.2, where
/// Metal answers the NaN). Not recorded by precise `fmod`, whose answer is the one right value on
/// every device, nor, on a device whose `float` functions are Metal's own, in an entry Metal
/// compiles with fast math ([`EntryMath::Fast`]) by a call the device answers as Metal's own
/// function; there its fast `sinpi`, `cospi`, and `tanpi`, near-equivalents, still record it.
/// every device.
DeviceTranscendentals,
/// Float reductions use the device's association order.
ReductionOrder,
@@ -565,15 +563,9 @@ pub enum PrecisionNote {
/// arithmetic, comparisons, and functions as the zero of its sign and flushes a denormal result
/// to one, where a Vulkan device keeps or flushes them by its own float controls (this
/// translation declares no `DenormFlushToZero`). Recorded where the module leaves an
/// operation's denormals to a device not measured to read them as Metal does: `+ - *`, the
/// comparisons, `fma`, `dot`, `sqrt`, `rsqrt`, `trunc`, `rint` and `ldexp` on `float` (by the
/// device's products) but on a device that takes
/// the measured `DriverDeviation::MetalFloatDenormals`, and those on such a device too in an
/// entry that declares the 16-bit float controls, where a driver may keep them (NVIDIA's on
/// the RTX 3090 and the RTX 5080 Laptop GPU) and no query tells which; `fneg`, `fabs`, `floor`
/// and `ceil` on
/// `float` but on a device that takes the measured `DriverDeviation::MetalUnaryDenormals`; and
/// on every device the divisions and the remainder, the device's maths functions
/// operation's denormals to the device: `+ - *`, the comparisons, `fma`, `dot`, `sqrt`,
/// `rsqrt`, `trunc`, `rint` and `ldexp` on `float` (by the device's products), `fneg`, `fabs`,
/// `floor` and `ceil` on `float`, the divisions and the remainder, the device's maths functions
/// (`fast::fmod`'s fused multiply-add, `sign` and `fract` among them), `mix` by `FMix`, `fast::sqrt`
/// by `Sqrt`, `dot` of vectors of other than two to four lanes, whose chunks' products the
/// device sums where Metal flushes each one below `2^-126`, beside their own notes, and a
@@ -638,10 +630,7 @@ pub enum PrecisionNote {
/// precision bounds (e.g. 2.5 ULP division, a possibly unfused `Fma`) rather than correct
/// rounding. A fast (`arcp`) division is the device's `OpFDiv`, where Metal's is `x` times a
/// reciprocal it rounds within about 0.64 ulp but not correctly. Not recorded by precise
/// `fmod`, whose answer is the one right value on every device, nor, on a device whose `float`
/// functions are Metal's own (MoltenVK), in an entry Metal compiles with fast math
/// ([`EntryMath::Fast`]), by a fast division, which is Metal's own there, or by a call the
/// device answers as Metal's own function.
/// `fmod`, whose answer is the one right value on every device.
DeviceArithmetic,
/// Float operations LLVM requires to keep signed zeros, infinities, and NaNs run without
/// `SignedZeroInfNanPreserve`, which the device does not support at their width. Without the
@@ -830,11 +819,7 @@ pub enum PrecisionNote {
/// pixel fetch of a `half` texel: Metal hands back the texel's own NaN, sign and payload, and
/// Vulkan states no encoding for a 16-bit float texel's decode (MoltenVK answers the canonical
/// NaN for every one); on a device that rounds a `half` through its conversion under the float
/// controls (ANV, RADV), the NaN that conversion makes of the device's decode. Not by such an
/// access at a texture slot bound to a 32-bit float or packed small float format on a profile
/// that takes [`DriverDeviation::MetalHalfConversion`](crate::error::DriverDeviation::MetalHalfConversion),
/// whose `half` of such a texel is measured to be Metal's (`0x7e00` for its NaN); the module
/// then requires `VkProperty::MetalHalfConversion`. Also recorded
/// controls (ANV, RADV), the NaN that conversion makes of the device's decode. Also recorded
/// by a `half` texel's write to a storage texture that may hold a float format, a slot whose
/// storage choice declares none or a heap element: Metal stores a 16-bit float texel's NaN as
/// the half's own bits and a 32-bit or packed small float one's as its canonical NaN, and the
@@ -867,9 +852,7 @@ pub enum PrecisionNote {
/// device converts the NaN as it likes, where Metal's fill keeps a half NaN's sign and payload
/// and makes a small float's all ones. Not recorded by a texture write of a constant texel none
/// of whose lanes is a NaN, nor where the write's stored NaN is measured to be Metal's: a
/// `half` texel's write to a 32-bit float format on a profile that takes
/// `DriverDeviation::MetalNanMoves` (MoltenVK on the Apple M3 Max's macOS 27 identity), and a
/// `float` or `half` texel's write to `RG11B10Float` on one that takes
/// `float` or `half` texel's write to `RG11B10Float` on a profile that takes
/// `DriverDeviation::MetalSmallFloatNans` (that identity and lavapipe) (the module then
/// requires the matching `VkProperty`). Validation derives no tolerance and no explanation from
/// it, as for `DeviceDenormals`.
@@ -953,10 +936,7 @@ pub enum PrecisionNote {
/// result, and its nearest even `half` is Metal's `half` but for the classes the note is
/// recorded under, by the slot's bound format (`SpecKey::TexelFormat`): a 32-bit float
/// texel's sample, which Metal rounds toward zero (within one `half` ulp, but past `±65504` the
/// infinity of its sign where Metal saturates to `±65504`), but on a profile that takes
/// [`DriverDeviation::MetalHalfConversion`](crate::error::DriverDeviation::MetalHalfConversion),
/// whose `half` of every `float` word a read, sample or gather hands back is measured to be
/// Metal's (the module then requires `VkProperty::MetalHalfConversion`); a 16-bit normalized texel, whose
/// infinity of its sign where Metal saturates to `±65504`); a 16-bit normalized texel, whose
/// `float` steps `65455 / 65535`, `65519 / 65535` and `32759 / 32767` round twice (one `half`
/// ulp); and a format whose conversion is not measured (unbounded). A heap element and a depth
/// texture record it wherever they are accessed. A two-plane YCbCr texture on the grid `8192`
@@ -1757,21 +1737,15 @@ pub enum PrecisionNote {
/// computed `half` NaN is `0x7FFF` (where 18 C3 cases differed in NaNs, signs of zero,
/// `atan2` and `pow` at special operands, and `half` texel and pack conversions).
///
/// Not recorded for that rounding on a profile that takes
/// [`DriverDeviation::MetalHalfConversion`](crate::error::DriverDeviation::MetalHalfConversion)
/// (MoltenVK on the Apple M3 Max's macOS 27 identity) where every `half` the module rounds
/// through the conversion is a conversion of a `float` the function holds (an AIR `fptrunc` or
/// `air.convert` from `float`, whatever computed the `float`) or of a texel's value, measured to
/// answer Metal's `half(float)` there; the module then requires
/// `VkProperty::MetalHalfConversion`. A texel's value is an image instruction's texel, a texel
/// the module decodes itself (an extended-range, padded or bfloat code) or a merge of texels (a
/// heap read's fetched texel and its decode routine's): where Metal's `half` texel is not that
/// rounding of the value, the access records its own note ([`PrecisionNote::HalfTexelConversion`],
/// outright for a heap element; [`PrecisionNote::DevicePackConversion`] for a decoded texel). A
/// `half` operation or function the module computes in `float` and rounds keeps this note
/// there (Metal's `half` `tanh` answers 7 of the 65,536 `half`s otherwise than the conversion
/// of its `float` `tanh`), as does every other rounding
/// (`lower::arith::narrow::rounds_unmeasured`).
/// Recorded for every such rounding, a conversion of a `float` the function holds (an AIR
/// `fptrunc` or `air.convert` from `float`), of a texel's value, or of a `half` operation or
/// function the module computes in `float` (Metal's `half` `tanh` answers 7 of the 65,536
/// `half`s otherwise than the conversion of its `float` `tanh`). A texel's value is an image
/// instruction's texel, a texel the module decodes itself (an extended-range, padded or bfloat
/// code) or a merge of texels (a heap read's fetched texel and its decode routine's): where
/// Metal's `half` texel is not that rounding of the value, the access records its own note
/// too ([`PrecisionNote::HalfTexelConversion`], outright for a heap element;
/// [`PrecisionNote::DevicePackConversion`] for a decoded texel).
///
/// Every `half` a module reads from its bits (a load, a reinterpretation, a texel's bits) is
/// the device's widening of them, on every device: an `OpFConvert` to 32 bits of the bits read
@@ -1780,10 +1754,8 @@ pub enum PrecisionNote {
/// bits) where they are not the bits it was read from: the device's narrowing of it, an
/// `OpFConvert` to 16 bits read as a word with `shaderFloat16`, `GLSL.std.450 PackHalf2x16`
/// without it. A module that reads or encodes one records this note too where that widening
/// or narrowing is neither under the float controls' `DenormPreserve` for 16 bits (ANV, RADV,
/// NVIDIA) nor measured to read and narrow every `half` as Metal's (MoltenVK's conversion is,
/// `DriverDeviation::MetalHalfArithmetic`, and the module requires it there), so on every
/// device without `shaderFloat16`: its bound is the last two items', a half denormal read or
/// or narrowing is not under the float controls' `DenormPreserve` for 16 bits (ANV, RADV,
/// NVIDIA), so on every device without `shaderFloat16`: its bound is the last two items', a half denormal read or
/// encoded as the zero of its sign on a device that flushes 16-bit denormals (the Vulkan spec
/// lets a device flush a denormal "obtained via unpacking an integer" without `DenormPreserve`
/// for 16 bits, and gives `UnpackHalf2x16` and `PackHalf2x16` implementation-defined
@@ -1833,13 +1805,8 @@ pub enum PrecisionNote {
/// (an `OpFConvert` to 16 bits with `shaderFloat16`, `PackHalf2x16` without it), and a NaN
/// narrows to a NaN whose bits are the device's, where Metal keeps a `half` NaN's sign and
/// payload. Every other `half` widens to its value and narrows to its bits, but a denormal on a
/// device that may flush 16-bit ones ([`PrecisionNote::NativeHalfConversion`]). Not recorded,
/// on a device whose moves of a NaN are measured to be Metal's (MoltenVK on the Apple M3 Max's
/// macOS 27 identity, `DriverDeviation::MetalNanMoves`), for a `float` `fneg` or `fabs`, a
/// `half`'s widening to `float` or `fabs`, or a module's reads and encodes of a `half`'s bits
/// where it moves its `half` values through the registers alone, or into a texture write's
/// texel, whose store the write's [`PrecisionNote::DeviceNanEncoding`] accounts for.
/// Validation derives no tolerance from it.
/// device that may flush 16-bit ones ([`PrecisionNote::NativeHalfConversion`]). Validation
/// derives no tolerance from it.
NativeNanEncoding,
/// Native device maths: Metal's `fmin`, `fmax`, `min3`, `max3`, `clamp` or `saturate` (its
/// `clamp(x, +0, 1)`) on `float` or `half` is the device's `GLSL.std.450` `NMin`, `NMax` or
@@ -1863,9 +1830,8 @@ pub enum PrecisionNote {
/// Native device maths: Metal's `dot` on `float` and `half` is the device's `OpDot` (a `half`
/// one summed in `float` and rounded once to `half`, or the device's 16-bit `OpDot` where the
/// module computes `half` in 16 bits under the 16-bit float controls and holds its operands
/// there, `spirv::half_hold`), not Metal's fused chain of its products, on every device but
/// for a `float` one where the device's functions are Metal's own (MoltenVK, Metal's own
/// `dot`). **Recorded bound:** a `float` `dot` of `n` lanes within
/// there, `spirv::half_hold`), not Metal's fused chain of its products, on every device.
/// **Recorded bound:** a `float` `dot` of `n` lanes within
/// `(3n - 1) * 2^-24 * sum |a_i * b_i|` of Metal's chain, plus `n * 2^-126` where a product is
/// an `f32` denormal the device keeps (Vulkan's `OpDot` inherits `OpFMul`'s and `OpFAdd`'s
/// rounding, `2n - 1` roundings, where Metal's chain rounds `n` times); a `half` one rounded
@@ -1878,8 +1844,7 @@ pub enum PrecisionNote {
/// (a `half` one computed in `float` and rounded once to `half`, or the device's 16-bit `FMix`
/// where the module computes `half` in 16 bits under the 16-bit float controls and holds its
/// operands there, `spirv::half_hold`), not Metal's `fma(t, y, fma(-t, x, x))`, on every
/// device but for a `float` one where the device's functions are Metal's own (MoltenVK,
/// Metal's own `mix`). **Recorded bound:** a `float` result within
/// device. **Recorded bound:** a `float` result within
/// `2^-21 * (|x * (1 - t)| + |y * t|)` of Metal's (Vulkan's `FMix` inherits
/// `x * (1 - t) + y * t`'s rounding, four roundings, where Metal's rounds twice); a `half` one
/// rounded from `float` within `3 * 2^-10 * (|x * (1 - t)| + |y * t|) + 2^-23`, and a 16-bit
@@ -1900,14 +1865,7 @@ pub enum PrecisionNote {
/// encode the byte of that table's step. Also: a write of an 8-bit sRGB storage texture held
/// through its UNORM alias (`StorageImageClass::SrgbEncode`, Vulkan having no sRGB storage
/// view), at a slot or held by an argument buffer, encodes by `unorm4x8_srgb`'s pack.
/// Recorded on every device but for
/// a `float` conversion of the four named formats on a device whose functions are Metal's own
/// (MoltenVK: Metal's own `pack_float_to_*` and `unpack_*_to_float`), and but for the forms
/// measured to answer Metal's on a profile that takes
/// [`DriverDeviation::MetalPackConversions`](crate::error::DriverDeviation::MetalPackConversions)
/// (MoltenVK on the Apple M3 Max's macOS 27 identity: `unorm565` in `float`, and in `half`
/// `unorm4x8`, `snorm4x8`, `unorm10a2` and `unorm565` both ways and `unorm2x16` and
/// `snorm2x16` packed), which require `VkProperty::MetalPackConversions`. **Recorded bound:**
/// Recorded on every device. **Recorded bound:**
/// Vulkan bounds the instructions by their definition (`round(clamp(c) * scale)` and
/// `c / scale`): a packed code within one of Metal's, apart only where `clamp(c) * scale` lies
/// within its `float` rounding of a half-integer (`Round` may tie either way); an unpacked
@@ -2337,23 +2295,6 @@ pub enum PrecisionNote {
DeviceFragmentRuns,
}
/// The math mode of an entry's module, which decides, on a device whose `float` functions are
/// Metal's own (MoltenVK), how Metal compiles the entry's functions and its fast divisions, and
/// so which of its operations record a precision note: a module declares `SignedZeroInfNanPreserve`
/// where a `float` operation of the entry lacks one of the `nnan`, `ninf`, and `nsz` flags (an
/// entry Metal compiled without fast math) and the device supports the mode at the operation's
/// width. [`PrecisionNote::of_float_operator`] and [`PrecisionNote::of_math_call`] read it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum EntryMath {
/// The module declares no `SignedZeroInfNanPreserve`: Metal compiles it with fast math, its
/// fast division and its fast functions Metal's own.
Fast,
/// The module declares `SignedZeroInfNanPreserve`: Metal compiles it with its precise
/// functions and a correctly rounded division.
Precise,
}
/// Which lowering strategies a module used, with their word costs.
///
/// Keys name `Strategy` variants (`Family::Variant`) for reporting only; translation never reads
+8 -87
View File
@@ -3266,28 +3266,17 @@ fn lower_bounded<K>(
let device_quantize = quantize == crate::spirv::builder::QuantizeForm::Device
&& crate::lower::arith::narrow::quantizes(&module);
// A `half` rounded through the device's conversion to 16 bits and back, with no quantize: the
// module records the native note, but where the device's conversion is measured to answer
// Metal's (`DriverDeviation::MetalHalfConversion`) and every such rounding is of a form the
// measurement covers (a `float` the function converts, or an image instruction's texel),
// which the module then requires.
// module records the native note.
let converts = quantize == crate::spirv::builder::QuantizeForm::Converted
&& crate::lower::arith::narrow::rounds_by_conversion(&module, m)?;
let measured_conversion = converts
&& p.takes_driver_deviation(crate::error::DriverDeviation::MetalHalfConversion)
&& !crate::lower::arith::narrow::rounds_unmeasured(&module, m)?;
// A `half` read from its bits by the device's widening, or encoded to them by its narrowing
// (every profile: `OpFConvert` with `shaderFloat16`, `UnpackHalf2x16` and `PackHalf2x16`
// without): a NaN's bits are the device's, recorded. Under the float controls its denormals
// are Metal's, as a single conversion's, also on a driver that folds the round trip; on a
// device whose conversion is measured to read and
// narrow every `half` as Metal's (`DriverDeviation::MetalHalfArithmetic`) the module requires
// that fact; elsewhere the device may flush them, within the native conversion's note.
// are Metal's, as a single conversion's, also on a driver that folds the round trip; elsewhere
// the device may flush them, within the native conversion's note.
let widens = crate::lower::arith::narrow::widens_bits(&module, m)?
|| crate::lower::arith::narrow::encodes_bits(&module, m)?;
let measured_widening = widens
&& quantize == crate::spirv::builder::QuantizeForm::Converted
&& p.takes_driver_deviation(crate::error::DriverDeviation::MetalHalfArithmetic);
let native_widening = widens && !controls && !measured_widening;
let native_widening = widens && !controls;
// A `half` rounded through the conversion and its widening under the float controls: Metal's
// `half(float)` by the Vulkan spec, but a driver's compiler may fold the pair into the value it
// started from or fuse the `float` operation computing the value into the narrowing and round
@@ -3295,17 +3284,6 @@ fn lower_bounded<K>(
// the rounding.
let controlled = quantize == crate::spirv::builder::QuantizeForm::Controlled;
let fused = controlled && crate::lower::arith::narrow::rounds_by_conversion(&module, m)?;
// Its NaN's bits, and those of a `half` held widened that a widening to `float` or a `half`
// `fabs` moves: Metal's where the device's widening and narrowing are measured to answer
// them (`DriverDeviation::MetalNanMoves`) and the module moves its `half` values only as
// measured, which it then requires; the device's, recorded, elsewhere.
let held_moves = plan.families.arith.held_nan_moves;
let unfolded = (widens || held_moves)
&& p.takes_driver_deviation(crate::error::DriverDeviation::MetalNanMoves)
&& crate::lower::arith::narrow::moves_unfolded(&module, m)?;
let moved_nans = widens
&& p.takes_driver_deviation(crate::error::DriverDeviation::MetalNanMoves)
&& !unfolded;
// A `half` rounded through the device's conversion and its widening, each decorated
// `NoContraction`, under the float controls that make it Metal's, computed by the device's
// 16-bit arithmetic, which they make Metal's too, or read from its bits by the device's
@@ -3320,16 +3298,13 @@ fn lower_bounded<K>(
module.declare_modes(&modes)?;
}
// Native half rounding and widening: a module that rounds through the device's quantize or
// conversion, or widens a `half` by the device where that is not measured or controlled to be
// Metal's, records each kind, and requires no fact.
// conversion, or widens a `half` by the device where that is not controlled to be Metal's,
// records each kind, and requires no fact.
let native_half = [
(
(widens && !moved_nans) || (held_moves && unfolded),
PrecisionNote::NativeNanEncoding,
),
(widens, PrecisionNote::NativeNanEncoding),
(device_quantize, PrecisionNote::NativeHalfQuantize),
(
(converts && !measured_conversion) || native_widening || fused,
converts || native_widening || fused,
PrecisionNote::NativeHalfConversion,
),
];
@@ -3404,39 +3379,6 @@ fn lower_bounded<K>(
false => VkProperty::MetalSampler,
});
}
// A NaN's bits left to the device's widening, narrowing, negation or magnitude because they
// are Metal's.
if plan.families.arith.nan_moves || moved_nans || (held_moves && !unfolded) {
requirements
.properties
.insert(crate::device::requirements::VkProperty::MetalNanMoves);
}
// A `half` rounded by the device's conversion with no note because it is Metal's.
if measured_conversion {
requirements
.properties
.insert(crate::device::requirements::VkProperty::MetalHalfConversion);
}
// A packed format's conversion left to the device with no note because it is Metal's.
if plan.families.arith.metal_packs {
requirements
.properties
.insert(crate::device::requirements::VkProperty::MetalPackConversions);
}
// Metal's `float` and `half` minimum and maximum family left to the device's `NMin`, `NMax`
// and `NClamp` because they are Metal's.
if plan.families.arith.device_min_max {
requirements
.properties
.insert(crate::device::requirements::VkProperty::MetalMinMax);
}
// `half` `+ - * /` left to the device's 16-bit arithmetic because it is Metal's, and a `half`
// read from its bits by the device's widening, whose denormals that measurement makes Metal's.
if plan.families.arith.f16_arith || measured_widening {
requirements
.properties
.insert(crate::device::requirements::VkProperty::MetalHalfArithmetic);
}
// A fragment's simdgroup lane read from its subgroup lane because the device's fragment
// subgroups are Metal's simdgroups.
if plan.families.simd.metal_lane {
@@ -3451,27 +3393,6 @@ fn lower_bounded<K>(
.properties
.insert(crate::device::requirements::VkProperty::MetalFullQuads);
}
// `float` denormals left to the device because it reads them as Metal does: measured in
// entries that declare no float-controls mode. In one that declares the 16-bit controls a
// driver may keep them (NVIDIA's on the RTX 3090 and the RTX 5080 Laptop GPU), and no query
// tells which: there they are the device's own on every device, noted.
if plan.families.arith.device_denormals {
if !declares_controls {
requirements
.properties
.insert(crate::device::requirements::VkProperty::MetalFloatDenormals);
} else if !precision.contains(&PrecisionNote::DeviceDenormals) {
precision.push(PrecisionNote::DeviceDenormals);
precision.sort_unstable();
}
}
// The negations, absolute values, floors and ceilings whose `float` denormals the device
// reads as Metal does.
if plan.families.arith.unary_denormals {
requirements
.properties
.insert(crate::device::requirements::VkProperty::MetalUnaryDenormals);
}
// Center varyings read as they are as their pixel form, because the device reads them at
// the pixel center as Metal does.
if plan.families.stage_io.center_varyings_by_device {
+3 -3
View File
@@ -104,9 +104,9 @@ pub(crate) mod tile_map;
pub(crate) mod vertex;
pub use artifact::{
ComputePipeline, ComputePipelineMetalInfo, EntryMath, ModuleStats, PrecisionNote,
Reconvergence, RenderPipeline, RuntimeDependency, SpecClause, SpecConstant, SpecTest,
SpecializationLayout, SpecializedNote, StageModule, StrategyCensus, StrategyUse,
ComputePipeline, ComputePipelineMetalInfo, ModuleStats, PrecisionNote, Reconvergence,
RenderPipeline, RuntimeDependency, SpecClause, SpecConstant, SpecTest, SpecializationLayout,
SpecializedNote, StageModule, StrategyCensus, StrategyUse,
};
pub use descriptor::{
ColorAttachmentDescriptor, ComputePipelineDescriptor, DynamicLibraries, FunctionDescriptor,
+1 -5
View File
@@ -185,14 +185,10 @@ pub fn storage_buffers(a: &FunctionArtifact) -> u32 {
}
/// Whether artifact `a` leaves a NaN's bits to the device, which the interpreter does not model:
/// it records `PrecisionNote::NativeNanEncoding`, or it requires `VkProperty::MetalNanMoves`, whose
/// measured device answers Metal's bits where the interpreter's conversions answer their own.
/// it records `PrecisionNote::NativeNanEncoding`.
pub fn device_nan_bits(a: &FunctionArtifact) -> bool {
a.precision
.contains(&crate::pipeline::artifact::PrecisionNote::NativeNanEncoding)
|| a.requirements
.properties
.contains(&crate::device::requirements::VkProperty::MetalNanMoves)
}
/// A fresh per-attempt meter with the standard caps and no deadline.
+1 -1
View File
@@ -11,7 +11,7 @@ pub mod ops;
pub use function::FunctionBuilder;
pub(crate) use module::{geometry_per_vertex, mesh_arrayed, mesh_per_primitive};
pub use module::{ModuleBuilder, NarrowFmt, ProductForm, QuantizeForm};
pub use module::{ModuleBuilder, NarrowFmt, QuantizeForm};
#[cfg(test)]
mod tests;
@@ -90,16 +90,6 @@ pub struct ModuleBuilder {
/// Every result that carries a non-uniform descriptor element (`Inst::carries_non_uniform`):
/// decorated `NonUniform`, and refused where it would reach an undecorated operand.
pub(super) non_uniform: BTreeSet<Value>,
/// The narrowings to 16 bits of the conversion pairs that round a `half` in a form measured
/// to answer Metal's on the devices whose driver takes `DriverDeviation::MetalHalfConversion`
/// (`ModuleBuilder::note_measured_rounding`). Nothing emitted depends on it: the compile
/// reads it to decide `PrecisionNote::NativeHalfConversion`.
pub(super) measured_roundings: BTreeSet<Value>,
/// The texels the texture family's writes store (`ModuleBuilder::note_stored_texel`), whose
/// stored NaN the write's own notes account for (`lower::texture::half_write_nans` and
/// `half_storage_facts`). Nothing emitted depends on it: the compile reads it to decide
/// `PrecisionNote::NativeNanEncoding` (`lower::arith::narrow::moves_unfolded`).
pub(super) stored_texels: BTreeSet<Value>,
/// The `Function` variables the emitter holds workgroup uniform by construction
/// (`FunctionBuilder::note_uniform_var`). Nothing emitted depends on it: a record for the
/// checks of `spirv::testing::barriers`, kept only where they build.
@@ -156,9 +146,6 @@ pub struct ModuleBuilder {
/// The encode of a narrow vector computed for its lanes' stores in a block, with its offer
/// group (`FunctionBuilder::note_encode`).
pub(super) encodes: HashMap<(NarrowFmt, Value), (Value, BlockId, u32)>,
/// How a float multiply the device must round on its own is emitted
/// ([`ModuleBuilder::product_form`]).
pub(super) product_form: ProductForm,
/// How the lowering rounds an `f32` to `half` ([`ModuleBuilder::quantize_form`]).
quantize_form: QuantizeForm,
/// Whether that rounding is the device's own rather than one measured to be Metal's
@@ -172,27 +159,6 @@ pub struct ModuleBuilder {
half_controls: bool,
}
/// How a float multiply the device must round on its own and never fuse is emitted
/// ([`FunctionBuilder::binary_no_contraction`]). Lowering takes it from the profile's `float`
/// functions fact (`ArithPlan::product`). In either form an `f32` product by a constant with a
/// `-0.0` component multiplies by `+0.0` there and negates that component of the product.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ProductForm {
/// `OpFMul` decorated `NoContraction`, for a device whose driver compiles the SPIR-V itself:
/// the device rounds the product once, keeps a `-0` product, and folds a zero factor as
/// Metal does (`x · 0` to `0` where the multiply carries `nsz`). It has no addend a device
/// could answer for a zero product.
#[default]
Multiply,
/// `GLSL.std.450 Fma(a, b, -0.0)` decorated `NoContraction`, for a device whose SPIR-V reaches
/// Metal's compiler through SPIRV-Cross (MoltenVK, the profile whose `float` functions are
/// Metal's): SPIRV-Cross renders a `NoContraction` `OpFMul` as `fma(l, r, 0)`, which answers
/// `+0` for a `-0` product, and this form as `fma(a, b, -0.0)`, which Metal's compiler treats
/// as Metal treats its own multiply. `a · b + (-0.0)` is `a · b` exactly whether the device
/// fuses it or not.
NegativeZeroFma,
}
/// How the lowering rounds an `f32` to `half` (`lower::arith::narrow`): the device's own
/// rounding. Lowering takes it from the profile's `shaderFloat16` and float-controls properties
/// (`ArithPlan::quantize`). `Controlled` gives Metal's conversion to `half` (to nearest even on the
@@ -260,13 +226,6 @@ impl ModuleBuilder {
ModuleBuilder::default()
}
/// Emit every float multiply the device must round on its own in `form`. Emission sets it
/// before any instruction, from the profile's `float` functions fact; a builder that never
/// sets it emits [`ProductForm::Multiply`].
pub fn product_form(&mut self, form: ProductForm) {
self.product_form = form;
}
/// Round an `f32` to `half` in `form`. Emission sets it before any instruction, from the
/// profile; a builder that never sets it emits [`QuantizeForm::Device`].
pub fn set_quantize_form(&mut self, form: QuantizeForm) {
@@ -285,19 +244,6 @@ impl ModuleBuilder {
self.native_half = native;
}
/// Record `narrowed`, the narrowing to 16 bits of a conversion pair that rounds a `half` in a
/// form measured to answer Metal's where the driver takes
/// `DriverDeviation::MetalHalfConversion` (`narrow::round_measured`).
pub fn note_measured_rounding(&mut self, narrowed: Value) {
self.measured_roundings.insert(narrowed);
}
/// Record `texel`, a texel a texture write stores, whose stored NaN the write's own notes
/// account for (`lower::texture::emit`).
pub fn note_stored_texel(&mut self, texel: Value) {
self.stored_texels.insert(texel);
}
/// Whether the module's `half` rounding is the device's own
/// ([`ModuleBuilder::set_native_half`]).
pub fn native_half(&self) -> bool {
@@ -378,8 +324,6 @@ impl ModuleBuilder {
std::mem::size_of::<(GlobalId, crate::spv::Capability)>(),
)
+ tree_bytes(self.non_uniform.len(), std::mem::size_of::<Value>())
+ tree_bytes(self.measured_roundings.len(), std::mem::size_of::<Value>())
+ tree_bytes(self.stored_texels.len(), std::mem::size_of::<Value>())
+ map_bytes(&self.bits)
+ map_bytes(&self.lanes)
+ map_bytes(&self.inserts)
@@ -1376,8 +1320,6 @@ impl ModuleBuilder {
unwritten_buffers: self.unwritten_buffers,
enabling: self.enabling,
non_uniform: self.non_uniform,
measured_roundings: self.measured_roundings,
stored_texels: self.stored_texels,
#[cfg(test)]
uniform_vars: self.uniform_vars,
})
@@ -1,12 +1,11 @@
//! Arithmetic, bitwise, logical, comparison, linear-algebra, select, and bit-field constructors.
use crate::spirv::builder::function::FunctionBuilder;
use crate::spirv::builder::module::ProductForm;
use crate::spirv::builder::ops::{err, Num};
use crate::spirv::error::{BResult, OperandRule};
use crate::spirv::ids::{TypeId, Value};
use crate::spirv::ir::{
BinOp, ConstBits, ConstKind, Constant, Contraction, ConvOp, GlslOp, Inst, Shape, Type, UnOp,
BinOp, ConstBits, ConstKind, Constant, Contraction, ConvOp, Inst, Shape, Type, UnOp,
ValueOrigin,
};
@@ -70,19 +69,7 @@ impl FunctionBuilder<'_> {
/// the operation on its own and never fuses it with another. `op` must allow the decoration
/// ([`BinOp::allows_no_contraction`]).
///
/// A multiply (`FMul`) takes the module's [`ProductForm`]: an `OpFMul` decorated
/// `NoContraction` where the device's driver compiles the SPIR-V itself, or `GLSL.std.450
/// Fma(a, b, -0.0)` decorated `NoContraction` where it reaches Metal through SPIRV-Cross. `a *
/// b + (-0.0)` is `a * b` exactly whether the device fuses it or rounds the product and then
/// the sum (`x + (-0.0)` is `x` for every `x`, either zero included). SPIRV-Cross, which
/// MoltenVK uses, renders a `NoContraction` `OpFMul` as `fma(l, r, 0)`, which answers `+0` for
/// a `-0` product; it renders the `Fma` as `fma(a, b, -0.0)`. Elsewhere the `-0.0` addend is a
/// value the device may answer: Mesa folds `Fma(0, b, -0.0)` to it under `nsz`, where Metal's
/// multiply answers `+0`, and no per-instruction decoration keeps it from doing so on Mesa
/// 26.2. The `Fma`'s decoration is still needed: Mesa splits a contractable `Fma` into a
/// multiply and an add and folds the `-0.0` away, leaving a multiply that may be fused with a
/// following add allowing contraction (NIR's `fuse` option on older Mesa, or a backend such as
/// ACO). Mesa's SPIR-V reader marks a `NoContraction` result exact, so it is not split.
/// A multiply (`FMul`) is an `OpFMul` decorated `NoContraction`, which the device rounds once.
pub fn binary_no_contraction(&mut self, op: BinOp, a: Value, b: Value) -> BResult<Value> {
self.binary_with(op, a, b, Contraction::Forbidden)
}
@@ -220,13 +207,6 @@ impl FunctionBuilder<'_> {
return Ok(r);
}
}
if op == BinOp::FMul
&& contract == Contraction::Forbidden
&& self.mb().product_form == ProductForm::NegativeZeroFma
{
let z = self.negative_zero(a)?;
return self.glsl_with(GlslOp::Fma, &[a, b, z], Contraction::Forbidden);
}
self.emit(Inst::Binary { op, a, b, contract }, ty)
}
@@ -330,7 +310,7 @@ impl FunctionBuilder<'_> {
/// The product `op` of `a` and `b` where one of them is an `f32` constant with a `-0.0`
/// component, on every device: the product by that constant with each such component `+0.0`
/// (in the module's [`ProductForm`]), negated in those components of the result
/// (an `OpFMul`), negated in those components of the result
/// (`OpFNegate`, and an `OpVectorShuffle` of the product and its negation where only some
/// components are). `-(x · +0)` is `x · (−0)` for every `x`; a NaN's sign is the device's
/// either way. So no product the module emits has a `-0.0` factor beside a `+0.0` one, which a
@@ -428,24 +408,6 @@ impl FunctionBuilder<'_> {
self.module().const_value(id)
}
/// The `-0.0` of `v`'s float scalar or vector type: the sign bit alone in each component.
fn negative_zero(&mut self, v: Value) -> BResult<Value> {
let x = self.want(crate::spv::Op::FMul, 0, v, Num::is_float)?;
let s = self.module().constant(Constant::Scalar {
ty: x.elem,
bits: ConstBits(1u64 << (x.width - 1)),
})?;
let c = if x.n == 1 {
s
} else {
self.module().constant(Constant::Composite {
ty: x.ty,
parts: vec![s; usize::from(x.n)].into(),
})?
};
self.module().const_value(c)
}
/// The value of `v` when it is a plain `bool` constant.
pub fn const_bool(&self, v: Value) -> BResult<Option<bool>> {
Ok(match self.scalar_const(v)? {
@@ -1118,14 +1118,6 @@ fn rewrite(
}
block.term.for_each_value_mut(swap);
}
m.measured_roundings.retain(|v| !replaced.contains_key(v));
let texels = tree_bytes(m.stored_texels.len(), std::mem::size_of::<Value>());
charge(meter, ledger, texels)?;
m.stored_texels = m
.stored_texels
.iter()
.map(|v| replaced.get(v).copied().unwrap_or(*v))
.collect();
Ok(Some(held))
}
-2
View File
@@ -405,8 +405,6 @@ impl TypedModule {
};
let values = &self.values;
self.non_uniform.retain(|v| !removed(v, values));
self.measured_roundings.retain(|v| !removed(v, values));
self.stored_texels.retain(|v| !removed(v, values));
self.loops.retain(|l| at(&bmap, l.header.index()).is_some());
for l in &mut self.loops {
l.header = block(l.header);
@@ -1471,13 +1471,6 @@ pub struct TypedModule {
/// The values decorated `NonUniform`: every result that carries a non-uniform descriptor
/// element ([`Inst::carries_non_uniform`]), recorded as the builder appends it.
pub(in crate::spirv) non_uniform: std::collections::BTreeSet<Value>,
/// The narrowings to 16 bits of the conversion pairs that round a `half` in a form measured
/// to answer Metal's where the driver takes `DriverDeviation::MetalHalfConversion`
/// (`ModuleBuilder::measured_roundings`), recorded as the builder emits them.
pub(in crate::spirv) measured_roundings: std::collections::BTreeSet<Value>,
/// The texels the texture family's writes store, whose stored NaN the write's own notes
/// account for (`ModuleBuilder::stored_texels`), recorded as the builder emits them.
pub(in crate::spirv) stored_texels: std::collections::BTreeSet<Value>,
/// The `Function` variables the emitter holds workgroup uniform by construction: the `cont`
/// flag of a predicated loop that iterates together, which the lowering's uniformity analysis
/// proved. An in-memory record for checks (`spirv::testing::barriers`), kept only where they
@@ -1503,17 +1496,6 @@ impl TypedModule {
&self.consts
}
/// The narrowings to 16 bits of the conversion pairs that round a `half` in a form measured to
/// answer Metal's (`ModuleBuilder::note_measured_rounding`).
pub fn measured_roundings(&self) -> &std::collections::BTreeSet<Value> {
&self.measured_roundings
}
/// The texels the texture family's writes store (`ModuleBuilder::note_stored_texel`).
pub fn stored_texels(&self) -> &std::collections::BTreeSet<Value> {
&self.stored_texels
}
/// The SSA value of a constant.
pub fn const_value(&self, c: ConstId) -> BResult<Value> {
self.const_values
@@ -1854,8 +1854,6 @@ fn verify(
for (x, y) in pairs {
if m.value(x)?.ty != m.value(y)?.ty
|| m.non_uniform.contains(&x) != m.non_uniform.contains(&y)
|| m.measured_roundings.contains(&x) != m.measured_roundings.contains(&y)
|| m.stored_texels.contains(&x) != m.stored_texels.contains(&y)
{
return Ok(None);
}
@@ -5,7 +5,7 @@
use super::{assert_spirv_valid, float, int, vec};
use crate::spirv::builder::ops::group::GroupMode;
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder, ProductForm};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::ids::{FuncId, TypeId, Value};
use crate::spirv::ir::{
AtomicOp, BinOp, Constant, Contraction, ConvOp, ExecMode, ExecModel, GlslOp, GroupArith,
@@ -287,18 +287,10 @@ fn binary_operations() {
/// `NoContraction`: every float arithmetic opcode takes it, `spirv-val` accepts the decoration, and
/// exactly the decorated results carry it; other opcodes refuse it. A multiply rounded on its own
/// takes the module's [`ProductForm`]: an `OpFMul` decorated `NoContraction` by default, or
/// `GLSL.std.450 Fma(a, b, -0.0)` decorated `NoContraction`, its addend the `-0.0` of its type,
/// where the module's SPIR-V reaches Metal through SPIRV-Cross. An `Fma` built
/// without the decoration stays undecorated, and no other `GLSL.std.450` instruction takes it.
/// is an `OpFMul` decorated `NoContraction`. An `Fma` built without the decoration stays
/// undecorated, and no other `GLSL.std.450` instruction takes it.
#[test]
fn no_contraction_decorates_float_arithmetic() {
for form in [ProductForm::Multiply, ProductForm::NegativeZeroFma] {
no_contraction_under(form);
}
}
fn no_contraction_under(form: ProductForm) {
use crate::spirv::error::{BuildError, OperandRule};
let mut decorated = Vec::new();
let mut plain = Vec::new();
@@ -307,7 +299,6 @@ fn no_contraction_under(form: ProductForm) {
let m = compute(
|t| vec![t.f32_, t.vec4, t.f16, t.f64_, t.u32_],
|f, p, _| {
f.module().product_form(form);
let [x, xv, h, d, u] = p else { unreachable!() };
for a in [x, xv, h, d] {
for op in [BinOp::FAdd, BinOp::FSub, BinOp::FDiv, BinOp::FRem] {
@@ -384,51 +375,27 @@ fn no_contraction_under(form: ProductForm) {
assert!(plain_fma.is_some());
// Results are emitted in order, each operand's group holding its four decorated results,
// its plain multiply, and (as an `OpFMul`) its multiply without contraction.
let group = match form {
ProductForm::Multiply => 6,
ProductForm::NegativeZeroFma => 5,
};
let products = match form {
ProductForm::Multiply => fused.len(),
ProductForm::NegativeZeroFma => 0,
};
assert_eq!(
arith.len(),
decorated.len() + plain.len() + products,
"{form:?}"
);
let group = 6;
assert_eq!(arith.len(), decorated.len() + plain.len() + fused.len());
let plain_ids: Vec<u32> = arith
.chunks(group)
.filter_map(|c| c.get(4).copied())
.collect();
assert_eq!(plain_ids.len(), plain.len());
assert_eq!(targets.len(), decorated.len() + fused.len(), "{form:?}");
// Each multiply without contraction is, in the `Fma` form, one `Fma` decorated
// `NoContraction` whose addend is `-0.0`: the sign bit alone in its last word (`half`,
// `float`, `double`, and a `float` vector). The plain `Fma`, emitted last, is undecorated.
let (fused_fmas, plain_fmas) = fmas.split_at(fmas.len() - 1);
assert_eq!(fused_fmas.len(), fused.len() - products, "{form:?}");
let signs = [0x8000_0000u32, 0x8000_0000, 0x8000, 0x8000_0000];
for (&(r, addend), sign) in fused_fmas.iter().zip(signs) {
assert!(targets.contains(&r), "%{r} not decorated");
assert_eq!(constants.get(&addend), Some(&sign), "%{r}'s addend");
}
assert!(
!targets.contains(&plain_fmas[0].0),
"the plain Fma decorated"
);
if form != ProductForm::NegativeZeroFma {
// No `-0.0` addend at all: each multiply is the `OpFMul` after its group's plain one.
assert!(!constants
.values()
.any(|w| [0x8000_0000, 0x8000].contains(w)));
for c in arith.chunks(group).filter(|c| c.len() == group) {
assert!(targets.contains(&c[5]), "%{} not decorated", c[5]);
}
assert_eq!(targets.len(), decorated.len() + fused.len());
// The one `Fma`, the plain one, is undecorated.
assert_eq!(fmas.len(), 1);
assert!(!targets.contains(&fmas[0].0), "the plain Fma decorated");
// No `-0.0` addend at all: each multiply is the `OpFMul` after its group's plain one.
assert!(!constants
.values()
.any(|w| [0x8000_0000, 0x8000].contains(w)));
for c in arith.chunks(group).filter(|c| c.len() == group) {
assert!(targets.contains(&c[5]), "%{} not decorated", c[5]);
}
for t in &targets {
assert!(
(arith.contains(t) && !plain_ids.contains(t)) || fused_fmas.iter().any(|f| f.0 == *t),
arith.contains(t) && !plain_ids.contains(t),
"%{t} decorated"
);
}
@@ -965,8 +965,7 @@ fn offsets(size: u64) -> Vec<u64> {
/// bounds. Probes are skipped where the offset breaks the access's stated alignment (undefined in
/// Metal). A `half` NaN loaded, or stored from a constant, need only come back a NaN where the
/// module reads a `half` from its bits by the device's widening or encodes one by its narrowing
/// (`PrecisionNote::NativeNanEncoding`, or `VkProperty::MetalNanMoves`, measured on a device the
/// interpreter is not: `device_nan_bits`), whose NaN encoding is the device's.
/// (`PrecisionNote::NativeNanEncoding`, `device_nan_bits`), whose NaN encoding is the device's.
#[test]
fn every_leaf_path_is_exact_in_bounds_and_contained_out_of_bounds() {
let size = 32u64;
@@ -1274,8 +1273,8 @@ fn push_with_table(plan: &Plan) -> Vec<u8> {
/// and leaves the allocation unchanged. Robust buffer access does not cover device addresses, so
/// the check is emitted on a robust profile too. A `half` NaN loaded, or stored from a constant,
/// need only come back a NaN where the module reads a `half` from its bits by the device's
/// widening or encodes one by its narrowing (`PrecisionNote::NativeNanEncoding`, or
/// `VkProperty::MetalNanMoves`: `device_nan_bits`), whose NaN encoding is the device's.
/// widening or encodes one by its narrowing (`PrecisionNote::NativeNanEncoding`,
/// `device_nan_bits`), whose NaN encoding is the device's.
#[test]
fn a_device_address_slot_is_exact_and_contained() {
let size = 32u64;
@@ -1984,8 +1983,8 @@ fn profile_without(stem: &str, features: &[VkFeature]) -> DeviceProfile {
/// follows the binder contract (descriptor base congruent to the Metal address modulo 4), and a
/// sub-word store through a unit leaves its neighbours unchanged. A `half` NaN loaded, or stored
/// from a constant, need only come back a NaN where the module reads a `half` from its bits by the
/// device's widening or encodes one by its narrowing (`PrecisionNote::NativeNanEncoding`, or
/// `VkProperty::MetalNanMoves`: `device_nan_bits`), whose NaN encoding is the device's.
/// device's widening or encodes one by its narrowing (`PrecisionNote::NativeNanEncoding`,
/// `device_nan_bits`), whose NaN encoding is the device's.
#[test]
fn narrow_units_are_exact_at_every_bind_residual() {
let size = 32u64;
+50 -201
View File
@@ -16,7 +16,7 @@
//! (`engine_native_maths`).
use crate::air::{self, SpecRequest};
use crate::device::profile::{DeviceProfile, FloatFunctions};
use crate::device::profile::DeviceProfile;
use crate::device::requirements::VkFeature;
use crate::device::requirements::VkProperty;
use crate::device::{Device, DevicePolicy};
@@ -1158,12 +1158,9 @@ fn arith_kernels_validate_and_compute_on_every_profile() {
plan.estimate.words
);
if let Some(n) = kk.note {
// A maths function off Metal's own functions records the device's
// precision.
// A maths function records the device's precision.
let n = match n {
PrecisionNote::DeviceTranscendentals
if p.fields().float_functions != FloatFunctions::Metal =>
{
PrecisionNote::DeviceTranscendentals => {
PrecisionNote::NativeTranscendentals
}
n => n,
@@ -1434,8 +1431,8 @@ fn fma16_and_marks(words: &[u32]) -> (usize, usize) {
/// On `Device::from_queries`' profile (`HalfFma::Native`) a `half` fused multiply-add is the
/// device's 16-bit `Fma` wherever the profile computes `half` under the 16-bit float controls
/// (`fma::Route::F16Native`: RADV, ANV and NVIDIA's captures): the module computes it on 16-bit
/// floats with no conversion around it, so no instruction is decorated `NoContraction`; it requires
/// no `VkProperty::MetalHalfFma`, and it records `PrecisionNote::NativeFma`, as the device's
/// floats with no conversion around it, so no instruction is decorated `NoContraction`, and it
/// records `PrecisionNote::NativeFma`, as the device's
/// `float` `Fma` rounded to `half` does where the profile lacks those controls (lavapipe, which
/// does not keep 16-bit denormals, and vk12-floor, without `shaderFloat16`). The 16-bit `Fma`
/// rounds [`half_fma_kernel`]'s sum once on the interpreter, the `float` one twice.
@@ -1475,12 +1472,6 @@ fn a_half_fused_multiply_add_is_the_devices_16_bit_fma_on_from_queries() {
"{what}: {:?}",
a.precision
);
assert!(
!a.requirements
.properties
.contains(&VkProperty::MetalHalfFma),
"{what}"
);
let (fmas, marks) = fma16_and_marks(&a.module.words);
if controls {
assert_eq!((fmas, marks), (1, 0), "{what}: 16-bit Fma, NoContraction");
@@ -1534,9 +1525,8 @@ fn opaque_vector(name: &str, half: bool, vals: &[f32]) -> String {
/// `dot` on `float` and `half` is the device's `OpDot` on every profile, with and without fast
/// math, on two to four lanes; of more, each chunk's `OpDot` summed. Metal's is the products' fused
/// chain: a `float` one on a profile whose `float` functions are Metal's (moltenvk-m3) reaches
/// Metal's own `dot`, with no note; every other records `NativeDot` (a `half` one summed in its
/// `float` container), and a chunked one `DeviceArithmetic`. No fused multiply-add is emitted.
/// chain: each records `NativeDot` (a `half` one summed in its `float` container), and a chunked
/// one `DeviceArithmetic`. No fused multiply-add is emitted.
#[test]
fn dot_is_the_devices_op_dot_on_every_profile() {
let vals = |n: usize, k: f32| (0..n).map(|i| k * (i as f32 + 1.5)).collect::<Vec<_>>();
@@ -1632,7 +1622,6 @@ fn dot_is_the_devices_op_dot_on_every_profile() {
{
let policy = DevicePolicy::default();
let p = profile(stem, policy).expect("profile");
let metal = p.fields().float_functions == FloatFunctions::Metal;
for kk in &ks {
let what = format!("{} on {stem}", kk.name);
let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}"));
@@ -1641,7 +1630,6 @@ fn dot_is_the_devices_op_dot_on_every_profile() {
assert!(count_op(&words, crate::spv::Op::Dot) > 0, "{what}: OpDot");
assert_eq!(fma(&words), 0, "{what}: a fused chain");
let chunked = kk.name.ends_with("_chunked");
let float = kk.name.contains("_float");
if chunked {
assert!(
a.precision.contains(&PrecisionNote::DeviceArithmetic),
@@ -1649,9 +1637,8 @@ fn dot_is_the_devices_op_dot_on_every_profile() {
a.precision
);
} else {
assert_eq!(
assert!(
a.precision.contains(&PrecisionNote::NativeDot),
!(metal && float),
"{what}: {:?}",
a.precision
);
@@ -1856,8 +1843,7 @@ fn every_profile() -> Vec<String> {
/// Metal's fast division answers `0x7FC00000` for a NaN divisor of either sign, a NaN numerator,
/// `0 / 0` and `inf / inf`; the module leaves that NaN to the device's `OpFDiv` on every profile
/// (RADV answered `0xffc00000` for a negative NaN divisor, a probe cases 9496749c and 3921d3e2),
/// selecting none, so the module is the same on both sides of `MetalCanonicalNans`, and records
/// `PrecisionNote::NativeNanEncoding` where the device is not measured to answer Metal's. Its
/// selecting none, and records `PrecisionNote::NativeNanEncoding`. Its
/// `f32` denormals are the device's on every committed profile. The operands are integer bits, so
/// the division is the kernel's only float operation, and it records the device's arithmetic, its
/// division and its denormals, and never `DeviceNanEncoding`. The interpreter answers a NaN, its
@@ -1902,8 +1888,6 @@ fn a_fast_division_leaves_its_nans_to_the_device() {
nans_are_the_device_s(&bitcode, &ks, false, &[], &|_| true);
for stem in every_profile() {
let p = profile(&stem, crate::device::DevicePolicy::default()).expect("profile");
let device_nans =
p.takes_driver_deviation(crate::error::DriverDeviation::MetalCanonicalNans);
for kk in &ks {
let what = format!("{} on {stem}", kk.name);
let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}"));
@@ -1919,9 +1903,8 @@ fn a_fast_division_leaves_its_nans_to_the_device() {
a.precision
);
}
assert_eq!(
assert!(
a.precision.contains(&PrecisionNote::NativeNanEncoding),
!device_nans,
"{what}: {:?}",
a.precision
);
@@ -1945,8 +1928,7 @@ fn a_fast_division_leaves_its_nans_to_the_device() {
/// gives 0x3D59E381). Metal answers `0x7FC00000` for `0 / 0`; the module selects no NaN, so the
/// quotient is a NaN whose bits are the device's (the interpreter's are its host CPU's: x86-64's
/// default NaN, `0xFFC00000`, has its sign set, arm64's is `0x7FC00000`), noted
/// `NativeNanEncoding` exactly where the profile does not state the device answers Metal's
/// (`DriverDeviation::MetalCanonicalNans`). A `half` division under every flag set, `arcp`
/// `NativeNanEncoding`. A `half` division under every flag set, `arcp`
/// included, is the `float` quotient rounded once to `half`.
#[test]
fn a_division_without_arcp_is_the_devices_quotient() {
@@ -2003,8 +1985,6 @@ fn a_division_without_arcp_is_the_devices_quotient() {
};
for stem in ["moltenvk-m3", "lavapipe", "runtime-floor"] {
let p = profile(stem, crate::device::DevicePolicy::default()).expect("profile");
let device_nans =
p.takes_driver_deviation(crate::error::DriverDeviation::MetalCanonicalNans);
for kk in &ks {
let what = format!("{} on {stem}", kk.name);
let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}"));
@@ -2024,9 +2004,8 @@ fn a_division_without_arcp_is_the_devices_quotient() {
Some(want) => assert_eq!(got, want, "{what}: {got:#x}"),
None => {
assert!(stores_nan(got, false), "{what}: {got:#x}");
assert_eq!(
assert!(
a.precision.contains(&PrecisionNote::NativeNanEncoding),
!device_nans,
"{what}: {:?}",
a.precision
);
@@ -2367,11 +2346,9 @@ fn float_ops_without_contract_and_reassoc_are_no_contraction() {
let mul_rewritable = matches!(kk.name, "mul_add_reassoc_contract" | "mul_add_fast");
let add_rewritable = mul_rewritable || kk.name == "mul_strict_add_fast";
// A multiply carrying both flags is the device's `OpFMul`, undecorated; any other is
// the profile's product with `NoContraction`.
let metal = p.fields().float_functions == FloatFunctions::Metal;
// an `OpFMul` with `NoContraction`.
let mul = match (muls.as_slice(), fmas.as_slice()) {
([m], []) if mul_rewritable || !metal => *m,
([], [m]) if !mul_rewritable && metal => *m,
([m], []) => *m,
_ => panic!("{what}: one multiply in the profile's form: {muls:?} {fmas:?}"),
};
assert_eq!(
@@ -2614,17 +2591,10 @@ fn half_rounding_follows_the_operation() {
// Where the device's float controls make the conversion Metal's, each rounding is
// that conversion and its widening too.
let controlled = form == crate::spirv::builder::QuantizeForm::Controlled;
// Where the device's 16-bit `+ - *` is Metal's, measured or under the 16-bit float
// controls, the operations among the roundings: sixteen of each chain's seventeen. The
// conversion's rounding stays the module's.
let ha = (p.takes_driver_deviation(crate::error::DriverDeviation::MetalHalfArithmetic)
&& p.fields().leaf.float16)
|| controlled;
assert!(
!ha || converted || controlled,
"{what}: the half arithmetic beside the conversion"
);
let kept = if ha { 16 } else { 0 };
// Where the device's 16-bit `+ - *` is Metal's, under the 16-bit float controls, the
// operations among the roundings: sixteen of each chain's seventeen. The conversion's
// rounding stays the module's.
let kept = if controlled { 16 } else { 0 };
// Each 16-bit operation reads the previous one's 16-bit result itself, and narrows
// `%x0`, the conversion's rounding, which stays a pair (the first operation reads it
// twice); the last result is widened once.
@@ -2689,70 +2659,6 @@ fn half_rounding_follows_the_operation() {
}
}
/// Where the device's 16-bit `+ - *` is measured Metal's, a `half` sum is that instruction, which
/// rounds nothing of the module's: it requires `MetalHalfArithmetic`. A kernel there whose
/// `half`s (each read from its bits by a bitcast) only the device's 16-bit `fma` reads takes them
/// as 16-bit floats, with no widening, and requires nothing of that measurement.
#[test]
fn a_measured_half_sum_requires_the_arithmetic_fact_alone() {
let halves = format!(
"{}{}{} %h = bitcast i16 %t to half\n %g = bitcast i16 %s to half\n %u = bitcast i16 %v to half\n",
on("t", 16, 0x3C01),
on("s", 16, 0x4100),
on("v", 16, 0x3800)
);
let ks = [
Kernel {
name: "half_sum",
body: format!("{halves} %x = fadd half %h, %g\n %r = fpext half %x to float\n"),
float: true,
want: None,
needs: &[],
note: None,
},
Kernel {
name: "half_fma",
body: format!(
"{halves} %x = call half @llvm.fma.f16(half %h, half %g, half %u)\n %r = fpext half %x to float\n"
),
float: true,
want: None,
needs: &[],
note: None,
},
];
let text = module(&ks).replace(
DECLS,
&format!("{DECLS}declare half @llvm.fma.f16(half, half, half)\n"),
);
let Some(bitcode) = assemble("half-conversion-fact", &text) else {
return;
};
let mut converting = 0;
for stem in PROFILES {
let p = profile(stem, crate::device::DevicePolicy::default()).expect("profile");
let converted = crate::lower::arith::narrow::quantize_form(&p)
== crate::spirv::builder::QuantizeForm::Converted;
let ha = p.takes_driver_deviation(crate::error::DriverDeviation::MetalHalfArithmetic)
&& p.fields().leaf.float16;
converting += usize::from(converted);
for kk in &ks {
let what = format!("{} on {stem}", kk.name);
let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}"));
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
assert_eq!(
a.requirements
.properties
.contains(&crate::device::requirements::VkProperty::MetalHalfArithmetic),
ha && kk.name == "half_sum",
"{what}: {:?}",
a.requirements.properties
);
}
}
assert!(converting > 0, "no profile rounds through the conversion");
}
/// Without `shaderFloat16` every `half` rounding is the device's `OpQuantizeToF16` alone, with no
/// denormal arithmetic (no `RoundEven`) whatever the operation: a transcendental, `ldexp`, a
/// quotient, a square root, `fract`'s difference and the one rounding of a fused sum (`fmuladd`
@@ -2832,12 +2738,10 @@ fn a_half_rounding_without_float16_is_the_quantize_alone() {
let round_even = count_ops(&words, |w| {
w[0] & 0xFFFF == crate::spv::Op::ExtInst as u32 && w.len() > 4 && w[4] == 2
});
let fused = matches!(kk.name, "half_mix" | "half_fmuladd")
&& p.takes_driver_deviation(crate::error::DriverDeviation::MetalHalfFma);
// A rounding through the conversion holds neither, under the float controls or not.
let converts = crate::lower::arith::narrow::quantize_form(&p)
!= crate::spirv::builder::QuantizeForm::Device;
let want = match fused || converts {
let want = match converts {
true => (0, 0),
false => (quantizes, 0),
};
@@ -3322,11 +3226,10 @@ fn nans_are_the_device_s(
}
}
/// A NaN of `float` arithmetic is the device's on every profile: the module selects none, whatever
/// the profile's `MetalCanonicalNans` fact, and records `PrecisionNote::NativeNanEncoding` where
/// the device is not measured to answer Metal's: for `+`, whose canonical NaN the fact covers,
/// where the fact is absent, and for `round`, which returns a NaN operand's own bits on Metal,
/// whatever the fact. The interpreter keeps a NaN operand's payload, as such a device would.
/// A NaN of `float` arithmetic is the device's on every profile: the module selects none, and
/// records `PrecisionNote::NativeNanEncoding` for `+`, which answers Metal's canonical NaN, and for
/// `round`, which returns a NaN operand's own bits on Metal. The interpreter keeps a NaN operand's
/// payload, as such a device would.
#[test]
fn a_float_nan_is_the_device_s_on_every_profile() {
let ks = [
@@ -3501,9 +3404,8 @@ fn float_denormals_are_the_devices_and_noted() {
/// `air.sincos` answers the NaN its `sin` and `cos` answer as calls of their own, since Metal's
/// `sincos` is its `sin` and `cos` word for word (cases 7b283404 and f6524207, every pair): precise
/// `sin` and `cos` without fast-math flags answer the canonical NaN, which the device answers where
/// the profile takes `MetalCanonicalNans`; elsewhere either result, read or not, is noted
/// `PrecisionNote::NativeNanEncoding`, and neither is selected.
/// `sin` and `cos` without fast-math flags answer the canonical NaN; either result, read or not, is
/// noted `PrecisionNote::NativeNanEncoding`, and neither is selected.
#[test]
fn sincos_answers_the_device_s_nan() {
let kernel = |name: &'static str, read: &str| {
@@ -3678,8 +3580,7 @@ fn half_nan_kernel(name: &'static str, body: String, want: Option<u32>) -> Kerne
/// Class B: Metal's `half` `+`, `*`, and `air.fma.f16`, with or without fast-math flags, and its
/// narrowing of a `float` to `half` (`fptrunc`, and `air.convert` from class E's version) answer
/// the canonical `half` NaN `0x7E00`, as `half` `-` (class K's) does. The NaN is the device's on
/// every profile, selected nowhere, and noted `PrecisionNote::NativeNanEncoding` where the profile
/// does not take `MetalCanonicalNans`.
/// every profile, selected nowhere, and noted `PrecisionNote::NativeNanEncoding`.
#[test]
fn half_nans_answer_the_device_s_nan() {
let hx = oh("hx", 0xFE01);
@@ -3742,9 +3643,7 @@ fn half_nans_answer_the_device_s_nan() {
/// dropped, by `fpext` and by its intrinsic form `air.convert`. A `half` is held widened, so
/// `fpext` emits no device operation: the NaN is the device's widening of the `half`'s bits where
/// the profile has `shaderFloat16` (both profiles here), and the module selects nothing and notes
/// `PrecisionNote::NativeNanEncoding` whatever the device fact states, but where the device's
/// widening is measured to answer Metal's (`DriverDeviation::MetalNanMoves`, on `moltenvk-m3`),
/// where it requires that. The interpreter's widening keeps the payload, as a device may.
/// `PrecisionNote::NativeNanEncoding`. The interpreter's widening keeps the payload, as a device may.
#[test]
fn a_widened_half_nan_keeps_its_payload_on_every_profile() {
let hx = oh("hx", 0xFE01);
@@ -3782,10 +3681,8 @@ fn a_widened_half_nan_keeps_its_payload_on_every_profile() {
/// Class D: Metal's `half` `fneg` and `fabs` answer the canonical `half` NaN `0x7E00`, with or
/// without fast-math flags. A device computes both exactly on the held value's sign, so a NaN's
/// payload is kept on every profile: the module selects nothing and notes
/// `PrecisionNote::NativeNanEncoding` whatever the device fact states, as for an `fadd` whose only
/// use is the `fneg`; but `fabs` where the device's is measured to answer Metal's
/// (`DriverDeviation::MetalNanMoves`, on `moltenvk-m3`: the held value is its widening's canonical
/// NaN there), where it requires that. The interpreter keeps a `half` NaN's payload through the
/// `PrecisionNote::NativeNanEncoding`, as for an `fadd` whose only use is the `fneg`. The
/// interpreter keeps a `half` NaN's payload through the
/// held value, as a device may (the value stored unchanged is `0xFE01`, and notes nothing).
#[test]
fn half_sign_operations_keep_a_nan_s_payload_on_every_profile() {
@@ -3970,8 +3867,7 @@ fn half_moves_are_the_devices_bits() {
}
/// Every normalized format's `air.pack` and `air.unpack`, in `float` and `half`: the device's
/// conversion, noted `DevicePackConversion` but where it reaches Metal's own function (a `float`
/// form `GLSL.std.450` names, where the profile's `float` functions are Metal's), on every profile,
/// conversion, noted `DevicePackConversion` on every profile,
/// requiring no property but the float controls the module declares.
#[test]
fn pack_conversions_are_the_devices() {
@@ -3986,7 +3882,7 @@ fn pack_conversions_are_the_devices() {
("snorm.rgb10a2", 4, 32),
("unorm.rgb565", 3, 16),
];
let (mut forms, mut ks) = (Vec::new(), Vec::new());
let mut ks = Vec::new();
let mut decls = String::new();
for (format, lanes, width) in formats {
for packs in [true, false] {
@@ -4050,7 +3946,6 @@ fn pack_conversions_are_the_devices() {
if packs { "pack" } else { "unpack" },
format.replace('.', "_")
);
forms.push((format, half));
ks.push(Kernel {
want: None,
..k(Box::leak(name.into_boxed_str()), body, 0)
@@ -4064,16 +3959,12 @@ fn pack_conversions_are_the_devices() {
};
for stem in ["lavapipe", "moltenvk-m3"] {
let p = profile(stem, DevicePolicy::default()).expect("profile");
let metal_functions = p.fields().float_functions == FloatFunctions::Metal;
for (&(format, half), kk) in forms.iter().zip(&ks) {
for kk in &ks {
let what = format!("{} on {stem}", kk.name);
let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}"));
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let glsl = matches!(format, "unorm4x8" | "snorm4x8" | "unorm2x16" | "snorm2x16");
let own = metal_functions && !half && glsl;
assert_eq!(
assert!(
a.precision.contains(&PrecisionNote::DevicePackConversion),
!own,
"{what}: {:?}",
a.precision
);
@@ -4093,11 +3984,7 @@ fn pack_conversions_are_the_devices() {
/// NaN keeps its payload, signaling or not, and a denormal stays. The lowering is the device's
/// `OpFNegate` and `FAbs` on every profile (RADV's `fneg` keeps a NaN's sign, NVIDIA's `fabs`
/// answers `0x7FFFFFFF`, RADV and ANV flush a denormal): no NaN is selected and nothing moves on
/// the bits, the NaN noted `NativeNanEncoding` but where the device's are measured to be Metal's
/// (`DriverDeviation::MetalNanMoves`, on `moltenvk-m3`), where the module requires that, and
/// `fneg`'s denormal `DeviceDenormals` but where the device keeps it as Metal does
/// (`DriverDeviation::MetalUnaryDenormals`, on `moltenvk-m3`), where the module requires that and
/// `fabs` records no `DeviceDenormals` either. The interpreter keeps the payload and the
/// the bits, the NaN noted `NativeNanEncoding`, and `fneg`'s denormal `DeviceDenormals`. The interpreter keeps the payload and the
/// denormal, as a device may.
#[test]
fn float_sign_operations_are_the_devices_on_every_profile() {
@@ -4182,40 +4069,18 @@ fn float_sign_operations_are_the_devices_on_every_profile() {
assert_eq!(fabs(&words) > 0, abs, "{what}");
assert_eq!(nan_tests(&words), (0, 0), "{what}");
if neg || abs {
let moves = p.takes_driver_deviation(crate::error::DriverDeviation::MetalNanMoves);
assert_eq!(
assert!(
a.precision.contains(&PrecisionNote::NativeNanEncoding),
!moves,
"{what}: {:?}",
a.precision
);
assert_eq!(
a.requirements
.properties
.contains(&crate::device::requirements::VkProperty::MetalNanMoves),
moves,
"{what}"
);
}
// A denormal is the device's but where it is measured to keep it as Metal does
// (`DriverDeviation::MetalUnaryDenormals`), which the module then requires.
if neg || abs {
let unary =
p.takes_driver_deviation(crate::error::DriverDeviation::MetalUnaryDenormals);
if neg || unary {
assert_eq!(
a.precision.contains(&PrecisionNote::DeviceDenormals),
!unary,
"{what}: {:?}",
a.precision
);
}
assert_eq!(
a.requirements
.properties
.contains(&crate::device::requirements::VkProperty::MetalUnaryDenormals),
unary,
"{what}"
// A negated denormal is the device's.
if neg {
assert!(
a.precision.contains(&PrecisionNote::DeviceDenormals),
"{what}: {:?}",
a.precision
);
}
let got = interpret(&bitcode, kk.name, &p);
@@ -4229,10 +4094,8 @@ fn float_sign_operations_are_the_devices_on_every_profile() {
/// and with some, answer an operand bit for bit (`nan_minmax`, `nan_minmax_fast`, and their
/// zeros-and-denormals cases, every lane; for the other flag states): a NaN loses, two NaNs and a
/// tie answer the second operand, and a denormal compares as zero but is returned itself. On every
/// profile the device's `NMin`, `NMax`, or `NClamp` decides it: where the profile takes
/// `DriverDeviation::MetalMinMax` measured to be Metal's (the interpreter models them so), and the
/// module requires `VkProperty::MetalMinMax`; elsewhere noted `PrecisionNote::NativeMinMax`. No
/// device note is recorded.
/// profile the device's `NMin`, `NMax`, or `NClamp` decides it, noted `PrecisionNote::NativeMinMax`
/// (the interpreter models them as Metal's). No device note is recorded.
#[test]
fn float_min_max_are_the_device_s_on_every_profile() {
let two = |a: u32, b: u32| format!("{}{}", ob("x", a), ob("y", b));
@@ -4379,21 +4242,12 @@ fn float_min_max_are_the_device_s_on_every_profile() {
let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}"));
let (_, words) =
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let device = p.takes_driver_deviation(crate::error::DriverDeviation::MetalMinMax);
assert!(device_pick(&words) > 0, "{what}");
assert_eq!(
assert!(
a.precision.contains(&PrecisionNote::NativeMinMax),
!device,
"{what}: {:?}",
a.precision
);
assert_eq!(
a.requirements
.properties
.contains(&crate::device::requirements::VkProperty::MetalMinMax),
device,
"{what}"
);
for note in [
PrecisionNote::DeviceDenormals,
PrecisionNote::DeviceNanEncoding,
@@ -4495,9 +4349,8 @@ fn half_fmod_is_its_float_remainder_on_every_profile() {
/// Class I: Metal's `mix(x, y, t)` on `float` and `half` is `fma(t, y, fma(-t, x, x))`, with and
/// without fast-math flags (`nan_functions`: `mix(inf, 1, 0)` is the canonical NaN; `nan_half`:
/// `mix(-0.3, 0.7, 0.2)` is `0xAE68`, where the blend gives `0xAE66`). On every profile the module
/// takes the device's `FMix` and no fused multiply-add: a `float` one on a profile whose `float`
/// functions are Metal's (moltenvk-m3) reaches Metal's own `mix`, with no note; every other records
/// `NativeMix` (a `half` one the blend in its `float` container, rounded once).
/// takes the device's `FMix` and no fused multiply-add, and records `NativeMix` (a `half` one the
/// blend in its `float` container, rounded once).
#[test]
fn mix_is_the_devices_fmix_on_every_profile() {
let three = |a: u32, b: u32, c: u32| format!("{}{}{}", ob("x", a), ob("y", b), ob("z", c));
@@ -4571,7 +4424,6 @@ fn mix_is_the_devices_fmix_on_every_profile() {
.chain(["lavapipe", "amd-rdna3-radv"])
{
let p = profile(stem, crate::device::DevicePolicy::default()).expect("profile");
let metal = p.fields().float_functions == FloatFunctions::Metal;
for kk in &ks {
let what = format!("{} on {stem}", kk.name);
let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}"));
@@ -4579,10 +4431,8 @@ fn mix_is_the_devices_fmix_on_every_profile() {
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
assert!(blend(&words) > 0, "{what}: FMix");
assert_eq!(fma(&words), 0, "{what}: a fused form");
let half = kk.name.starts_with("half_");
assert_eq!(
assert!(
a.precision.contains(&PrecisionNote::NativeMix),
!(metal && !half),
"{what}: {:?}",
a.precision
);
@@ -4592,10 +4442,9 @@ fn mix_is_the_devices_fmix_on_every_profile() {
/// Class K: Metal's `half` functions answer the canonical `half` NaN `0x7E00` with and without
/// fast-math flags (`nan_half`, `nan_half_fast`): `llvm.fmuladd`, `ldexp` (unlike `float`'s, which
/// returns the operand), and `sqrt`, which the device answers where the profile takes
/// `MetalCanonicalNans` and which are noted `PrecisionNote::NativeNanEncoding` elsewhere. `round`
/// and `fract` return a NaN operand itself on Metal, and `asin`'s domain error takes the operand's
/// sign: each the device's NaN on every profile, noted whatever the fact. None is selected.
/// returns the operand), and `sqrt`, noted `PrecisionNote::NativeNanEncoding`. `round` and `fract`
/// return a NaN operand itself on Metal, and `asin`'s domain error takes the operand's sign: each
/// the device's NaN on every profile, noted. None is selected.
/// `round`'s zero is C99's (`-0` for `round(-0.3)`, where Metal answers `+0`), and `fract` of an
/// infinity the device's `Fract`'s NaN (Metal's: `+0`, and `0x3BFF` with every flag).
#[test]
@@ -21,7 +21,7 @@
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
use crate::device::profile::{DeviceProfile, FloatFunctions};
use crate::device::profile::DeviceProfile;
use crate::device::DevicePolicy;
use crate::error::{Error, Feature, Needs, Unsupported};
use crate::lower::select::Plan;
@@ -1261,11 +1261,9 @@ fn the_emulation_validates_on_every_committed_profile() {
/// The ids the footprint's three `f32` operations produce in the entry point of a linked module
/// `words`, and whether each is rounded on its own. The operations are the normalized coordinate
/// times the extent (a product of an `OpConvertUToF` result), `y = 256 x` (a product by the
/// constant 256), and `r = y - floor(y)` (an `OpFSub` of a GLSL `Floor` result). A product
/// rounded on its own is `GLSL.std.450 Fma(a, b, -0.0)` where the profile's `float` functions are
/// Metal's (`metal`), and an `OpFMul` elsewhere; it and the subtraction are rounded on their own
/// when decorated `NoContraction`.
fn footprint_ops(words: &[u32], metal: bool) -> [Vec<(u32, bool)>; 3] {
/// constant 256), and `r = y - floor(y)` (an `OpFSub` of a GLSL `Floor` result). A product and
/// the subtraction are rounded on their own when decorated `NoContraction`.
fn footprint_ops(words: &[u32]) -> [Vec<(u32, bool)>; 3] {
let insts: Vec<&[u32]> = {
let (mut v, mut i) = (Vec::new(), 5);
while i < words.len() {
@@ -1322,27 +1320,9 @@ fn footprint_ops(words: &[u32], metal: bool) -> [Vec<(u32, bool)>; 3] {
&& glsl.contains(&w[3])
&& w[4] == crate::spv::GlslStd450Op::Floor as u32
});
let negative_zero = insts
.iter()
.filter(|w| {
op(w) == crate::spv::Op::Constant as u32
&& floats.contains(&w[1])
&& w[3] == 0x8000_0000
})
.map(|w| w[2])
.collect::<Vec<_>>();
// The product of `a` and `b` rounded on its own, in the profile's form: `Fma(a, b, -0.0)`
// where its `float` functions are Metal's, an `OpFMul` elsewhere.
// The product of `a` and `b`: an `OpFMul`.
let product = |w: &[u32], of: &[u32]| {
if metal {
op(w) == crate::spv::Op::ExtInst as u32
&& glsl.contains(&w[3])
&& w[4] == crate::spv::GlslStd450Op::Fma as u32
&& negative_zero.contains(&w[7])
&& (of.contains(&w[5]) || of.contains(&w[6]))
} else {
op(w) == crate::spv::Op::FMul as u32 && (of.contains(&w[3]) || of.contains(&w[4]))
}
op(w) == crate::spv::Op::FMul as u32 && (of.contains(&w[3]) || of.contains(&w[4]))
};
let decorated: Vec<u32> = insts
.iter()
@@ -1368,9 +1348,8 @@ fn footprint_ops(words: &[u32], metal: bool) -> [Vec<(u32, bool)>; 3] {
/// The footprint's `x = c n` (normalized coordinates only), `y = 256 x`, and `r = y - floor(y)` are
/// each rounded on its own on every committed profile, one of each per plane axis, so no device
/// fuses them into the arithmetic after them: the products in the profile's form (`Fma(a, b, -0.0)`
/// where its `float` functions are Metal's, an `OpFMul` elsewhere), each decorated `NoContraction`
/// as the subtraction is. A re-bless of the golden table would not notice the form dropped; this
/// fuses them into the arithmetic after them: the products an `OpFMul`, each decorated
/// `NoContraction` as the subtraction is. A re-bless of the golden table would not notice the form dropped; this
/// test does.
#[test]
fn the_footprint_arithmetic_is_no_contraction() {
@@ -1386,8 +1365,7 @@ fn the_footprint_arithmetic_is_no_contraction() {
let a = compile(&bc, "k", &p).unwrap_or_else(|e| panic!("{name} on {stem}: {e}"));
let (_, spv) =
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name} on {stem}: {e}"));
let metal = p.fields().float_functions == FloatFunctions::Metal;
let [cn, y, r] = footprint_ops(&spv, metal);
let [cn, y, r] = footprint_ops(&spv);
for (what, ops, want) in [
("c n", cn, products),
("256 x", y, 2),
@@ -343,9 +343,8 @@ fn run(
/// Every read through a slot of another class gives the words the slot of the texture's own
/// class gives, a `half` result their low 16 bits: Metal's rule. A `ushort` result of an integer
/// texture is the low 16 bits too, of a float texture the `half` read's bits. Where the module
/// widens a `half` from its bits by the device and records `PrecisionNote::NativeNanEncoding` or
/// requires `VkProperty::MetalNanMoves` (both profiles here, which have `shaderFloat16`;
/// `device_nan_bits`), a `half` result's NaN is the device's widening's, which the interpreter is
/// widens a `half` from its bits by the device and records `PrecisionNote::NativeNanEncoding`
/// (both profiles here, which have `shaderFloat16`; `device_nan_bits`), a `half` result's NaN is the device's widening's, which the interpreter is
/// not, so a NaN pattern need only come back a NaN.
#[test]
fn accesses_through_another_class_are_the_native_words() {
@@ -770,8 +770,7 @@ declare void @air.write_texture_2d.v4f16(ptr addrspace(1), <2 x i32>, <4 x half>
/// families of the textures its handles can name (`SpecKey::HeapNanFamilies`): on every committed
/// profile with a heap, one clause for each family, as each stores the device's NaN (a 16-bit
/// float format, a 32-bit one, a packed small float one, and a float format of none of those),
/// and no `VkProperty::MetalHalfTexelWrites`, `MetalNanMoves` or `MetalSmallFloatNans` is
/// required. A plan gives the key from the command's resident textures (`R16Float` 1,
/// and no `VkProperty::MetalHalfTexelWrites` or `MetalSmallFloatNans` is required. A plan gives the key from the command's resident textures (`R16Float` 1,
/// `RGBA32Float` 2, `RG11B10Float` 4, `RGBA8Unorm` and `R32Uint` 0), and the note holds under the
/// plan's values exactly where a resident texture is of a family of a clause.
#[test]
@@ -819,7 +818,6 @@ fn a_heap_half_write_s_nan_note_follows_the_families_its_command_can_name() {
assert_eq!(noted(&a.specialized), 15, "{stem}: every family");
for property in [
VkProperty::MetalHalfTexelWrites,
VkProperty::MetalNanMoves,
VkProperty::MetalSmallFloatNans,
] {
assert!(
@@ -3,20 +3,17 @@
//! product computes as a near-equivalent of Metal's, so the two must never diverge from what a
//! compile records.
//!
//! Every float function of the `air` math table, on `float`, `half`, and `bfloat`, called with
//! and without the `fast_` prefix and with and without fast-math flags, and every float binary
//! Every float function of the `air` math table, on `float`, `half`, and `bfloat`, called with and
//! without the `fast_` prefix and with and without fast-math flags, and every float binary
//! operator, is compiled alone (its operands loaded from a buffer and its result stored) on one
//! committed profile per class of the facts the notes read: the `float` fused multiply-add route,
//! whether the `float` functions are Metal's, whether the device reads `f32` denormals as Metal
//! does, and whether its moves of a NaN are Metal's (`nan::moves_answered`). Each artifact's notes are exactly what the exported function answers for that call
//! in that entry's math mode. The loads and stores around it record none, but a `half` kernel's
//! widening and rounding, which the module records once by the profile's own form: its rounding's
//! note (`narrow::native_rounding`), and under the float controls `NativeHalfConversion` where the
//! module rounds through the conversion pair (`narrow::rounds_by_conversion`), which the test sets
//! aside, and a module's widening of a
//! `half` from its bits or narrowing of one to them by the device (every profile), whose NaN's
//! bits are the device's (`narrow::widens_bits`, `narrow::encodes_bits`, `NativeNanEncoding`) but
//! where the device's moves of a NaN are measured to be Metal's (`narrow::moves_unfolded`), and
//! committed profile per class of the facts the notes read: the `float` fused multiply-add route.
//! Each artifact's notes are exactly what the exported function answers for that call. The loads
//! and stores around it record none, but a `half` kernel's widening and rounding, which the module
//! records once by the profile's own form: its rounding's note (`narrow::native_rounding`), and
//! under the float controls `NativeHalfConversion` where the module rounds through the conversion
//! pair (`narrow::rounds_by_conversion`), which the test sets aside, and a module's widening of a
//! `half` from its bits or narrowing of one to them by the device (every profile), whose NaN's bits
//! are the device's (`narrow::widens_bits`, `narrow::encodes_bits`, `NativeNanEncoding`), and
//! without `shaderFloat16` its denormals too (`UnpackHalf2x16`, `PackHalf2x16`,
//! `NativeHalfConversion`), which the test adds to the operation's notes.
//!
@@ -24,13 +21,10 @@
use crate::air::intrinsics::{AirIntrinsic, Elem, Math, NumTy, Operand};
use crate::air::ir::{BinOp, FastMath};
use crate::device::profile::{FloatFunctions, NanEncoding};
use crate::device::DeviceProfile;
use crate::error::DriverDeviation;
use crate::lower::arith::fma::{self, Route};
use crate::lower::arith::libm::Mode;
use crate::lower::arith::{denormal, float_binop_notes, float_call_notes, nan, narrow, FloatFmt};
use crate::pipeline::artifact::{EntryMath, PrecisionNote};
use crate::lower::arith::{float_binop_notes, float_call_notes, narrow, FloatFmt};
use crate::pipeline::artifact::PrecisionNote;
use crate::pipeline::testing::{
compile, llvm_assemble, meter, typed_module, AssembleError, Scratch,
};
@@ -288,19 +282,12 @@ fn assemble(token: &str, chunk: usize, text: &str) -> Option<Vec<u8>> {
}
}
/// What the notes of a float operation read of a profile: its `float` fused multiply-add route,
/// whether its `float` functions are Metal's, whether the device reads `f32` denormals as Metal
/// does, and whether its moves of a NaN are Metal's.
type NoteClass = (Route, bool, bool, bool);
/// What the notes of a float operation read of a profile: its `float` fused multiply-add route.
type NoteClass = Route;
/// The note class of profile `p`.
fn note_class(p: &DeviceProfile) -> NoteClass {
(
fma::float_route(p),
p.fields().float_functions == FloatFunctions::Metal,
denormal::device_flushes(p),
nan::moves_answered(p),
)
fma::float_route(p)
}
/// One committed profile per note class (the first by name).
@@ -311,7 +298,7 @@ fn one_profile_per_class() -> BTreeMap<NoteClass, (String, DeviceProfile)> {
{
out.entry(note_class(&p)).or_insert((stem, p));
}
let routes: BTreeSet<Route> = out.keys().map(|(route, _, _, _)| *route).collect();
let routes: BTreeSet<Route> = out.keys().copied().collect();
assert_eq!(
routes,
BTreeSet::from([Route::Khr, Route::Native]),
@@ -320,21 +307,6 @@ fn one_profile_per_class() -> BTreeMap<NoteClass, (String, DeviceProfile)> {
out
}
/// The mode of the `float` functions of an entry on `p` whose one float operation carries flags
/// `fmf` (`None` where the profile's are the device's): precise where the operation lacks one of
/// `nnan`, `ninf`, and `nsz` and the profile declares `SignedZeroInfNanPreserve` for `f32`, the
/// container of every format here (`arith::fp_env`, `libm::module_mode`).
fn entry_mode(p: &DeviceProfile, fmf: FastMath) -> Option<Mode> {
let relaxed = FastMath::NNAN.union(FastMath::NINF).union(FastMath::NSZ);
let preserves =
!fmf.contains(relaxed) && p.fields().float_controls.f32.signed_zero_inf_nan_preserve;
(p.fields().float_functions == FloatFunctions::Metal).then_some(if preserves {
Mode::Precise
} else {
Mode::Fast
})
}
#[test]
fn exported_float_notes_are_the_ones_a_compile_records() {
let profiles = one_profile_per_class();
@@ -354,10 +326,9 @@ fn exported_float_notes_are_the_ones_a_compile_records() {
Op::Call { name, math, fmf } => {
let notes = float_call_notes(*math, *fmf, p);
assert!(notes.is_some(), "{what}: {name} is not a float function");
notes.map(|notes| notes.in_entry(entry_mode(p, *fmf)))
notes
}
Op::Binop { op, fmt, fmf } => float_binop_notes(*op, *fmt, *fmf, p)
.map(|notes| notes.in_entry(entry_mode(p, *fmf))),
Op::Binop { op, fmt, fmf } => float_binop_notes(*op, *fmt, *fmf, p),
};
let mut want = want.unwrap_or_else(|| panic!("{what}: no exported notes"));
let a =
@@ -381,12 +352,8 @@ fn exported_float_notes_are_the_ones_a_compile_records() {
let crosses = narrow::widens_bits(&m, &mut meter())
.and_then(|w| Ok(w || narrow::encodes_bits(&m, &mut meter())?))
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
// Its NaN's bits Metal's where the device's moves are measured to be and
// the module moves its `half` values only so.
let moved = nan::moves_answered(p)
&& !narrow::moves_unfolded(&m, &mut meter())
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
if crosses && !moved {
// Its NaN's bits the device's.
if crosses {
want.insert(PrecisionNote::NativeNanEncoding);
}
if crosses && form == crate::spirv::builder::QuantizeForm::Device {
@@ -404,96 +371,81 @@ fn exported_float_notes_are_the_ones_a_compile_records() {
}
/// The binary operators' notes beside the functions': a remainder and a division are the device's
/// arithmetic, and a `float` operator leaves the device its denormals where the profile does not
/// take `DriverDeviation::MetalFloatDenormals`, and a remainder and a division on every profile.
/// arithmetic, and a `float` operator leaves the device its denormals.
/// Metal's precise division (an `fdiv` on `float` without `arcp`, or on `half` under every flag
/// set) is the device's `OpFDiv`, noted `NativeDivision`. A `float` remainder without every flag is
/// the device's `OpFRem`, and with every flag Metal's `fast::fmod`, whose notes it records. Metal's
/// fast division (an `fdiv` on `float` with `arcp`) is the device's `OpFDiv` too, and records the
/// device's arithmetic, its division and its denormals, but where the profile's `float` functions
/// are Metal's, in an entry Metal compiles with fast math, whose quotient is Metal's own. Metal
/// answers its canonical NaN for a `float` or `half` `+ - * /` and a `float` remainder; each leaves
/// that NaN to the device, noted `NativeNanEncoding` where the profile is not measured to answer
/// Metal's (`NanEncoding::Native`), a fast `float` division but in Metal's own fast-math entry.
/// device's arithmetic, its division and its denormals. Metal answers its canonical NaN for a
/// `float` or `half` `+ - * /` and a `float` remainder; each leaves that NaN to the device, noted
/// `NativeNanEncoding`.
/// No operator records `DeviceNanEncoding`.
#[test]
fn a_float_division_is_the_devices_arithmetic_unless_it_is_metals_precise_one() {
for (class, (stem, p)) in one_profile_per_class() {
let (_, metal_functions, _, _) = class;
let flushes = p.takes_driver_deviation(DriverDeviation::MetalFloatDenormals);
let native_nans = nan::encoding(&p) == NanEncoding::Native;
for (stem, p) in one_profile_per_class().into_values() {
for (_, _, _, fmt) in ELEMS {
for op in BinOp::ALL {
for fmf in [FastMath::NONE, FastMath::ARCP, every_flag()] {
let notes = float_binop_notes(op, fmt, fmf, &p);
assert_eq!(notes.is_some(), op.is_float(), "{op:?}");
let Some(notes) = notes else { continue };
for mode in [Mode::Fast, Mode::Precise] {
let metal = metal_functions.then_some(mode);
let notes = notes.clone().in_entry(metal);
let single = fmt == FloatFmt::F32;
let precise = op == BinOp::FDiv
&& (fmt == FloatFmt::Half || (single && !fmf.contains(FastMath::ARCP)));
let what = format!("{op:?} on {fmt:?} under {fmf:?} on {stem}, {metal:?}");
assert!(!notes.contains(&PrecisionNote::DeviceNanEncoding), "{what}");
if precise {
let want: BTreeSet<_> = [PrecisionNote::NativeDivision]
.into_iter()
.chain(single.then_some(PrecisionNote::DeviceDenormals))
.chain(native_nans.then_some(PrecisionNote::NativeNanEncoding))
.collect();
assert_eq!(notes, want, "{what}");
continue;
}
if op == BinOp::FRem && single && fmf == every_flag() {
let Some(AirIntrinsic::Math(fmod)) =
AirIntrinsic::parse("air.fast_fmod.f32")
else {
panic!("air.fast_fmod.f32 does not parse");
};
let want = float_call_notes(fmod, fmf, &p)
.expect("fast fmod is a float function")
.in_entry(metal);
assert_eq!(notes, want, "{what}");
continue;
}
if op == BinOp::FDiv && single {
let want = if metal == Some(Mode::Fast) {
BTreeSet::new()
} else {
[
PrecisionNote::DeviceArithmetic,
PrecisionNote::NativeDivision,
PrecisionNote::DeviceDenormals,
]
.into_iter()
.chain(native_nans.then_some(PrecisionNote::NativeNanEncoding))
.collect()
};
assert_eq!(notes, want, "{what}");
continue;
}
assert_eq!(
notes.contains(&PrecisionNote::DeviceArithmetic),
matches!(op, BinOp::FDiv | BinOp::FRem),
"{what}"
);
// Metal's canonical NaN: a `float` or `half` `+ - *`, and a `float`
// remainder.
let canonical = (matches!(fmt, FloatFmt::F32 | FloatFmt::Half)
&& matches!(op, BinOp::FAdd | BinOp::FSub | BinOp::FMul))
|| (op == BinOp::FRem && single);
assert_eq!(
notes.contains(&PrecisionNote::NativeNanEncoding),
native_nans && canonical,
"{what}"
);
assert_eq!(
notes.contains(&PrecisionNote::DeviceDenormals),
single && (op == BinOp::FRem || !flushes),
"{what}"
);
let single = fmt == FloatFmt::F32;
let precise = op == BinOp::FDiv
&& (fmt == FloatFmt::Half || (single && !fmf.contains(FastMath::ARCP)));
let what = format!("{op:?} on {fmt:?} under {fmf:?} on {stem}");
assert!(!notes.contains(&PrecisionNote::DeviceNanEncoding), "{what}");
if precise {
let want: BTreeSet<_> = [PrecisionNote::NativeDivision]
.into_iter()
.chain(single.then_some(PrecisionNote::DeviceDenormals))
.chain([PrecisionNote::NativeNanEncoding])
.collect();
assert_eq!(notes, want, "{what}");
continue;
}
if op == BinOp::FRem && single && fmf == every_flag() {
let Some(AirIntrinsic::Math(fmod)) =
AirIntrinsic::parse("air.fast_fmod.f32")
else {
panic!("air.fast_fmod.f32 does not parse");
};
let want =
float_call_notes(fmod, fmf, &p).expect("fast fmod is a float function");
assert_eq!(notes, want, "{what}");
continue;
}
if op == BinOp::FDiv && single {
let want: BTreeSet<_> = [
PrecisionNote::DeviceArithmetic,
PrecisionNote::NativeDivision,
PrecisionNote::DeviceDenormals,
]
.into_iter()
.chain([PrecisionNote::NativeNanEncoding])
.collect();
assert_eq!(notes, want, "{what}");
continue;
}
assert_eq!(
notes.contains(&PrecisionNote::DeviceArithmetic),
matches!(op, BinOp::FDiv | BinOp::FRem),
"{what}"
);
// Metal's canonical NaN: a `float` or `half` `+ - *`, and a `float`
// remainder.
let canonical = (matches!(fmt, FloatFmt::F32 | FloatFmt::Half)
&& matches!(op, BinOp::FAdd | BinOp::FSub | BinOp::FMul))
|| (op == BinOp::FRem && single);
assert_eq!(
notes.contains(&PrecisionNote::NativeNanEncoding),
canonical,
"{what}"
);
assert_eq!(
notes.contains(&PrecisionNote::DeviceDenormals),
single,
"{what}"
);
}
}
}
@@ -506,7 +458,7 @@ fn a_float_division_is_the_devices_arithmetic_unless_it_is_metals_precise_one()
/// either mode, with or without flags; a `half` one records `NativeTranscendentals` for its zero
/// remainder's sign, its `float` remainder's, where Metal's `half` answers `+0`
/// (`FloatFn::half_zero_of_float`). Precise `sqrt` and `rsqrt`, which Metal documents correctly rounded, are the
/// device's `Sqrt` and `InverseSqrt`: off Metal's own functions they record the device's precision
/// device's `Sqrt` and `InverseSqrt`: they record the device's precision
/// (`NativeTranscendentals`), as precise `exp`, which Apple bounds by ulps, does.
#[test]
fn precise_fmod_records_no_precision_note_and_the_roots_the_devices() {
@@ -519,43 +471,34 @@ fn precise_fmod_records_no_precision_note_and_the_roots_the_devices() {
Some(AirIntrinsic::Math(call)) => call,
_ => panic!("{name} is a math call"),
};
for ((_, metal_functions, _, _), (stem, p)) in one_profile_per_class() {
for (stem, p) in one_profile_per_class().into_values() {
for name in ["air.fmod.f32", "air.fmod.f16"] {
for fmf in [FastMath::NONE, every_flag()] {
for math in [EntryMath::Fast, EntryMath::Precise] {
let notes = PrecisionNote::of_math_call(parse(name), fmf, &p, math)
.unwrap_or_else(|| panic!("{name} is a float function"));
let half_zero = name.ends_with("f16");
assert!(
function_notes.iter().all(|note| {
notes.contains(note)
== (half_zero && *note == PrecisionNote::NativeTranscendentals)
}),
"{name} under {fmf:?} on {stem}, {math:?}: {notes:?}"
);
}
}
}
if !metal_functions {
for name in [
"air.sqrt.f32",
"air.rsqrt.f32",
"air.sqrt.f16",
"air.rsqrt.f16",
"air.exp.f32",
] {
let notes = PrecisionNote::of_math_call(
parse(name),
FastMath::NONE,
&p,
EntryMath::Precise,
)
.unwrap_or_else(|| panic!("{name} is a float function"));
let notes = PrecisionNote::of_math_call(parse(name), fmf, &p)
.unwrap_or_else(|| panic!("{name} is a float function"));
let half_zero = name.ends_with("f16");
assert!(
notes.contains(&PrecisionNote::NativeTranscendentals),
"{name} on {stem}: {notes:?}"
function_notes.iter().all(|note| {
notes.contains(note)
== (half_zero && *note == PrecisionNote::NativeTranscendentals)
}),
"{name} under {fmf:?} on {stem}: {notes:?}"
);
}
}
for name in [
"air.sqrt.f32",
"air.rsqrt.f32",
"air.sqrt.f16",
"air.rsqrt.f16",
"air.exp.f32",
] {
let notes = PrecisionNote::of_math_call(parse(name), FastMath::NONE, &p)
.unwrap_or_else(|| panic!("{name} is a float function"));
assert!(
notes.contains(&PrecisionNote::NativeTranscendentals),
"{name} on {stem}: {notes:?}"
);
}
}
}
@@ -6,12 +6,10 @@
//!
//! Each kernel loops over its rows (three operand words a row in `[[buffer(0)]]`) and stores one
//! answer word a row in `[[buffer(1)]]`. The CPU SPIR-V interpreter keeps denormals, as a device
//! without `DriverDeviation::MetalFloatDenormals` may, so on each such committed profile (one per
//! fused multiply-add route) an entry that records no `PrecisionNote::DeviceDenormals` must answer
//! every row as Metal did. `llvm-as` assembles the module; without it the tests skip visibly.
//! may, so on each committed profile (one per fused multiply-add route) an entry that records no
//! `PrecisionNote::DeviceDenormals` must answer every row as Metal did. `llvm-as` assembles the module; without it the tests skip visibly.
use crate::device::{DevicePolicy, DeviceProfile};
use crate::error::DriverDeviation;
use crate::lower::arith::fma;
use crate::pipeline::artifact::PrecisionNote;
use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage};
@@ -257,14 +255,13 @@ fn interpret(bc: &[u8], name: &str, p: &DeviceProfile, rows: &[([u32; 3], [u32;
.collect()
}
/// The committed profiles under `policy` whose device may keep denormals (no
/// `DriverDeviation::MetalFloatDenormals`), one per fused multiply-add route.
/// The committed profiles under `policy`, one per fused multiply-add route: each device may keep
/// denormals.
fn profiles(policy: DevicePolicy) -> Vec<(String, DeviceProfile)> {
let mut seen = BTreeSet::new();
committed_profiles_with(policy)
.expect("profiles")
.into_iter()
.filter(|(_, p)| !p.takes_driver_deviation(DriverDeviation::MetalFloatDenormals))
.filter(|(_, p)| seen.insert(fma::float_route(p)))
.collect()
}
@@ -28,7 +28,6 @@
//! `llvm-as` assembles the modules; without it the tests skip visibly.
use crate::air::{self, SpecRequest};
use crate::device::profile::FloatFunctions;
use crate::lower::emit::emit_module;
use crate::lower::select::{select, LowerInputs};
use crate::lower::simd::WidestPin;
@@ -62,12 +61,8 @@ struct Kernel {
has: &'static [u32],
lacks: &'static [u32],
/// 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.
/// recording `NativeTranscendentals`.
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>,
}
@@ -79,7 +74,6 @@ const KERNELS: [Kernel; 7] = [
has: &[TANH],
lacks: &[EXP2],
native: true,
off_metal: true,
want: None,
},
Kernel {
@@ -88,7 +82,6 @@ const KERNELS: [Kernel; 7] = [
has: &[TANH],
lacks: &[EXP2],
native: false,
off_metal: false,
want: None,
},
Kernel {
@@ -97,7 +90,6 @@ const KERNELS: [Kernel; 7] = [
has: &[TANH],
lacks: &[EXP2],
native: true,
off_metal: true,
want: None,
},
Kernel {
@@ -106,7 +98,6 @@ const KERNELS: [Kernel; 7] = [
has: &[FSIGN],
lacks: &[],
native: true,
off_metal: false,
want: Some(0xBF80_0000),
},
Kernel {
@@ -115,7 +106,6 @@ const KERNELS: [Kernel; 7] = [
has: &[FSIGN],
lacks: &[],
native: true,
off_metal: false,
want: Some(0xBF80_0000),
},
Kernel {
@@ -124,7 +114,6 @@ const KERNELS: [Kernel; 7] = [
has: &[SIN, ROUND_EVEN],
lacks: &[],
native: false,
off_metal: false,
want: None,
},
Kernel {
@@ -133,7 +122,6 @@ const KERNELS: [Kernel; 7] = [
has: &[SIN, ROUND_EVEN],
lacks: &[],
native: false,
off_metal: false,
want: None,
},
];
@@ -259,21 +247,16 @@ fn metal_math_variants_select_their_forms() {
"{what}: GLSL.std.450 {i} present ({ext:?})"
);
}
let metal = p.fields().float_functions == FloatFunctions::Metal;
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; `fast::tanh` is
// MSL's precise `tanh`, and a `half` `tanh` MSL's `float` one rounded to `half`.
// The device's instruction: noted `NativeTranscendentals`.
if k.native {
assert_eq!(
assert!(
a.precision.contains(&PrecisionNote::NativeTranscendentals),
!metal,
"{what}: {:?}",
a.precision
);
assert_eq!(
a.precision.contains(&PrecisionNote::DeviceTranscendentals),
metal && k.off_metal,
assert!(
!a.precision.contains(&PrecisionNote::DeviceTranscendentals),
"{what}: {:?}",
a.precision
);
@@ -420,8 +420,7 @@ fn half_nan(bits: u32) -> bool {
/// infinities and NaNs returned with their bits and exponent 0, `ilogb` `INT_MAX` for an infinity
/// and `INT_MIN` for a NaN, lane by lane. The one exception: a module that records
/// `NativeNanEncoding` answers a `half` NaN's mantissa with a NaN of the device's bits; every
/// `half` kernel records it, on a profile whose moves of a NaN are measured to be Metal's
/// (`DriverDeviation::MetalNanMoves`) too, since the routines read the widened value's bits.
/// `half` kernel records it, since the routines read the widened value's bits.
#[test]
fn frexp_and_ilogb_answer_as_metals_routines() {
let Some(bc) = assemble() else {
@@ -434,8 +433,7 @@ fn frexp_and_ilogb_answer_as_metals_routines() {
let a = compile(&bc, k.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}"));
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let device_nans = a.precision.contains(&PrecisionNote::NativeNanEncoding);
// The routines read a `half`'s widened bits, which the device's measured moves of a
// NaN do not cover (`narrow::moves_unfolded`): noted on every profile.
// The routines read a `half`'s widened bits: noted on every profile.
assert!(!k.half || device_nans, "{what}: {:?}", a.precision);
let got = interpret(&bc, k, &p, &what);
for (i, &(x, mantissa, exponent, ilogb)) in k.inputs().iter().enumerate() {
@@ -193,8 +193,7 @@ fn half_rounding_is_the_devices_on_every_profile() {
}
/// On lavapipe and MoltenVK (`shaderFloat16`, no `DenormPreserve` for 16 bits) each kernel rounds
/// its `half` through the conversion, records `NativeHalfConversion` and requires no
/// `VkProperty::MetalHalfConversion`; on a profile without `shaderFloat16` it quantizes and
/// its `half` through the conversion and records `NativeHalfConversion`; on a profile without `shaderFloat16` it quantizes and
/// records `NativeHalfQuantize`; RADV takes the controlled conversion and holds `half` at 16 bits
/// under those controls: its sum, between exact conversions, records nothing, and its narrowing
/// widened back, a conversion pair a driver's compiler may fold, records `NativeHalfConversion`.
@@ -202,7 +201,7 @@ fn half_rounding_is_the_devices_on_every_profile() {
/// whose conversion and quantize round to nearest even, the native modules answer Metal's
/// `half(float)`, but for the quantize's zero below the smallest normal half.
#[test]
fn native_half_rounding_records_its_kind_and_requires_no_fact() {
fn native_half_rounding_records_its_kind() {
let Some(bc) = bitcode() else {
return;
};
@@ -225,12 +224,6 @@ fn native_half_rounding_records_its_kind_and_requires_no_fact() {
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let noted: Vec<_> = natives.iter().filter(|n| a.precision.contains(n)).collect();
assert_eq!(noted, note.iter().collect::<Vec<_>>(), "{what}");
assert!(
!a.requirements
.properties
.contains(&VkProperty::MetalHalfConversion),
"{what}"
);
}
}
// Metal's `half(float)` on the interpreter's nearest-even conversion and quantize: a tie to
@@ -392,7 +385,7 @@ fn decodes(m: &TypedModule) -> (usize, usize) {
/// where the device flushes 16-bit denormals, a denormal); on NVIDIA, under the float controls (its
/// driver folds only the conversion's round trip, `narrow::half_controls`), `NativeNanEncoding`
/// alone; on the floor (no `shaderFloat16`) it is `UnpackHalf2x16` of each word, recording both
/// notes. None requires `VkProperty::MetalHalfArithmetic`. A `half4` widens as one vector (two
/// notes. A `half4` widens as one vector (two
/// words unpacked and shuffled where the device unpacks). Each module passes L3 and answers the
/// `half`s' values on the interpreter (whose widening is exact).
#[test]
@@ -445,13 +438,6 @@ fn a_half_decode_is_the_devices_widening_inside_loops_and_out() {
"{what}: {:?}",
a.precision
);
assert!(
!a.requirements
.properties
.contains(&VkProperty::MetalHalfArithmetic),
"{what}: {:?}",
a.requirements.properties
);
let res = Resources {
buffers: vec![Buffer {
slot: Some(ResourceSlot {
@@ -1006,11 +992,10 @@ fn half_load_module() -> String {
/// controls (ANV, RADV, the RTX 50 series) its entry declares them (`narrow::controlled_modes`, so
/// a half denormal widens exactly) and it records no other note; elsewhere (lavapipe and MoltenVK:
/// the device's conversion, no float controls) it records `NativeHalfConversion`, whose bound holds
/// a denormal the device flushes. None requires `VkProperty::MetalHalfArithmetic` or
/// `VkProperty::MetalNanMoves`. Without it (Pascal,
/// a denormal the device flushes. Without it (Pascal,
/// the LunarG baseline, SwiftShader, the floor) the widening is one `UnpackHalf2x16` of the word,
/// a 16-bit unit's zero extension where the profile has 16-bit storage, with no 16-bit float type,
/// recording `NativeHalfConversion` too and requiring no fact. Each passes L3; on the interpreter
/// recording `NativeHalfConversion` too. Each passes L3; on the interpreter
/// a half denormal, a zero's sign, `65504` and an infinity read as their values, and a NaN as a
/// NaN; the `half` stored back unchanged keeps its bits, NaNs included.
#[test]
@@ -1029,21 +1014,12 @@ fn a_half_read_from_memory_is_the_devices_widening_on_every_profile() {
link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let r = rounding(&a.module.words);
assert_eq!(r.narrowings, 0, "{what}: {r:?}");
let fact = a
.requirements
.properties
.contains(&VkProperty::MetalHalfArithmetic);
let nan = a.precision.contains(&PrecisionNote::NativeNanEncoding);
let moved = a
.requirements
.properties
.contains(&VkProperty::MetalNanMoves);
let conversion = a.precision.contains(&PrecisionNote::NativeHalfConversion);
assert!(!moved, "{what}: {:?}", a.requirements.properties);
match form {
QuantizeForm::Device => {
assert_eq!((r.widenings, r.unpacks), (0, 1), "{what}: {r:?}");
assert!(nan && conversion && !fact, "{what}: {:?}", a.precision);
assert!(nan && conversion, "{what}: {:?}", a.precision);
}
QuantizeForm::Controlled => {
assert_eq!((r.widenings, r.unpacks), (1, 0), "{what}: {r:?}");
@@ -1053,11 +1029,11 @@ fn a_half_read_from_memory_is_the_devices_widening_on_every_profile() {
"{what}: {mode:?} {r:?}"
);
}
assert!(nan && !conversion && !fact, "{what}: {:?}", a.precision);
assert!(nan && !conversion, "{what}: {:?}", a.precision);
}
QuantizeForm::Converted => {
assert_eq!((r.widenings, r.unpacks), (1, 0), "{what}: {r:?}");
assert!(nan && conversion && !fact, "{what}: {:?}", a.precision);
assert!(nan && conversion, "{what}: {:?}", a.precision);
for mode in [M::RoundingModeRTE, M::DenormPreserve] {
assert!(
!r.modes.contains(&(mode as u32, 16)),
@@ -1169,7 +1145,7 @@ fn f16_arithmetic(words: &[u32]) -> Vec<(crate::spv::Op, bool)> {
/// profiles): under fast math its one 16-bit instruction is undecorated, a product a plain
/// `OpFMul`; under `contract` alone or no flag it is kept apart, decorated `NoContraction`, a
/// product `Fma(a, b, -0.0)`. A lone operation has no neighbour to be rewritten with, so the module
/// notes nothing, as for `float`, and requires no `VkProperty::MetalHalfArithmetic`. On the
/// notes nothing, as for `float`. On the
/// interpreter each answers the rounded result either way.
#[test]
fn half_arithmetic_on_the_device_takes_the_airs_contraction() {
@@ -1204,13 +1180,6 @@ fn half_arithmetic_on_the_device_takes_the_airs_contraction() {
"{what}: {:?}",
a.precision
);
assert!(
!a.requirements
.properties
.contains(&VkProperty::MetalHalfArithmetic),
"{what}: {:?}",
a.requirements.properties
);
}
let run = |name: &str, x: [f32; 2]| interpret(&bc, name, p, x);
let (x, y) = (1.0 + 2f32.powi(-10), 2f32.powi(-11));
@@ -12,7 +12,7 @@
//! `llvm-as` assembles the module; without it the tests skip visibly.
use crate::air::{self, SpecRequest};
use crate::device::profile::{DeviceProfile, FloatFunctions};
use crate::device::profile::DeviceProfile;
use crate::device::DevicePolicy;
use crate::lower::emit::emit_module;
use crate::lower::select::{select, LowerInputs};
@@ -24,7 +24,6 @@ use crate::pipeline::testing::{
};
use crate::pipeline::PrecisionNote;
use crate::spirv::interp::{run, Buffer, Config, Resources};
use crate::spirv::testing::committed_profiles_with;
const OP_FUNCTION: u32 = 54;
@@ -211,16 +210,6 @@ fn ulps(got: f32, want: f64) -> f64 {
(f64::from(got) - want).abs() / ulp
}
/// On every committed profile the maths functions are the device's.
#[test]
fn the_maths_functions_are_the_device_s() {
let profiles = committed_profiles_with(DevicePolicy::default()).expect("profiles");
assert!(profiles.len() >= 10, "{} profiles", profiles.len());
for (stem, p) in &profiles {
assert_eq!(p.fields().float_functions, FloatFunctions::Native, "{stem}");
}
}
/// On lavapipe each kernel records its kind, passes L3, and is its entry alone (no routine).
#[test]
fn each_kernel_records_its_kind() {
@@ -925,12 +925,9 @@ attributes #4 = { nounwind willreturn memory(argmem: write) }\n\
/// A `float` narrowed to a stored `half` (`vstore_half_rtz`, and a plain `fptrunc` stored) is the
/// device's conversion, whose NaN's bits are its own (NVIDIA's 0x7fff where Metal stores 0x7e00):
/// on every committed profile the kernel's module records `NativeNanEncoding`, which the runtime
/// announces as `native-nan-encoding`, but where the device's narrowing is measured to move a NaN
/// as Metal's (`DriverDeviation::MetalNanMoves`), which the module then requires.
/// announces as `native-nan-encoding`.
#[test]
fn an_opencl_mode_half_store_records_the_devices_nan_encoding() {
use crate::device::requirements::VkProperty;
use crate::error::DriverDeviation;
use crate::pipeline::PrecisionNote;
let b = Budget::standard();
let mut checked = 0;
@@ -948,22 +945,10 @@ fn an_opencl_mode_half_store_records_the_devices_nan_encoding() {
Err(e) => panic!("{what}: {e}"),
};
let notes = &p.stage.precision_notes;
match dev
.profile()
.takes_driver_deviation(DriverDeviation::MetalNanMoves)
{
true => assert!(
notes.contains(&PrecisionNote::NativeNanEncoding)
|| p.requirements
.properties
.contains(&VkProperty::MetalNanMoves),
"{what}: {notes:?}"
),
false => assert!(
notes.contains(&PrecisionNote::NativeNanEncoding),
"{what}: {notes:?}"
),
}
assert!(
notes.contains(&PrecisionNote::NativeNanEncoding),
"{what}: {notes:?}"
);
checked += 1;
}
}
@@ -1,10 +1,8 @@
//! Rasterization-rate maps end to end (Apple's layout): `rasterization_rate_map_decoder`'s `float2`
//! maps compile to Apple's GPU decoder of Metal's parameter data on every tested profile, pass L3,
//! and record no `RasterizationRateMap` note (the decoder is Apple's arithmetic over Metal's
//! bytes). Its `float` arithmetic is the device's: Metal's on a device measured to read `float`
//! denormals as Metal does (`DriverDeviation::MetalFloatDenormals`, MoltenVK's), the device's own
//! denormals elsewhere, noted `DeviceDenormals`, and its `NaN` the device's, noted
//! `NativeNanEncoding` where the profile is not measured to answer Metal's. On the CPU interpreter,
//! bytes). Its `float` arithmetic is the device's: its denormals the device's own, noted
//! `DeviceDenormals`, and its `NaN` the device's, noted `NativeNanEncoding`. On the CPU interpreter,
//! which keeps `float` denormals as lavapipe does, the module computes the shader decoder's
//! arithmetic over the same bytes with denormals kept ([`kept`]): bit for bit, the sign of a zero
//! included (a `NaN` is any `NaN`), in both directions, for every layer (a layer past the map's
@@ -27,10 +25,8 @@ use std::sync::atomic::{AtomicU64, Ordering};
use crate::air::canon::rate_map_data as format;
use crate::bind::{RasterizationRateMap, RateMapAxis, RateMapDescriptor, RateMapLayerDescriptor};
use crate::device::profile::NanEncoding;
use crate::device::requirements::VkFeature;
use crate::device::{Device, DeviceDescription, DevicePolicy, DeviceProfile};
use crate::lower::arith::{denormal, nan};
use crate::lower::select::Plan;
use crate::pipeline::interface::PushLoc;
use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage};
@@ -273,8 +269,7 @@ fn maps() -> Vec<(&'static str, RasterizationRateMap)> {
/// Both maps of every layer, as the shader decoder's arithmetic computes them with the device's
/// denormals ([`kept`]), on every profile, with the notes of the device's arithmetic: no
/// `RasterizationRateMap`, `DeviceDenormals` where the profile does not read `float` denormals as
/// Metal does, and `NativeNanEncoding` where it is not measured to answer Metal's `NaN`. The
/// `RasterizationRateMap`, `DeviceDenormals` and `NativeNanEncoding`. The
/// answers are `bind::RasterizationRateMap`'s shader decoders' (Metal's) at every point of a
/// map's own layers; only a layer past a map's, whose tables are other words read as `float`s,
/// some of them denormal, answers otherwise at some points.
@@ -294,15 +289,13 @@ fn the_decoder_answers_as_the_map() {
"{what}: {:?}",
a.precision
);
assert_eq!(
assert!(
a.precision.contains(&PrecisionNote::DeviceDenormals),
!denormal::device_flushes(&p),
"{what}: {:?}",
a.precision
);
assert_eq!(
assert!(
a.precision.contains(&PrecisionNote::NativeNanEncoding),
nan::encoding(&p) == NanEncoding::Native,
"{what}: {:?}",
a.precision
);
@@ -826,9 +826,8 @@ fn simd_uniform_runs_emulated_at_every_width() {
/// out of both forms (1,145 against 462 words, 2.48x, to 1,136 against 453, 2.51x): the emulation's
/// 683 words over the subgroup form did not change, so the hold moved to 2.55x. Through
/// `Device::from_queries` the kernel is 1,164 words on `lavapipe` against 453 (2.57x), held at
/// 2.6x, still below the flag form's 112 extra words (about 2.75x against 453). The subgroup form is `moltenvk-m3`'s
/// without its driver's measured deviation (`MetalCanonicalNans`), which neither emulated profile
/// has, so both forms carry the same NaN selects (the input's `fadd` before the reduction: 14
/// 2.6x, still below the flag form's 112 extra words (about 2.75x against 453). The subgroup form is
/// `moltenvk-m3`'s, so both forms carry the same NaN selects (the input's `fadd` before the reduction: 14
/// words, 1,150 against 467 on `lavapipe`, 2.46x) and the ratio stays the emulation's. A profile
/// with no measured half-rounding fact (`lavapipe`, `vk12-floor`) rounds each `half` add in integer
/// arithmetic, twenty instructions, where `moltenvk-m3`'s measured conversion takes three. That
@@ -427,7 +427,7 @@ const OP_IS_NAN: u16 = 156;
/// `DeviceNanEncoding`; bound in `RGBA16Float` it records the note too; bound in `RGBA8Unorm` it
/// records none. Where the choice declares no format and no class, the write records the note
/// under the format bound there. A choice declaring `RGBA16Float` records the note on every
/// profile. No write requires `VkProperty::MetalHalfTexelWrites` or `VkProperty::MetalNanMoves`.
/// profile. No write requires `VkProperty::MetalHalfTexelWrites`.
#[test]
fn a_half_texel_write_records_the_device_nan_encoding_where_it_may_not_be_metal_s() {
use crate::device::requirements::VkProperty;
@@ -456,7 +456,6 @@ fn a_half_texel_write_records_the_device_nan_encoding_where_it_may_not_be_metal_
let required = |a: &FunctionArtifact| {
let properties = &a.requirements.properties;
properties.contains(&VkProperty::MetalHalfTexelWrites)
|| properties.contains(&VkProperty::MetalNanMoves)
};
let tests = |a: &FunctionArtifact| opcodes(&a.module.words).contains(&OP_IS_NAN);
for pf in [
@@ -9,13 +9,11 @@
//! `2^-126` there, and the module takes the device's multiply (announced once per device,
//! `float-tininess-after-rounding`).
//!
//! The CPU SPIR-V interpreter rounds first and keeps denormals, as a device without
//! `DriverDeviation::MetalFloatDenormals` may, so on each such committed profile (one per fused
//! multiply-add route) it shows what the device answers. `llvm-as` assembles the fixtures; without
//! The CPU SPIR-V interpreter rounds first and keeps denormals, as a device may, so on each
//! committed profile (one per fused multiply-add route) it shows what the device answers. `llvm-as` assembles the fixtures; without
//! it the tests skip visibly.
use crate::device::{DevicePolicy, DeviceProfile};
use crate::error::DriverDeviation;
use crate::lower::arith::fma;
use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage};
use crate::pipeline::testing::{
@@ -138,15 +136,13 @@ fn interpret(bc: &[u8], entry: &str, p: &DeviceProfile, threads: &[Thread]) -> V
.collect()
}
/// The committed profiles whose device may keep denormals (no
/// `DriverDeviation::MetalFloatDenormals`), as the interpreter does, one per fused multiply-add
/// route.
/// The committed profiles, one per fused multiply-add route: each device may keep denormals, as
/// the interpreter does.
fn keeping() -> Vec<(String, DeviceProfile)> {
let mut seen = BTreeSet::new();
committed_profiles_with(DevicePolicy::default())
.expect("profiles")
.into_iter()
.filter(|(_, p)| !p.takes_driver_deviation(DriverDeviation::MetalFloatDenormals))
.filter(|(_, p)| seen.insert(fma::float_route(p)))
.collect()
}
@@ -179,8 +179,7 @@ fn run_both(m: &TypedModule, res: &Resources) -> Vec<u32> {
}
/// Whether entry `entry` of `bc` on `prof` reads a `half` from its bits by the device's widening
/// (`PrecisionNote::NativeNanEncoding`, or `VkProperty::MetalNanMoves` on a device the interpreter
/// is not: `device_nan_bits`), whose reinterpretation of a NaN's bits is the device's.
/// (`PrecisionNote::NativeNanEncoding`, `device_nan_bits`), whose reinterpretation of a NaN's bits is the device's.
fn native_halves(bc: &[u8], entry: &str, prof: &DeviceProfile) -> bool {
device_nan_bits(&compile(bc, entry, prof).expect("compile"))
}
+4 -25
View File
@@ -927,7 +927,6 @@ enum metal2vulkan::pipeline::BufferForm #[cfg_attr(feature = "serde", derive(ser
enum metal2vulkan::pipeline::BufferKind #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum BufferKind
enum metal2vulkan::pipeline::ChannelWrite #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum ChannelWrite
enum metal2vulkan::pipeline::DescriptorView #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum DescriptorView
enum metal2vulkan::pipeline::EntryMath #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum EntryMath
enum metal2vulkan::pipeline::EntryRef #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum EntryRef<'a>
enum metal2vulkan::pipeline::FactorLane #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum FactorLane
enum metal2vulkan::pipeline::HandleClass #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum HandleClass
@@ -6650,8 +6649,8 @@ method metal2vulkan-runtime::MemoryClass::block_len pub const fn block_len(self)
method metal2vulkan-runtime::PhysicalDevice::check pub fn check(&self) -> Result<floor::Capabilities, floor::BelowFloor>
method metal2vulkan-runtime::PhysicalDevice::raw pub fn raw(&self) -> vk::PhysicalDevice
method metal2vulkan-runtime::PixelFormatInfo::describes_a_format pub fn describes_a_format(&self) -> bool
method metal2vulkan-runtime::PrecisionNote::of_float_operator pub fn of_float_operator(op: AirBin, width: FloatWidth, fmf: FastMath, p: &DeviceProfile, math: EntryMath) -> Option<BTreeSet<PrecisionNote>>
method metal2vulkan-runtime::PrecisionNote::of_math_call pub fn of_math_call(call: Math, fmf: FastMath, p: &DeviceProfile, math: EntryMath) -> Option<BTreeSet<PrecisionNote>>
method metal2vulkan-runtime::PrecisionNote::of_float_operator pub fn of_float_operator(op: AirBin, width: FloatWidth, fmf: FastMath, p: &DeviceProfile) -> Option<BTreeSet<PrecisionNote>>
method metal2vulkan-runtime::PrecisionNote::of_math_call pub fn of_math_call(call: Math, fmf: FastMath, p: &DeviceProfile) -> Option<BTreeSet<PrecisionNote>>
method metal2vulkan-runtime::RenderCommandEncoder::draw_indexed_primitives pub fn draw_indexed_primitives(&mut self, primitive_type: PrimitiveType, index_count: u32, indices: IndexBuffer<'_>, instance_count: u32, base_vertex: i32, base_instance: u32) -> Result<(), Error>
method metal2vulkan-runtime::RenderCommandEncoder::draw_patches pub fn draw_patches(&mut self, number_of_patch_control_points: u32, patch_start: u32, patch_count: u32, patch_index_buffer: Option<(&Buffer, u64)>, instance_count: u32, base_instance: u32) -> Result<(), Error>
method metal2vulkan-runtime::RenderCommandEncoder::draw_primitives pub fn draw_primitives(&mut self, primitive_type: PrimitiveType, vertex_start: u32, vertex_count: u32, instance_count: u32, base_instance: u32) -> Result<(), Error>
@@ -7282,8 +7281,8 @@ method metal2vulkan::pipeline::MeshPipelineDescriptor::reflection pub fn reflect
method metal2vulkan::pipeline::MeshPipelineDescriptor::slot_writes pub fn slot_writes(&self, budget: &crate::Budget) -> Result<SlotWrites, Error>
method metal2vulkan::pipeline::MeshPipelineDescriptor::stages_using_direct_arguments pub fn stages_using_direct_arguments(&self, budget: &crate::Budget, entries: &StageEntries) -> Result<Vec<DirectArgumentUse>, Error>
method metal2vulkan::pipeline::MeshPipelineDescriptor::unwritten_fragment_inputs pub fn unwritten_fragment_inputs(&self, budget: &crate::Budget, entries: &StageEntries) -> Result<Option<UnwrittenFragmentInputs>, Error>
method metal2vulkan::pipeline::PrecisionNote::of_float_operator pub fn of_float_operator(op: AirBin, width: FloatWidth, fmf: FastMath, p: &DeviceProfile, math: EntryMath) -> Option<BTreeSet<PrecisionNote>>
method metal2vulkan::pipeline::PrecisionNote::of_math_call pub fn of_math_call(call: Math, fmf: FastMath, p: &DeviceProfile, math: EntryMath) -> Option<BTreeSet<PrecisionNote>>
method metal2vulkan::pipeline::PrecisionNote::of_float_operator pub fn of_float_operator(op: AirBin, width: FloatWidth, fmf: FastMath, p: &DeviceProfile) -> Option<BTreeSet<PrecisionNote>>
method metal2vulkan::pipeline::PrecisionNote::of_math_call pub fn of_math_call(call: Math, fmf: FastMath, p: &DeviceProfile) -> Option<BTreeSet<PrecisionNote>>
method metal2vulkan::pipeline::PrivateRenderState::new pub const fn new() -> PrivateRenderState
method metal2vulkan::pipeline::RenderPipeline::content_digest pub fn content_digest(&self) -> Hash256
method metal2vulkan::pipeline::RenderPipeline::footprint pub fn footprint(&self) -> u64
@@ -10265,24 +10264,16 @@ variant metal2vulkan::device::VkProperty::MetalCenterVaryings MetalCenterVarying
variant metal2vulkan::device::VkProperty::MetalDepth16BiasedStores MetalDepth16BiasedStores
variant metal2vulkan::device::VkProperty::MetalDepth16Stores MetalDepth16Stores
variant metal2vulkan::device::VkProperty::MetalFirstVertexIndices MetalFirstVertexIndices
variant metal2vulkan::device::VkProperty::MetalFloatDenormals MetalFloatDenormals
variant metal2vulkan::device::VkProperty::MetalFragmentSimdgroups MetalFragmentSimdgroups
variant metal2vulkan::device::VkProperty::MetalFullQuads MetalFullQuads
variant metal2vulkan::device::VkProperty::MetalHalfArithmetic MetalHalfArithmetic
variant metal2vulkan::device::VkProperty::MetalHalfConversion MetalHalfConversion
variant metal2vulkan::device::VkProperty::MetalHalfFma MetalHalfFma
variant metal2vulkan::device::VkProperty::MetalHalfStorageNans MetalHalfStorageNans
variant metal2vulkan::device::VkProperty::MetalHalfStorageWrites MetalHalfStorageWrites
variant metal2vulkan::device::VkProperty::MetalHalfTexelWrites MetalHalfTexelWrites
variant metal2vulkan::device::VkProperty::MetalInterpolation MetalInterpolation
variant metal2vulkan::device::VkProperty::MetalMinMax MetalMinMax
variant metal2vulkan::device::VkProperty::MetalNanMoves MetalNanMoves
variant metal2vulkan::device::VkProperty::MetalNormStorageWrites MetalNormStorageWrites
variant metal2vulkan::device::VkProperty::MetalNormalizedVertexFetch MetalNormalizedVertexFetch
variant metal2vulkan::device::VkProperty::MetalPackConversions MetalPackConversions
variant metal2vulkan::device::VkProperty::MetalSampler MetalSampler
variant metal2vulkan::device::VkProperty::MetalSmallFloatNans MetalSmallFloatNans
variant metal2vulkan::device::VkProperty::MetalUnaryDenormals MetalUnaryDenormals
variant metal2vulkan::device::VkProperty::MetalVertexSimdgroups MetalVertexSimdgroups
variant metal2vulkan::device::VkProperty::ProvokingVertexModePerPipeline ProvokingVertexModePerPipeline
variant metal2vulkan::device::VkProperty::RequiredSubgroupSizeStage RequiredSubgroupSizeStage(Stage)
@@ -10433,30 +10424,20 @@ variant metal2vulkan::error::DescriptorError::VertexStepRate VertexStepRate { st
variant metal2vulkan::error::DriverDeviation::CubeGradientRoute CubeGradientRoute
variant metal2vulkan::error::DriverDeviation::GraphicsCubeGradientTangents GraphicsCubeGradientTangents
variant metal2vulkan::error::DriverDeviation::MetalAlphaCoverage MetalAlphaCoverage
variant metal2vulkan::error::DriverDeviation::MetalCanonicalNans MetalCanonicalNans
variant metal2vulkan::error::DriverDeviation::MetalCenterVaryings MetalCenterVaryings
variant metal2vulkan::error::DriverDeviation::MetalDepth16BiasedStores MetalDepth16BiasedStores
variant metal2vulkan::error::DriverDeviation::MetalDepth16Stores MetalDepth16Stores
variant metal2vulkan::error::DriverDeviation::MetalFirstVertexIndices MetalFirstVertexIndices
variant metal2vulkan::error::DriverDeviation::MetalFloatDenormals MetalFloatDenormals
variant metal2vulkan::error::DriverDeviation::MetalFloatFunctions MetalFloatFunctions
variant metal2vulkan::error::DriverDeviation::MetalFragmentSimdgroups MetalFragmentSimdgroups
variant metal2vulkan::error::DriverDeviation::MetalFullQuads MetalFullQuads
variant metal2vulkan::error::DriverDeviation::MetalHalfArithmetic MetalHalfArithmetic
variant metal2vulkan::error::DriverDeviation::MetalHalfConversion MetalHalfConversion
variant metal2vulkan::error::DriverDeviation::MetalHalfFma MetalHalfFma
variant metal2vulkan::error::DriverDeviation::MetalHalfStorageNans MetalHalfStorageNans
variant metal2vulkan::error::DriverDeviation::MetalHalfStorageWrites MetalHalfStorageWrites
variant metal2vulkan::error::DriverDeviation::MetalHalfTexelWrites MetalHalfTexelWrites
variant metal2vulkan::error::DriverDeviation::MetalInterpolation MetalInterpolation
variant metal2vulkan::error::DriverDeviation::MetalMinMax MetalMinMax
variant metal2vulkan::error::DriverDeviation::MetalNanMoves MetalNanMoves
variant metal2vulkan::error::DriverDeviation::MetalNormStorageWrites MetalNormStorageWrites
variant metal2vulkan::error::DriverDeviation::MetalNormalizedVertexFetch MetalNormalizedVertexFetch
variant metal2vulkan::error::DriverDeviation::MetalPackConversions MetalPackConversions
variant metal2vulkan::error::DriverDeviation::MetalSampler MetalSampler
variant metal2vulkan::error::DriverDeviation::MetalSmallFloatNans MetalSmallFloatNans
variant metal2vulkan::error::DriverDeviation::MetalUnaryDenormals MetalUnaryDenormals
variant metal2vulkan::error::DriverDeviation::MetalVertexSimdgroups MetalVertexSimdgroups
variant metal2vulkan::error::DriverDeviation::SimdgroupLockstep SimdgroupLockstep
variant metal2vulkan::error::DynamicLibraryProblem::FunctionConstants FunctionConstants
@@ -10853,8 +10834,6 @@ variant metal2vulkan::pipeline::ChannelWrite::Unorm Unorm { bits: u8 }
variant metal2vulkan::pipeline::DescriptorView::Storage Storage
variant metal2vulkan::pipeline::DescriptorView::UniformVec4 UniformVec4
variant metal2vulkan::pipeline::DescriptorView::UniformWords UniformWords
variant metal2vulkan::pipeline::EntryMath::Fast Fast
variant metal2vulkan::pipeline::EntryMath::Precise Precise
variant metal2vulkan::pipeline::EntryRef::Index Index(u32)
variant metal2vulkan::pipeline::EntryRef::Name Name(&'a str)
variant metal2vulkan::pipeline::FactorLane::One One
Can't render this file because it is too large.
+8 -18
View File
@@ -316,7 +316,6 @@ surface! {
struct ComputePipelineMetalInfo N;
struct CompileReport N;
struct EntryDescriptor N;
enum EntryMath E;
struct EntryPlan N;
enum EntryRef E;
struct LinkedSource O;
@@ -936,7 +935,7 @@ use metal2vulkan::library::{CompiledFunction, Library};
use metal2vulkan::metal::{PixelFormat, VertexFormat};
use metal2vulkan::pipeline::{
ColorAttachmentDescriptor, ComputePipeline, ComputePipelineDescriptor, EntryDescriptor,
EntryMath, EntryRef, FunctionDescriptor, LoweringInputs, PrecisionNote, RenderPipeline,
EntryRef, FunctionDescriptor, LoweringInputs, PrecisionNote, RenderPipeline,
RenderPipelineDescriptor, Stage, StageSource, VertexAttributeDescriptor,
VertexBufferLayoutDescriptor, VertexDescriptor,
};
@@ -1222,12 +1221,11 @@ fn the_precision_contract_names_each_float_operations_notes() {
.fold(FastMath::NONE, |all, (flag, _)| all.union(*flag));
let lavapipe = device("lavapipe");
let lavapipe = lavapipe.profile();
let fdiv = |p: &metal2vulkan::device::DeviceProfile, math| {
PrecisionNote::of_float_operator(BinOp::FDiv, FloatWidth::F32, fast, p, math)
};
assert!(fdiv(lavapipe, EntryMath::Fast)
.expect("a float operator")
.contains(&PrecisionNote::DeviceArithmetic));
assert!(
PrecisionNote::of_float_operator(BinOp::FDiv, FloatWidth::F32, fast, lavapipe)
.expect("a float operator")
.contains(&PrecisionNote::DeviceArithmetic)
);
let native = device_under("lavapipe", DevicePolicy::default());
assert_eq!(
PrecisionNote::of_float_operator(
@@ -1235,7 +1233,6 @@ fn the_precision_contract_names_each_float_operations_notes() {
FloatWidth::F32,
FastMath::NONE,
native.profile(),
EntryMath::Precise
),
Some(BTreeSet::from([
PrecisionNote::DeviceDenormals,
@@ -1244,20 +1241,13 @@ fn the_precision_contract_names_each_float_operations_notes() {
]))
);
assert_eq!(
PrecisionNote::of_float_operator(
BinOp::Add,
FloatWidth::F32,
fast,
lavapipe,
EntryMath::Fast
),
PrecisionNote::of_float_operator(BinOp::Add, FloatWidth::F32, fast, lavapipe,),
None
);
let Some(AirIntrinsic::Math(tanh)) = AirIntrinsic::parse("air.fast_tanh.f32") else {
panic!("air.fast_tanh.f32 is a math call");
};
let notes = PrecisionNote::of_math_call(tanh, fast, lavapipe, EntryMath::Fast)
.expect("a float function");
let notes = PrecisionNote::of_math_call(tanh, fast, lavapipe).expect("a float function");
assert!(
notes.contains(&PrecisionNote::NativeTranscendentals),
"{notes:?}"
+4 -9
View File
@@ -45,10 +45,7 @@ A `half` computed in `float` rounds through the device's conversion to 16 bits a
`half(float)` under the float controls the entry declares, where the driver keeps that pair (ANV,
RADV). Elsewhere it rounds through the device's own conversion, or its `OpQuantizeToF16` alone
without `shaderFloat16` (which may flush a value below the smallest normal `half`), and the
pipeline records `NativeHalfConversion` or `NativeHalfQuantize`; not `NativeHalfConversion` on
MoltenVK on the Apple M3 Max's macOS 27 identity (`DriverDeviation::MetalHalfConversion`), where
every such `half` is a conversion of a `float` the function holds or of a texel, measured to be
Metal's. NVIDIA's driver (615.71.09) folds the pair even under the float controls, so its
pipeline records `NativeHalfConversion` or `NativeHalfQuantize`. NVIDIA's driver (615.71.09) folds the pair even under the float controls, so its
rounding there is the device's conversion, or none; its pipelines still declare the float controls
and compute a `half` `+`, `-`, `*`, `/` and `sqrt` with the device's 16-bit instructions, as ANV's
and RADV's do. RADV's compiler fuses a `float` addition, subtraction, multiply or fused
@@ -60,11 +57,9 @@ A `half` read from memory or from its bits is the device's widening on every dev
`OpFConvert` of the bits read as a 16-bit float with `shaderFloat16`, `GLSL.std.450
UnpackHalf2x16` without it), and a `half` stored or reinterpreted as bits, unless they are the
bits it was loaded from, the device's narrowing (an `OpFConvert` to 16 bits, `GLSL.std.450
PackHalf2x16` without `shaderFloat16`); the pipeline records `NativeNanEncoding` (a NaN's bits;
not on MoltenVK on the Apple M3 Max's macOS 27 identity, `DriverDeviation::MetalNanMoves`, where
the `half` moves through the registers alone or into a texture write's texel) and, where that conversion is neither under the
float controls nor measured to be Metal's, `NativeHalfConversion` (a denormal the device may
flush).
PackHalf2x16` without `shaderFloat16`); the pipeline records `NativeNanEncoding` (a NaN's bits)
and, where that conversion is not under the float controls, `NativeHalfConversion` (a denormal the
device may flush).
To read AIR without translating it (list a metallib's functions, decode a module into typed IR,
read its entry points' bindings, canonicalize an entry under function-constant values), depend on