translator: a controlled half pair is noted on every device; the two half workarounds go

What: a half rounded through the device's conversion and its widening under the 16-bit float
controls (QuantizeForm::Controlled) now records PrecisionNote::NativeHalfConversion on every
device, as a static note of the operation. Every profile with shaderFloat16 and those controls
takes that form, NVIDIA's included. DriverWorkaround::HalfConversionPairFolded (NVIDIA, identity)
and DriverWorkaround::HalfConversionFusedWithArithmetic (RADV, identity) are deleted, with
narrow::rounds_arithmetic, which only the second read.

Why: rule 2 of the owner's rules (one path for every device, no identity-keyed branch) and the
planner's ruling on these two rows of the workaround ladder. The pair is Metal's half(float) by
the Vulkan spec, but a driver's compiler may fold it (NVIDIA's) or fuse the float operation into
the narrowing (RADV's). Recording the note statically on every device covers both drivers with no
identity check, and it never refuses. NVIDIA's modules move from the Converted form to the
Controlled one (NoContraction on the pair, the entry declaring the 16-bit modes), so its golden
cells move. ANV's and RADV's modules gain only the note, which is not hashed. SEMANTICS_VERSION
goes to 2149.

Tests: engine_native_half, device::tests::profile (half_rounding_follows_the_queries_alone replaces
the two identity tests), engine_float_call_notes, and the native_maths and half_conversions
lanes, updated to expect the note on every controlled profile. Docs: API.md's
NativeHalfConversion entry and HOWTO.md. api_signatures.tsv loses the two variants, and
REFUSALS.md is regenerated unchanged.
This commit is contained in:
Anees Iqbal committed 2026-11-17 09:45:26 -08:00
1 parent eddc9b80bf
commit 07e62aa306
16 files changed
+225 -410

No files matched your search

@@ -14,10 +14,11 @@
//! the profile takes the deviation (MoltenVK on the Apple M3 Max's macOS 27 identity) the
//! conversion kernels record no `PrecisionNote::NativeHalfConversion` and every lane is Metal's
//! word; the `tanh` kernel records it there, as a `half` function computed in `float`. Under the
//! float controls (ANV, RADV) the conversion is Metal's and records no note, but where the driver
//! fuses the sum, the product or the fused multiply-add into it and rounds the exact result once
//! (RADV, `DriverWorkaround::HalfConversionFusedWithArithmetic`), which records it. Elsewhere a
//! kernel that rounds through the conversion records the note. A kernel that records it may answer
//! float controls (ANV, RADV, NVIDIA) the conversion and its widening are Metal's by the Vulkan
//! spec, but a driver's compiler may fold the pair (NVIDIA's) or fuse the sum, the product or the
//! fused multiply-add into the narrowing and round the exact result once (RADV's), so each kernel
//! that rounds through the pair records the note on every device, as it does elsewhere. A kernel
//! that records it may answer
//! the device's lanes, which the test prints as `HALF-CONVERSIONS` lines.
use super::degrade_notices::on_device_with;
@@ -24,7 +24,7 @@ use super::degrade_notices::{counts, on_device_with};
use super::{buffer_with, read_buffer, Messages, WAIT};
use crate::air_library::AirLibrary;
use metal2vulkan::cache::VariantKey;
use metal2vulkan::device::{DriverWorkaround, FloatControl, FloatWidth, VkProperty};
use metal2vulkan::device::{FloatControl, FloatWidth, VkProperty};
use metal2vulkan::error::DriverDeviation;
use metal2vulkan::library::Library;
use metal2vulkan::pipeline::{ComputePipelineDescriptor, FunctionDescriptor, PrecisionNote};
@@ -591,14 +591,14 @@ fn half_operand(r: &mut Stream) -> f32 {
/// `a` and the sum `a + b` rounded to `float` once (or of the operands rounded, or rounded
/// itself), exactly. CI's lavapipe (Mesa 26.0.8 with LLVM 21.1.8) rounds here (8192 of 8192). A
/// device whose float controls make its conversion Metal's (the module declares
/// `RoundingModeRTE`, `DenormPreserve` and `SignedZeroInfNanPreserve` for 16 bits: ANV and RADV)
/// records neither and answers Metal's exactly, and so does one whose conversion is measured to be
/// `RoundingModeRTE`, `DenormPreserve` and `SignedZeroInfNanPreserve` for 16 bits: ANV, RADV and
/// NVIDIA) computes the sum on its 16-bit addition of the narrowed operands, Metal's exactly, and
/// rounds `half(a)` through the conversion and its widening, a pair a driver's compiler may fold
/// (NVIDIA's: the RTX 3090 answers `a` itself), so the stage records `NativeHalfConversion` on
/// every such device and `half(a)` is within its bound. A device whose conversion is measured to be
/// Metal's (MoltenVK on the Apple M3 Max's macOS 27 identity,
/// `DriverDeviation::MetalHalfConversion`: the module requires its property), whose `half` sum
/// is its own 16-bit addition. NVIDIA's driver reports those controls but folds the conversion's
/// round trip (`DriverWorkaround::HalfConversionPairFolded`): its module declares them for the
/// sum, the device's 16-bit addition of the narrowed operands, Metal's exactly, while `half(a)`,
/// the round trip, stays the device's, recorded (the RTX 3090 answers `a` itself).
/// `DriverDeviation::MetalHalfConversion`: the module requires its property), whose `half` sum is
/// its own 16-bit addition, records neither and answers Metal's exactly.
#[test]
fn half_rounding_answers_within_its_recorded_bound() {
let bitcode = llvm_assemble_text(&half_kernel()).unwrap();
@@ -642,16 +642,15 @@ fn half_rounding_answers_within_its_recorded_bound() {
.filter(|note| kinds.contains(note))
.collect();
// A rounding by the bare quantize is the device's: only the float controls, or a
// conversion measured to be Metal's, answer Metal's.
// conversion measured to be Metal's, answer Metal's sum; only the measured conversion
// answers Metal's `half(a)`, the conversion's round trip, which a driver's compiler may
// fold under the controls.
let measured = required.contains(&VkProperty::MetalHalfConversion);
// A driver that folds the round trip leaves `half(a)` its own under the controls.
let folds = (device.compile_device().profile().workarounds())
.contains(&DriverWorkaround::HalfConversionPairFolded);
let sum_metal_s = controlled || measured;
let metal_s = (controlled && !folds) || measured;
let metal_s = measured;
eprintln!(
"{name}: float controls {controlled}; folded round trip {folds}; measured \
conversion {measured}; announced {announced:?}"
"{name}: float controls {controlled}; measured conversion {measured}; announced \
{announced:?}"
);
assert_eq!(announced.len(), usize::from(!metal_s), "{name}");
let operands = half_operands();
+5 -11
View File
@@ -469,18 +469,12 @@ fn by_identity(desc: &DeviceDescription) -> Vec<DriverWorkaround> {
Some(vk::DriverId::MESA_LLVMPIPE) => {
vec![DriverWorkaround::ClippedTrianglesSplitPixelFragments]
}
// A `half` round trip folded on every GPU it drives, and on the 3090's generation a
// narrow integer's mask dropped.
Some(vk::DriverId::NVIDIA_PROPRIETARY) => {
let mut found = vec![DriverWorkaround::HalfConversionPairFolded];
if super::NVIDIA_AMPERE_GA10X.contains(&desc.device_id) {
found.push(DriverWorkaround::NarrowMaskAfterSignedClamp);
}
found
// On the 3090's generation, a narrow integer's mask dropped.
Some(vk::DriverId::NVIDIA_PROPRIETARY)
if super::NVIDIA_AMPERE_GA10X.contains(&desc.device_id) =>
{
vec![DriverWorkaround::NarrowMaskAfterSignedClamp]
}
// An `f32` operation fused into the conversion of its result to `half`, on every GPU it
// drives.
Some(vk::DriverId::MESA_RADV) => vec![DriverWorkaround::HalfConversionFusedWithArithmetic],
// A register allocator that faults compiling a module past a word bound, products of one
// value by zeros of opposite sign kept as one, a stage past 2^20 objects of its
// serialized form corrupted, and a compiler whose memory outgrows the stage, on every GPU
-33
View File
@@ -1270,39 +1270,6 @@ pub enum DriverWorkaround {
/// emitted as `OpBitFieldUExtract(x, 0, N)` there (`lower::arith::ops::mask`), which is the
/// same bits on every device.
NarrowMaskAfterSignedClamp,
/// The driver's compiler folds a `half` round trip, an `OpFConvert` from 32- to 16-bit floats
/// and its widening back, each decorated `NoContraction`, into the 32-bit value it started
/// from, in an entry declaring `RoundingModeRTE`, `DenormPreserve` and
/// `SignedZeroInfNanPreserve` for 16 bits. Vulkan assumes no value-changing transform of an
/// operation decorated `NoContraction`, and rounds a conversion between types correctly
/// ("Precision and Operation of SPIR-V Instructions"). Measured on the GeForce RTX 3090
/// (`deviceID` 0x2204) under NVIDIA's 615.71.09 (`VK_DRIVER_ID_NVIDIA_PROPRIETARY`): of the
/// 2^32 `f32` values, the round trip left 2,231,288,832 off Metal's `half(float)`, under each
/// combination of those modes and with or without the decoration. Keyed on NVIDIA's driver
/// on every GPU, the others unmeasured. Such a profile rounds an `f32` to `half` in another
/// form (`lower::arith::narrow::quantize_form`), and computes under those controls all the
/// same (`lower::arith::narrow::half_controls`): its 16-bit instructions and a single
/// conversion between 16 and 32 bits are no round trip.
HalfConversionPairFolded,
/// The driver's compiler fuses an `f32` addition, subtraction, multiply or fused multiply-add
/// into the `OpFConvert` to 16 bits of its result, rounding the exact result to `half` once,
/// though both are decorated `NoContraction` (which forbids combining the operation with
/// another instruction into a single operation), in an entry declaring `RoundingModeRTE`,
/// `DenormPreserve` and `SignedZeroInfNanPreserve` for 16 bits. Metal rounds the `float` result
/// to `half`, so where that result lies on a `half` midpoint the two differ by one unit in the
/// last place of the `half`. Measured with Mesa 26.2.6 on the Radeon 780M (RADV PHOENIX,
/// GFX11): ACO compiled the product's `OpFMul` and the narrowing as one `v_fma_mixlo_f16` (a
/// sum's narrowing too), and the product of 2.6822087e-7 and 1.0000001 answered `0x0005` where
/// Metal's `half` of the `float` product is `0x0004`; the Radeon RX 7900 XTX (RADV NAVI31,
/// GFX11) answered as the 780M did, 4,542 of the 253,958 product lanes off Metal's on each
/// (`runtime_lane::half_conversions`). On the Radeon RX 550 (RADV POLARIS12, GFX8) the
/// narrowing alone answers its own way (8,185 of the 253,958 lanes of a loaded `float`), every
/// narrowing there records `PrecisionNote::NativeHalfConversion` already, and no fusion is told
/// apart. A fact of RADV's compiler, keyed on RADV (`VK_DRIVER_ID_MESA_RADV`) on every GPU;
/// other drivers unmeasured. Such a profile keeps the conversion under the float controls, and
/// a module that rounds such an operation's result through it records
/// `PrecisionNote::NativeHalfConversion` (`lower::arith::narrow::rounds_arithmetic`).
HalfConversionFusedWithArithmetic,
/// The driver refuses a fragment shader that reads both barycentric builtins,
/// `BaryCoordKHR` and `BaryCoordNoPerspKHR`, at pipeline creation, where Metal compiles a
/// fragment function that declares both `[[barycentric_coord, center_perspective]]` and
+31 -66
View File
@@ -768,11 +768,10 @@ fn moltenvk_on_apple_carries_the_early_tests_image_write_defect() {
desc.driver_id = Some(vk::DriverId::MESA_RADV);
// Every rasterizer but Apple's hands a clipped primitive's fragments other coverage than
// Metal's pieces, and every tessellator but Apple's orders a patch's triangles its own way;
// RADV's own interpolation facts and its fused half conversion hold on any vendor.
// RADV's own interpolation facts hold on any vendor.
assert_eq!(
workarounds(&desc),
[
W::HalfConversionFusedWithArithmetic,
W::InterpolationNeedsTheWholeQuad,
W::PerspectiveReadsExtrapolated,
W::ClippedCoverageNotMetals,
@@ -1075,82 +1074,48 @@ fn only_nvidia_on_ampere_ga10x_carries_the_narrow_mask_defect() {
assert!(!carries(&desc));
}
/// `DriverWorkaround::HalfConversionPairFolded` is keyed on NVIDIA's driver whatever its GPU and on
/// nothing else: every committed NVIDIA profile carries it (the RTX 3090's generation and the RTX
/// 50 series alike) and no other committed profile does; the RTX 5080 laptop GPU's description
/// under Mesa's NVK does not. Where it is carried, a profile whose float controls would make the
/// conversion Metal's rounds an `f32` to `half` in another form (`narrow::quantize_form` is
/// `Converted`, not `Controlled`) and computes under those controls all the same
/// (`narrow::half_controls`).
/// A profile's `half` rounding follows its queries alone: every committed profile with
/// `shaderFloat16` and the 16-bit float controls (`narrow::half_controls`) rounds an `f32` to
/// `half` through the controlled conversion (`narrow::quantize_form` is `Controlled`), NVIDIA's
/// and RADV's included, and the RTX 5080 laptop GPU's and the Radeon 780M's descriptions round the
/// same way under another driver.
#[test]
fn nvidia_carries_the_folded_half_conversion_pair() {
use crate::device::profile::DriverWorkaround;
let defect = DriverWorkaround::HalfConversionPairFolded;
let carries = |desc: &DeviceDescription| {
Device::new(desc.clone(), DevicePolicy::default())
.unwrap()
.profile()
.fields()
.workarounds
.contains(&defect)
};
for (stem, text) in committed_profiles() {
let desc = DeviceDescription::from_khronos_json(&text, None).unwrap();
let nvidia = desc.driver_id == Some(vk::DriverId::NVIDIA_PROPRIETARY);
assert_eq!(carries(&desc), nvidia, "{stem}");
}
let mut desc = profile("nvidia-rtx5080-laptop");
let p = Device::new(desc.clone(), DevicePolicy::default())
.unwrap()
.profile()
.clone();
let half = p.fields().float_controls.f16;
assert!(half.rounding_rte && half.denorm_preserve && half.signed_zero_inf_nan_preserve);
assert_eq!(
crate::lower::arith::narrow::quantize_form(&p),
crate::spirv::builder::QuantizeForm::Converted
);
assert!(crate::lower::arith::narrow::half_controls(&p));
desc.device_id = 0x2204;
assert!(carries(&desc));
desc.driver_id = Some(vk::DriverId::MESA_NVK);
assert!(!carries(&desc));
}
/// `DriverWorkaround::HalfConversionFusedWithArithmetic` is keyed on RADV whatever its GPU and on
/// nothing else: every committed RADV profile carries it (the Radeon 780M, 680M and RX 7800 XT)
/// and no other committed profile does; the 780M's description under another driver does not.
/// Such a profile keeps the conversion under the float controls (`QuantizeForm::Controlled`).
#[test]
fn radv_carries_the_fused_half_conversion() {
use crate::device::profile::DriverWorkaround;
let defect = DriverWorkaround::HalfConversionFusedWithArithmetic;
fn half_rounding_follows_the_queries_alone() {
use crate::lower::arith::narrow::{half_controls, quantize_form};
use crate::spirv::builder::QuantizeForm;
let profile_of = |desc: &DeviceDescription| {
Device::new(desc.clone(), DevicePolicy::default())
.unwrap()
.profile()
.clone()
};
let mut radv = 0;
let mut controlled = Vec::new();
for (stem, text) in committed_profiles() {
let desc = DeviceDescription::from_khronos_json(&text, None).unwrap();
let on_radv = desc.driver_id == Some(vk::DriverId::MESA_RADV);
let p = profile_of(&desc);
assert_eq!(p.workarounds().contains(&defect), on_radv, "{stem}");
if on_radv {
radv += 1;
assert_eq!(
crate::lower::arith::narrow::quantize_form(&p),
crate::spirv::builder::QuantizeForm::Controlled,
"{stem}"
);
if half_controls(&p) {
assert_eq!(quantize_form(&p), QuantizeForm::Controlled, "{stem}");
controlled.push(stem);
}
}
assert!(radv >= 3, "{radv} RADV profiles");
let mut desc = profile("amd-780m-radv");
assert!(profile_of(&desc).workarounds().contains(&defect));
desc.driver_id = Some(vk::DriverId::AMD_OPEN_SOURCE);
assert!(!profile_of(&desc).workarounds().contains(&defect));
for (stem, other) in [
("nvidia-rtx5080-laptop", vk::DriverId::MESA_NVK),
("amd-780m-radv", vk::DriverId::AMD_OPEN_SOURCE),
] {
assert!(
controlled.iter().any(|s| s == stem),
"{stem}: {controlled:?}"
);
let mut desc = profile(stem);
desc.driver_id = Some(other);
let p = profile_of(&desc);
assert!(half_controls(&p), "{stem} under {other:?}");
assert_eq!(
quantize_form(&p),
QuantizeForm::Controlled,
"{stem} under {other:?}"
);
}
}
/// `DriverWorkaround::RegisterAllocatorOverflowsLargeModules`,
@@ -2306,13 +2306,12 @@ pub fn unorm8_tile_value(
/// from 65520 up: each rounding of Metal's blend arithmetic. Where the module rounds to `half` by
/// the device's conversion under the 16-bit float controls ([`QuantizeForm::Controlled`]: the
/// profile has `shaderFloat16`, `RoundingModeRTE`, `DenormPreserve` and `SignedZeroInfNanPreserve`
/// for 16 bits, and a driver that keeps the conversion and its widening, not one with
/// `DriverWorkaround::HalfConversionPairFolded`; [`narrow::quantize_form`]), that conversion
/// and its widening ([`narrow::round`]): two instructions, Metal's `half(float)` by the Vulkan spec
/// (conversions are correctly rounded, to nearest even under `RoundingModeRTE`, denormals kept
/// under `DenormPreserve`, zero signs and infinities under `SignedZeroInfNanPreserve`), as the
/// module's own `half` results round on such a profile (docs/FAST-PATHS.md's `half` rounding row:
/// exact under either policy, no note). Elsewhere the integer sequence ([`f32_to_half`]), about
/// for 16 bits; [`narrow::quantize_form`]), that conversion and its widening ([`narrow::round`]):
/// two instructions, Metal's `half(float)` by the Vulkan spec (conversions are correctly rounded,
/// to nearest even under `RoundingModeRTE`, denormals kept under `DenormPreserve`, zero signs and
/// infinities under `SignedZeroInfNanPreserve`), as the module's own `half` results round on such a
/// profile, and like them the device's rounding where its compiler folds the pair (NVIDIA's),
/// recorded as `PrecisionNote::NativeHalfConversion`. Elsewhere the integer sequence ([`f32_to_half`]), about
/// fifty instructions, the same on every device. The two agree on every `x` but a NaN's bits,
/// which the conversion leaves to the device: the blends clamp a NaN source to zero, and a 16-bit
/// float blend stores every NaN as Metal's own.
+2 -3
View File
@@ -2209,9 +2209,8 @@ enum F16Basis {
Measured,
/// The 16-bit float controls ([`narrow::half_controls`]), which its entry then declares
/// ([`narrow::computes_in_16_bits`]): no fact. Its `half` roundings take them too
/// ([`QuantizeForm::Controlled`]) but on a driver that folds the conversion's round trip
/// (`DriverWorkaround::HalfConversionPairFolded`), which leaves a 16-bit instruction's
/// rounding as it is.
/// ([`QuantizeForm::Controlled`]); a driver that folds the conversion's round trip (NVIDIA's)
/// leaves a 16-bit instruction's rounding as it is.
Controlled,
}
+17 -97
View File
@@ -7,12 +7,11 @@
//! Vulkan spec (`RoundingModeRTE`, `DenormPreserve` and `SignedZeroInfNanPreserve` for 16 bits, and
//! the modes the device's independence ties to them), it is that conversion and its widening, each
//! decorated `NoContraction`, in an entry declaring those modes ([`QuantizeForm::Controlled`],
//! [`controlled_modes`]), where the driver keeps the pair (not NVIDIA's,
//! `DriverWorkaround::HalfConversionPairFolded`, whose round trip is the device's conversion,
//! [`quantize_form`]): exact, with no fact and no note, but for the result of
//! `float` arithmetic on a driver that fuses the operation into the narrowing (RADV's,
//! `DriverWorkaround::HalfConversionFusedWithArithmetic`, [`rounds_arithmetic`]), which the module
//! records as `PrecisionNote::NativeHalfConversion`. Elsewhere, where the
//! [`controlled_modes`]): Metal's `half(float)` by the Vulkan spec, but a driver's compiler may
//! fold the pair into the value it started from (NVIDIA's) or fuse the `float` operation
//! computing the value into the narrowing and round its exact result once (RADV's), so every such
//! module records `PrecisionNote::NativeHalfConversion` on every device, a static note of the
//! rounding (`pipeline::compile`). Elsewhere, where the
//! profile has `shaderFloat16`, it is the device's conversion to 16 bits and its widening
//! ([`QuantizeForm::Converted`]), recording `PrecisionNote::NativeHalfConversion`; without it, the
//! device's `OpQuantizeToF16` alone ([`QuantizeForm::Device`]), whose result below the smallest
@@ -25,7 +24,7 @@
//! 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
//! declares ([`computes_in_16_bits`]), on a driver that folds the conversion's round trip too
//! declares ([`computes_in_16_bits`]), a driver that folds the conversion's round trip included
//! (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
//! demotion variables and thread arrays, and its `dot` and `mix`, 16-bit instructions
@@ -59,7 +58,7 @@
mod merges;
use crate::budget::Meter;
use crate::device::profile::{DriverWorkaround, Independence};
use crate::device::profile::Independence;
use crate::device::DeviceProfile;
use crate::error::Error;
use crate::lower::arith::legal::{FloatFmt, Form, Held};
@@ -142,14 +141,13 @@ pub fn round(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult<Value>
/// How profile `p`'s modules round an `f32` to `half` ([`QuantizeForm`]): the device's conversion
/// to 16 bits and back under the float controls that make it Metal's by the Vulkan spec where the
/// profile computes under them ([`half_controls`]) and its driver keeps the pair, not one that
/// folds it (`DriverWorkaround::HalfConversionPairFolded`, NVIDIA's) ([`QuantizeForm::Controlled`]),
/// else that conversion as it is where the profile has `shaderFloat16`
/// ([`QuantizeForm::Converted`]), else the device's `OpQuantizeToF16` ([`QuantizeForm::Device`]).
/// profile computes under them ([`half_controls`]) ([`QuantizeForm::Controlled`]), else that
/// conversion as it is where the profile has `shaderFloat16` ([`QuantizeForm::Converted`]), else the
/// device's `OpQuantizeToF16` ([`QuantizeForm::Device`]). Each is the device's own rounding, noted
/// (`pipeline::compile`).
pub fn quantize_form(p: &DeviceProfile) -> QuantizeForm {
let float16 = p.fields().leaf.float16;
let folds = (p.fields().workarounds).contains(&DriverWorkaround::HalfConversionPairFolded);
if half_controls(p) && !folds {
if half_controls(p) {
QuantizeForm::Controlled
} else if float16 {
QuantizeForm::Converted
@@ -161,8 +159,9 @@ pub fn quantize_form(p: &DeviceProfile) -> QuantizeForm {
/// The precision note of a module whose `half` roundings take `form`, the device's own rounding:
/// `NativeHalfConversion` for [`QuantizeForm::Converted`], `NativeHalfQuantize` for
/// [`QuantizeForm::Device`] (a quantize's result below the smallest normal half is the device's on
/// every profile, which no measurement covers). `None` for the float controls' conversion, Metal's
/// by the Vulkan spec.
/// every profile, which no measurement covers). `None` for the float controls' conversion, whose
/// note a module records where it keeps the conversion and its widening as a pair
/// ([`rounds_by_conversion`], `pipeline::compile`).
pub fn native_rounding(form: QuantizeForm) -> Option<PrecisionNote> {
match form {
QuantizeForm::Converted => Some(PrecisionNote::NativeHalfConversion),
@@ -237,9 +236,8 @@ fn controlled(fb: &mut FunctionBuilder<'_>, wide: Form, x: Value) -> BResult<Val
/// Vulkan spec, so a `half` `+ - *`, `/`, `sqrt` and fused multiply-add are the device's 16-bit
/// instructions (`super::f16_arithmetic`, `super::divide`, `super::math`, `super::fma`), the module
/// holds its `half` values at 16 bits (`spirv::half_hold`), and a widening from bits or a narrowing
/// to them records no note. Whether its `f32` results round through the conversion and its widening
/// too is [`quantize_form`]'s: not on a driver that folds that pair
/// (`DriverWorkaround::HalfConversionPairFolded`).
/// to them records no note. Its `f32` results round through the conversion and its widening under
/// them too ([`quantize_form`]).
pub fn half_controls(p: &DeviceProfile) -> bool {
p.fields().leaf.float16 && controlled_modes(p).is_some()
}
@@ -457,84 +455,6 @@ pub fn rounds_unmeasured(m: &TypedModule, meter: &mut Meter) -> Result<bool, Err
Ok(found)
}
/// Whether module `m` rounds to `half` the result of `float` arithmetic through a conversion pair
/// (an `OpFConvert` of an `f32` to 16 bits whose result another widens back, as
/// [`rounds_by_conversion`] finds them): an `f32` addition, subtraction, multiply or fused
/// multiply-add (`OpFAdd`, `OpFSub`, `OpFMul`, `OpFmaKHR` or `GLSL.std.450 Fma`) whose result the
/// pair narrows. A driver that fuses that operation into the narrowing
/// (`DriverWorkaround::HalfConversionFusedWithArithmetic`) rounds its exact result to `half` once,
/// where Metal rounds the `float` result: the neighbouring `half` where that result lies on a
/// `half` midpoint, within `PrecisionNote::NativeHalfConversion`'s bound, which the module then
/// records. One pass over the instructions to find each value's definition and two over the
/// conversions, with a word and a bit per value of the module charged to `meter` while they run.
pub fn rounds_arithmetic(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 arithmetic = |v: Value| {
matches!(
def.get(v.index()).copied().flatten(),
Some(
Inst::Binary {
op: BinOp::FAdd | BinOp::FSub | BinOp::FMul,
..
} | Inst::Fma { .. }
| Inst::Glsl {
op: GlslOp::Fma,
..
}
)
)
};
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) && arithmetic(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 {
+11 -13
View File
@@ -1919,20 +1919,18 @@ pub enum PrecisionNote {
/// Native half rounding (a conversion): the module rounds a `half` result it computes in
/// `float` (a `half` operation's, a function's, a conversion from `float`'s, a texel's) by
/// the device's conversion of the `float` to 16 bits and its widening (`OpFConvert` of the
/// value itself), on a device with `shaderFloat16` whose float controls do not make that
/// value itself), on every device with `shaderFloat16`. Where its float controls make that
/// conversion Metal's (`RoundingModeRTE`, `DenormPreserve` and `SignedZeroInfNanPreserve` for
/// 16 bits, under which ANV and RADV round through the conversion exactly and record no
/// note): NVIDIA, whose driver folds the conversion's round trip even under those controls
/// (`DriverWorkaround::HalfConversionPairFolded`), MoltenVK, lavapipe, and any device
/// without them. NVIDIA's modules compute under those controls all the same: a `half` `+`,
/// `-`, `*`, `/` and `sqrt` there are the device's 16-bit instructions, whose results take
/// no such rounding. Without them Vulkan leaves the conversion's rounding mode and its 16-bit
/// denormals to the device. Also recorded under those controls on RADV where the `half` is the
/// result of an `f32` addition, subtraction, multiply or fused multiply-add: its compiler fuses
/// the operation into the conversion and rounds the exact result once
/// (`DriverWorkaround::HalfConversionFusedWithArithmetic`), one unit in the last place from
/// Metal's `half` of the `float` result where that result lies on a `half` midpoint. The
/// recorded
/// 16 bits) the module declares them and decorates the pair `NoContraction`, and still records
/// this note, a static note of the rounding on every device: a driver's compiler may fold the
/// pair into the value it started from (NVIDIA's, under those controls too) or fuse the `f32`
/// addition, subtraction, multiply or fused multiply-add computing the value into the
/// narrowing and round its exact result once (RADV's), one unit in the last place from Metal's
/// `half` of the `float` result where that result lies on a `half` midpoint; ANV's answered
/// every `f32` exactly. Under those controls a `half` `+`, `-`, `*`, `/` and `sqrt` are the
/// device's 16-bit instructions, whose results take no such rounding. Without them Vulkan
/// leaves the conversion's rounding mode and its 16-bit denormals to the device (MoltenVK,
/// lavapipe, and any device without them). The recorded
/// bound, against Metal's `half(float)` (to nearest even on the half grid, half denormals kept,
/// infinity from 65520 up, `0x7E00` for a NaN):
/// - a finite result within one unit in the last place of the `half`: NVIDIA's 615.71.09
+11 -17
View File
@@ -3044,14 +3044,13 @@ fn compile_bounded<K>(
&& quantize == crate::spirv::builder::QuantizeForm::Converted
&& p.takes_driver_deviation(crate::error::DriverDeviation::MetalHalfArithmetic);
let native_widening = widens && !controls && !measured_widening;
// A `half` rounded from `float` arithmetic through the conversion under the float controls,
// on a driver that fuses the operation into the narrowing
// (`DriverWorkaround::HalfConversionFusedWithArithmetic`): its exact result rounded once,
// where Metal rounds the `float` result; the module records the native note.
let fused = quantize == crate::spirv::builder::QuantizeForm::Controlled
&& p.workarounds()
.contains(&crate::device::profile::DriverWorkaround::HalfConversionFusedWithArithmetic)
&& crate::lower::arith::narrow::rounds_arithmetic(&module, m)?;
// 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 (NVIDIA's) or fuse the `float` operation computing the value into the narrowing
// and round its exact result once (RADV's), so the module records the native note on every
// device, a static note of the rounding.
let controlled_pair = quantize == crate::spirv::builder::QuantizeForm::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
@@ -3067,15 +3066,10 @@ fn compile_bounded<K>(
// `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
// widening, which they make exact but for a NaN's bits: the entry declares them, and so
// requires the device's float-controls properties for them, and no fact. On a driver that
// folds the round trip (`DriverWorkaround::HalfConversionPairFolded`, so `Converted`) the
// pair's rounding is the device's whatever the entry declares, recorded below, and the rest
// is Metal's under them as elsewhere.
// requires the device's float-controls properties for them, and no fact. The pair's rounding
// is noted below all the same.
let declares_controls = controls
&& (widens
|| crate::lower::arith::narrow::computes_in_16_bits(&module)
|| (quantize == crate::spirv::builder::QuantizeForm::Controlled
&& crate::lower::arith::narrow::rounds_by_conversion(&module, m)?));
&& (widens || crate::lower::arith::narrow::computes_in_16_bits(&module) || controlled_pair);
if declares_controls {
let modes = crate::lower::arith::narrow::controlled_modes(p).unwrap_or_default();
module.declare_modes(&modes)?;
@@ -3090,7 +3084,7 @@ fn compile_bounded<K>(
),
(device_quantize, PrecisionNote::NativeHalfQuantize),
(
(converts && !measured_conversion) || native_widening || fused,
(converts && !measured_conversion) || native_widening || controlled_pair,
PrecisionNote::NativeHalfConversion,
),
];
+3 -4
View File
@@ -1025,10 +1025,9 @@ fn rebuild(
}
/// Hold `m`'s `half` values at 16 bits (the module docs), where it computes `half` in 16 bits;
/// the caller asks only under the 16-bit float controls (`narrow::half_controls`), whatever the
/// module's rounding form: on a driver that folds the conversion's round trip
/// (`DriverWorkaround::HalfConversionPairFolded`) a narrowing a held value reads at 16 bits is no
/// round trip. What no
/// the caller asks only under the 16-bit float controls (`narrow::half_controls`): a narrowing a
/// held value reads at 16 bits is no round trip, so a driver that folds the conversion's round
/// trip (NVIDIA's) keeps its rounding. What no
/// instruction reads afterwards leaves the module, and its interface and requirements are derived
/// again.
pub fn hold(m: &mut TypedModule, meter: &mut Meter) -> Result<Held, Error> {
@@ -11,9 +11,9 @@
//! 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 on a driver that fuses `float`
//! arithmetic into the conversion `NativeHalfConversion` where the module rounds such a result
//! (`narrow::rounds_arithmetic`), which the test sets aside, and a module's widening of a
//! note (`narrow::native_rounding`), and under the float controls `NativeHalfConversion` where the
//! module rounds through the conversion and its widening as a pair, on every device
//! (`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
@@ -24,7 +24,7 @@
use crate::air::intrinsics::{AirIntrinsic, Elem, Math, NumTy, Operand};
use crate::air::ir::{BinOp, FastMath};
use crate::device::profile::{DriverWorkaround, FloatFunctions, NanEncoding};
use crate::device::profile::{FloatFunctions, NanEncoding};
use crate::device::requirements::VkProperty;
use crate::device::DeviceProfile;
use crate::error::DriverDeviation;
@@ -373,13 +373,12 @@ fn exported_float_notes_are_the_ones_a_compile_records() {
}
let (_, m) = typed_module(&bitcode, &k.name, p)
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
// The module's rounding of `float` arithmetic, fused into the conversion.
let fused = form == crate::spirv::builder::QuantizeForm::Controlled
&& (p.workarounds())
.contains(&DriverWorkaround::HalfConversionFusedWithArithmetic)
&& narrow::rounds_arithmetic(&m, &mut meter())
// The module's rounding through the conversion and its widening under the
// float controls, noted on every device.
let paired = form == crate::spirv::builder::QuantizeForm::Controlled
&& narrow::rounds_by_conversion(&m, &mut meter())
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
if fused && !want.contains(&PrecisionNote::NativeHalfConversion) {
if paired && !want.contains(&PrecisionNote::NativeHalfConversion) {
got.remove(&PrecisionNote::NativeHalfConversion);
}
let crosses = narrow::widens_bits(&m, &mut meter())
@@ -1,17 +1,17 @@
//! Native half rounding: a `half` result the module computes in `float` rounds through the device's
//! conversion and its widening under the float controls that make it Metal's
//! (`QuantizeForm::Controlled`), else through that conversion as it is where the profile has
//! `shaderFloat16` (`QuantizeForm::Converted`), recording `PrecisionNote::NativeHalfConversion`,
//! else through the device's quantize alone (`QuantizeForm::Device`), recording
//! `NativeHalfQuantize` on every such profile. A `half` read from memory is the device's widening
//! on every profile: its conversion where the module holds 16-bit floats, `UnpackHalf2x16`
//! elsewhere.
//! `shaderFloat16` (`QuantizeForm::Converted`), each pair recording
//! `PrecisionNote::NativeHalfConversion` on every device, else through the device's quantize alone
//! (`QuantizeForm::Device`), recording `NativeHalfQuantize` on every such profile. A `half` read
//! from memory is the device's widening on every profile: its conversion where the module holds
//! 16-bit floats, `UnpackHalf2x16` elsewhere.
//!
//! The kernels read two `float`s from buffer 0 and store one result after them: a `half` sum of
//! the two narrowed, and the first narrowed alone; and, under the float controls, a `float` sum,
//! product and fused multiply-add of the two rounded to `half`, which a driver may fuse into the
//! narrowing (`DriverWorkaround::HalfConversionFusedWithArithmetic`). `llvm-as` assembles the
//! module; without it the compiling tests skip visibly.
//! product and fused multiply-add of the two rounded to `half`, which a driver's compiler may fuse
//! into the narrowing. `llvm-as` assembles the module; without it the compiling tests skip
//! visibly.
use crate::air::{self, SpecRequest};
use crate::device::requirements::VkProperty;
@@ -173,14 +173,11 @@ fn interpret_bytes(bitcode: &[u8], entry: &str, p: &DeviceProfile, bytes: Vec<u8
}
/// The form a profile's `half` roundings take: the controlled conversion where the profile has
/// `shaderFloat16` and its float controls and its driver keeps the round trip (not NVIDIA's,
/// `DriverWorkaround::HalfConversionPairFolded`), else the conversion with `shaderFloat16`, else
/// the quantize.
/// `shaderFloat16` and its float controls, else the conversion with `shaderFloat16`, else the
/// quantize.
fn expected(p: &DeviceProfile) -> QuantizeForm {
let float16 = p.fields().leaf.float16;
let folds = (p.workarounds())
.contains(&crate::device::profile::DriverWorkaround::HalfConversionPairFolded);
if float16 && controlled_modes(p).is_some() && !folds {
if float16 && controlled_modes(p).is_some() {
QuantizeForm::Controlled
} else if float16 {
QuantizeForm::Converted
@@ -189,8 +186,9 @@ fn expected(p: &DeviceProfile) -> QuantizeForm {
}
}
/// Every committed profile rounds by the device's own form: the controlled conversion with no
/// note, the conversion noted `NativeHalfConversion`, and the quantize noted `NativeHalfQuantize`.
/// Every committed profile rounds by the device's own form: the controlled conversion, whose note a
/// module keeping its pair records (`pipeline::compile`), the conversion noted
/// `NativeHalfConversion`, and the quantize noted `NativeHalfQuantize`.
#[test]
fn half_rounding_is_the_devices_on_every_profile() {
let profiles = committed_profiles().expect("profiles");
@@ -223,8 +221,10 @@ fn half_rounding_is_the_devices_on_every_profile() {
/// measured fact, and MoltenVK on the M3 Max's identity, whose conversion of a `float` the function
/// holds is measured to be Metal's (`DriverDeviation::MetalHalfConversion`), records nothing and
/// requires `VkProperty::MetalHalfConversion`; on a profile without `shaderFloat16` it quantizes
/// and records `NativeHalfQuantize`; RADV takes the controlled conversion, with no fact and no
/// note. Each passes L3. On the interpreter,
/// and records `NativeHalfQuantize`; RADV takes the controlled conversion, with no fact, and
/// records `NativeHalfConversion` on the narrowing alone, which keeps the conversion and its
/// widening as a pair (its sum computes on 16-bit floats from the narrowings, with no pair). Each
/// passes L3. On the interpreter,
/// 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]
@@ -236,20 +236,22 @@ fn native_half_rounding_records_its_kind_and_requires_no_fact() {
PrecisionNote::NativeHalfConversion,
PrecisionNote::NativeHalfQuantize,
];
// Each profile, its note, and whether it requires the measured conversion.
let cases: [(&str, Option<PrecisionNote>, bool); 4] = [
("lavapipe", Some(natives[0]), false),
("swiftshader", Some(natives[1]), false),
("moltenvk-m3", None, true),
("amd-780m-radv", None, false),
// Each profile, its note, whether only a kernel keeping the pair records it, and whether it
// requires the measured conversion.
let cases: [(&str, Option<PrecisionNote>, bool, bool); 4] = [
("lavapipe", Some(natives[0]), false, false),
("swiftshader", Some(natives[1]), false, false),
("moltenvk-m3", None, false, true),
("amd-780m-radv", Some(natives[0]), true, false),
];
for (stem, note, measured) in cases {
for (stem, note, pair_only, measured) in cases {
let p = profile(stem, DevicePolicy::default()).expect("profile");
for (name, _) in &KERNELS {
let what = format!("{name} on {stem}");
let a = compile(&bc, name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}"));
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();
let note = note.filter(|_| !pair_only || *name == "half_narrow");
assert_eq!(noted, note.iter().collect::<Vec<_>>(), "{what}");
assert_eq!(
a.requirements
@@ -416,9 +418,9 @@ fn decodes(m: &TypedModule) -> (usize, usize) {
/// A `half` read from memory is the device's widening of its bits on every profile, inside a loop
/// and out, with no integer decode: on lavapipe (the device's conversion, no float controls) the
/// module records `NativeNanEncoding` and `NativeHalfConversion` (a NaN's bits and, 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,
/// requiring no fact; on MoltenVK, whose widening the measured
/// device flushes 16-bit denormals, a denormal); on NVIDIA, under the float controls
/// (`narrow::half_controls`), `NativeNanEncoding` alone, requiring no fact; on MoltenVK, whose
/// widening the measured
/// `MetalHalfArithmetic` reads as Metal's, it records `NativeNanEncoding` alone and requires that
/// fact; on the floor (no `shaderFloat16`) it is `UnpackHalf2x16` of each word, recording both
/// notes and requiring no fact. A `half4` widens as one vector (two words unpacked and shuffled
@@ -728,9 +730,8 @@ fn rounding(words: &[u32]) -> Rounding {
}
/// Where the profile has `shaderFloat16` and the float controls that make a conversion to 16 bits
/// Metal's `half(float)` by the Vulkan spec (every ANV and RADV profile), and its driver does not
/// fold the round trip (`DriverWorkaround::HalfConversionPairFolded`, NVIDIA's), each kernel
/// rounds its `half` through that conversion and its widening, every one decorated
/// Metal's `half(float)` by the Vulkan spec (every ANV, RADV and RTX 50 series profile), each
/// kernel rounds its `half` through that conversion and its widening, every one decorated
/// `NoContraction`, with no quantize, and computes its `half` sum on the device's 16-bit
/// arithmetic, which reads the roundings' 16-bit results themselves and is widened once, exactly
/// and undecorated (`spirv::half_hold`); its entry
@@ -738,10 +739,12 @@ fn rounding(words: &[u32]) -> Rounding {
/// modes the device's independence ties to them (`RoundingModeRTE` for 32 and 64 bits on ANV,
/// whose rounding modes are not independent; `RoundingModeRTE` and `DenormPreserve` for 64 bits on
/// RADV, independent for 32 bits only); the module requires those float-controls properties and no
/// measured fact, records no native note, and passes L3. On the interpreter (whose conversion
/// rounds to nearest even) it answers Metal's `half(float)`: a tie to even, the largest half below
/// 65520 and infinity from it, a half denormal, a zero's sign, and a sum. MoltenVK, lavapipe, the
/// floor and NVIDIA's profiles keep their forms.
/// measured fact, records `NativeHalfConversion` where it keeps the conversion and its widening as
/// a pair (the narrowing alone: a driver's compiler may fold that pair, NVIDIA's does) and no other
/// native note, and passes L3. On the interpreter (whose conversion rounds to nearest even) it
/// answers Metal's `half(float)`: a tie to even, the largest half below 65520 and infinity from it,
/// a half denormal, a zero's sign, and a sum. MoltenVK, lavapipe, the floor and Pascal keep their
/// forms.
#[test]
fn a_controlled_conversion_rounds_half_where_the_float_controls_allow() {
use crate::device::requirements::{FloatControl, FloatWidth};
@@ -826,12 +829,17 @@ fn a_controlled_conversion_rounds_half_where_the_float_controls_allow() {
"{what}: {kind:?} {width:?}"
);
}
for note in [
PrecisionNote::NativeHalfConversion,
PrecisionNote::NativeHalfQuantize,
] {
assert!(!a.precision.contains(&note), "{what}: {note:?}");
}
assert_eq!(
a.precision.contains(&PrecisionNote::NativeHalfConversion),
!sum,
"{what}: {:?}",
a.precision
);
assert!(
!a.precision.contains(&PrecisionNote::NativeHalfQuantize),
"{what}: {:?}",
a.precision
);
}
let run = |name: &str, x: [f32; 2]| interpret(&bc, name, p, x);
let tie = 1.0 + 2f32.powi(-11);
@@ -849,7 +857,12 @@ fn a_controlled_conversion_rounds_half_where_the_float_controls_allow() {
assert_eq!(run("half_sum", [1.0, 2f32.powi(-11)]), 1.0, "{stem}: a sum");
assert_eq!(run("half_sum", [1.5, 2.25]), 3.75, "{stem}: an exact sum");
}
for stem in ["intel-irisxe-rplp-anv", "amd-780m-radv"] {
for stem in [
"intel-irisxe-rplp-anv",
"amd-780m-radv",
"nvidia-rtx50-linux",
"nvidia-rtx5080-laptop",
] {
assert!(
controlled.iter().any(|s| s == stem),
"{stem}: {controlled:?}"
@@ -860,8 +873,6 @@ fn a_controlled_conversion_rounds_half_where_the_float_controls_allow() {
"lavapipe",
"vk12-floor",
"nvidia-pascal-linux",
"nvidia-rtx50-linux",
"nvidia-rtx5080-laptop",
] {
assert!(
!controlled.iter().any(|s| s == stem),
@@ -891,17 +902,18 @@ const NATIVE: [(&str, &str); 4] = [
),
];
/// NVIDIA's driver folds the conversion's round trip (`DriverWorkaround::HalfConversionPairFolded`)
/// but reports every 16-bit float control, so its `half` arithmetic is the device's 16-bit
/// instructions under them: on the committed RTX 50 series profiles (`nvidia-rtx50-linux`,
/// `nvidia-rtx5080-laptop`) and on the RTX 5080 Laptop GPU's description given an RTX 2080's
/// (`0x1E87`) and an RTX 3090's (`0x2204`) device ID (the workaround is the driver's, whatever the
/// GPU), a `half` sum, product and product plus a sum compute on 16-bit floats, one `OpFAdd` or
/// `OpFMul` an operation, between the narrowings of the loaded `float`s, which feed them directly
/// (no round trip, so no `NativeHalfConversion`); the entry declares `RoundingModeRTE`,
/// `DenormPreserve` and `SignedZeroInfNanPreserve` for 16 bits and requires their properties.
/// A `half` narrowed and widened back alone is the round trip, the device's conversion
/// (`QuantizeForm::Converted`), recorded. Each passes L3. On the interpreter each operation rounds
/// NVIDIA's driver reports every 16-bit float control, so its `half` arithmetic is the device's
/// 16-bit instructions under them and its roundings the controlled conversion
/// (`QuantizeForm::Controlled`), as on any device with them: on the committed RTX 50 series
/// profiles (`nvidia-rtx50-linux`, `nvidia-rtx5080-laptop`) and on the RTX 5080 Laptop GPU's
/// description given an RTX 2080's (`0x1E87`) and an RTX 3090's (`0x2204`) device ID (no device
/// identity enters), a `half` sum, product and product plus a sum compute on 16-bit floats, one
/// `OpFAdd` or `OpFMul` an operation, between the narrowings of the loaded `float`s, which feed
/// them directly (no round trip, so no `NativeHalfConversion`). A `half` narrowed and widened back
/// alone is the conversion's pair, which NVIDIA's compiler folds, recorded `NativeHalfConversion`
/// as on every device. Every entry declares `RoundingModeRTE`, `DenormPreserve` and
/// `SignedZeroInfNanPreserve` for 16 bits and requires their properties, and passes L3. On the
/// interpreter each operation rounds
/// to `half`: `(1 + 2^-10)^2` is `1 + 2^-9`, and that plus `1 + 2^-10` the tie `2 + 3·2^-10`,
/// rounded to the even `2 + 2^-8` (the `float` computation, unrounded, is `2 + 3·2^-10 + 2^-20`).
/// The negative control: the RTX 2080's description without `shaderRoundingModeRTEFloat16`
@@ -909,7 +921,6 @@ const NATIVE: [(&str, &str); 4] = [
/// kernel, as does Pascal's profile, without `shaderFloat16`.
#[test]
fn nvidia_computes_half_on_16_bit_floats_under_the_float_controls() {
use crate::device::profile::DriverWorkaround;
use crate::device::requirements::{FloatControl, FloatWidth};
use crate::device::{Device, DeviceDescription};
use crate::lower::arith::narrow::half_controls;
@@ -940,13 +951,8 @@ fn nvidia_computes_half_on_16_bit_floats_under_the_float_controls() {
];
let one = 1.0 + 2f32.powi(-10);
for (stem, p) in &nvidia {
assert!(
p.workarounds()
.contains(&DriverWorkaround::HalfConversionPairFolded),
"{stem}"
);
assert!(half_controls(p), "{stem}");
assert_eq!(quantize_form(p), QuantizeForm::Converted, "{stem}");
assert_eq!(quantize_form(p), QuantizeForm::Controlled, "{stem}");
for (name, _) in &NATIVE {
let what = format!("{name} on {stem}");
let a = compile(&bc, name, p).unwrap_or_else(|e| panic!("{what}: {e:?}"));
@@ -961,9 +967,6 @@ fn nvidia_computes_half_on_16_bit_floats_under_the_float_controls() {
assert_eq!(r.quantizes, 0, "{what}: {r:?}");
let conversion = a.precision.contains(&PrecisionNote::NativeHalfConversion);
assert_eq!(conversion, ops == 0, "{what}: {:?}", a.precision);
if ops == 0 {
continue;
}
for mode in [
M::RoundingModeRTE,
M::DenormPreserve,
@@ -1024,46 +1027,39 @@ fn nvidia_computes_half_on_16_bit_floats_under_the_float_controls() {
}
/// Under the float controls (`QuantizeForm::Controlled`), a `half` rounded from `float` arithmetic
/// (a sum, a product, a fused multiply-add) records `NativeHalfConversion` where the driver fuses
/// the operation into the narrowing (`DriverWorkaround::HalfConversionFusedWithArithmetic`, every
/// RADV profile) and not elsewhere (ANV); a loaded `float` narrowed alone records it on neither
/// (`narrow::rounds_arithmetic`). Each passes L3.
/// (a sum, a product, a fused multiply-add) and a loaded `float` narrowed alone each round through
/// the conversion and its widening, and record `NativeHalfConversion` on every profile, whatever
/// its driver (a driver's compiler may fuse the operation into the narrowing, RADV's does, or fold
/// the pair, NVIDIA's does): ANV, RADV and NVIDIA alike. Each passes L3.
#[test]
fn a_controlled_rounding_of_arithmetic_is_noted_where_the_driver_fuses_it() {
use crate::device::profile::DriverWorkaround;
fn a_controlled_rounding_is_noted_on_every_device() {
let Some(bc) = assemble("native-half-arithmetic", &module_of(&ARITHMETIC)) else {
return;
};
let mut seen = (0, 0);
let mut seen = Vec::new();
for (stem, p) in &committed_profiles().expect("profiles") {
if quantize_form(p) != QuantizeForm::Controlled {
continue;
}
let fuses = p
.workarounds()
.contains(&DriverWorkaround::HalfConversionFusedWithArithmetic);
if fuses {
seen.0 += 1;
} else {
seen.1 += 1;
}
seen.push(stem.clone());
for (name, _) in &ARITHMETIC {
let what = format!("{name} on {stem}");
let a = compile(&bc, name, p).unwrap_or_else(|e| panic!("{what}: {e:?}"));
link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let noted = a.precision.contains(&PrecisionNote::NativeHalfConversion);
assert_eq!(
noted,
fuses && *name != "float_narrow",
assert!(
a.precision.contains(&PrecisionNote::NativeHalfConversion),
"{what}: {:?}",
a.precision
);
}
}
assert!(
seen.0 > 0 && seen.1 > 0,
"fusing and other controlled profiles: {seen:?}"
);
for stem in [
"intel-irisxe-rplp-anv",
"amd-780m-radv",
"nvidia-rtx50-linux",
] {
assert!(seen.iter().any(|s| s == stem), "{stem}: {seen:?}");
}
}
/// A kernel that reads a `half` from buffer 0 and stores it widened to `float` after the two
@@ -1083,10 +1079,9 @@ fn half_load_module() -> String {
/// every committed profile, with no integer decode, and records `NativeNanEncoding` (a NaN's bits
/// the device's) and selects no canonical NaN. With `shaderFloat16` the widening is the device's
/// conversion (a 16-bit storage unit it reads is read as a 16-bit float itself): under the float
/// controls (ANV, RADV) its entry declares them (`narrow::controlled_modes`, so a half denormal
/// widens exactly) and it records no other note, and so on NVIDIA, which rounds by the device's
/// conversion (`QuantizeForm::Converted`, its driver folding the round trip) but computes under
/// those controls (`narrow::half_controls`); where the measured `MetalHalfArithmetic` reads
/// controls (ANV, RADV, NVIDIA) its entry declares them (`narrow::controlled_modes`, so a half
/// denormal widens exactly) and it records no other note; where the measured `MetalHalfArithmetic`
/// reads
/// every `half` through that widening as Metal's (MoltenVK) it requires the fact; elsewhere
/// (lavapipe: the device's conversion, no float controls) it records
/// `NativeHalfConversion`, whose bound holds a denormal the device flushes; where the device's
@@ -1143,18 +1138,11 @@ fn a_half_read_from_memory_is_the_devices_widening_on_every_profile() {
QuantizeForm::Converted => {
assert_eq!((r.widenings, r.unpacks), (1, 0), "{what}: {r:?}");
assert_eq!((nan, moved), (!moves, moves), "{what}: {:?}", a.precision);
let controls = crate::lower::arith::narrow::half_controls(p);
assert_eq!(
conversion,
!measured && !controls,
"{what}: {:?}",
a.precision
);
assert_eq!(conversion, !measured, "{what}: {:?}", a.precision);
assert_eq!(fact, measured, "{what}: {:?}", a.requirements.properties);
for mode in [M::RoundingModeRTE, M::DenormPreserve] {
assert_eq!(
r.modes.contains(&(mode as u32, 16)),
controls,
assert!(
!r.modes.contains(&(mode as u32, 16)),
"{what}: {mode:?} {r:?}"
);
}
@@ -14436,8 +14436,6 @@ variant metal2vulkan::device::DriverWorkaround::EarlyTestsDropMultisampledImageW
variant metal2vulkan::device::DriverWorkaround::ExternalUniformReadsSkipACache ExternalUniformReadsSkipACache
variant metal2vulkan::device::DriverWorkaround::FloatDenormalsKeptUnderHalfControls FloatDenormalsKeptUnderHalfControls
variant metal2vulkan::device::DriverWorkaround::FunctionsInlinedAtEveryCall FunctionsInlinedAtEveryCall
variant metal2vulkan::device::DriverWorkaround::HalfConversionFusedWithArithmetic HalfConversionFusedWithArithmetic
variant metal2vulkan::device::DriverWorkaround::HalfConversionPairFolded HalfConversionPairFolded
variant metal2vulkan::device::DriverWorkaround::InterpolationNeedsTheWholeQuad InterpolationNeedsTheWholeQuad
variant metal2vulkan::device::DriverWorkaround::LoadsForwardedIntoLoops LoadsForwardedIntoLoops
variant metal2vulkan::device::DriverWorkaround::LocalizedLoadsForwardedPastAtomicsAndCalls LocalizedLoadsForwardedPastAtomicsAndCalls
Can't render this file because it is too large.
+10 -12
View File
@@ -5229,18 +5229,16 @@ bound.
- `metal2vulkan-degrade-native-half-conversion` (precision). `PrecisionNote::NativeHalfConversion`:
Native half rounding (a conversion): the module rounds a `half` result it computes in `float` (a
`half` operation's, a function's, a conversion from `float`'s, a texel's) by the device's
conversion of the `float` to 16 bits and its widening, on a device with `shaderFloat16` whose
float controls do not make that conversion Metal's `half(float)` (`RoundingModeRTE`,
`DenormPreserve` and `SignedZeroInfNanPreserve` for 16 bits: ANV and RADV round through the
conversion under them, exactly, with no note): NVIDIA, whose driver folds the conversion's round
trip even under those controls (`DriverWorkaround::HalfConversionPairFolded`), MoltenVK,
lavapipe, and any device without them. NVIDIA's pipelines compute under those controls all the
same: a `half` `+`, `-`, `*`, `/` and `sqrt` there are the device's 16-bit instructions, whose
results take no such rounding. Also recorded under those controls on RADV where the
`half` is the result of a `float` addition, subtraction, multiply or fused multiply-add: its
compiler fuses the operation into the conversion and rounds the exact result once
(`DriverWorkaround::HalfConversionFusedWithArithmetic`), one `half` ulp from Metal's where the
`float` result lies on a `half` midpoint. Also recorded where a `half` read from its bits is the
conversion of the `float` to 16 bits and its widening, on every device with `shaderFloat16`.
Under the float controls that make that conversion Metal's `half(float)` by the Vulkan spec
(`RoundingModeRTE`, `DenormPreserve` and `SignedZeroInfNanPreserve` for 16 bits, which the entry
then declares) the pair is decorated `NoContraction`, and the note is recorded all the same, on
every device: a driver's compiler may still fold the pair into the value it started from
(NVIDIA's does, leaving the value unrounded) or fuse a `float` addition, subtraction, multiply or
fused multiply-add into the narrowing and round the exact result once (RADV's does, one `half`
ulp from Metal's where the `float` result lies on a `half` midpoint). Under those controls a
`half` `+`, `-`, `*`, `/` and `sqrt` are the device's 16-bit instructions, whose results take no
such rounding. Also recorded where a `half` read from its bits is the
device's widening, or a `half` encoded to its bits (where they are not the bits it was read from)
is the device's narrowing, and that conversion is neither under those controls nor measured to be
Metal's: the conversion on lavapipe, and `GLSL.std.450 UnpackHalf2x16` and
+11 -14
View File
@@ -41,20 +41,17 @@ walks the flow in the order a consumer meets it:
Every `air.simd_*` operation keeps Metal's 32-lane simdgroup; there is no option to use the
driver's subgroup width instead.
A `half` computed in `float` rounds through the device's conversion to 16 bits and back, Metal's
`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
(`DriverWorkaround::HalfConversionPairFolded`), so it takes the native conversion for that
rounding; 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 multiply-add into the conversion of its
result and rounds the exact result once (`DriverWorkaround::HalfConversionFusedWithArithmetic`), so
a pipeline that rounds such a result to `half` there records `NativeHalfConversion`.
A `half` computed in `float` rounds through the device's conversion to 16 bits and back, 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. Where the device has the 16-bit float
controls (ANV, RADV, NVIDIA) the entry declares them, which make the pair Metal's `half(float)` by
the Vulkan spec, and computes a `half` `+`, `-`, `*`, `/` and `sqrt` with the device's 16-bit
instructions; the pair's rounding is still noted on every device, as a driver's compiler may fold
the pair (NVIDIA's 615.71.09 does) or fuse a `float` addition, subtraction, multiply or fused
multiply-add into the narrowing and round the exact result once (RADV's does).
A `half` read from memory or from its bits is the device's widening on every device (an
`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