diff --git a/crates/metal2vulkan-validation/src/runtime_lane/half_conversions.rs b/crates/metal2vulkan-validation/src/runtime_lane/half_conversions.rs index 8445c24ec..183b958b9 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/half_conversions.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/half_conversions.rs @@ -13,9 +13,12 @@ //! The module rounds each `half` through the device's conversion of the `float` to 16 bits. Where //! 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`. Elsewhere a -//! kernel that rounds through the conversion records the note, and its lanes are the device's, -//! which the test prints as `HALF-CONVERSIONS` lines. +//! 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 +//! the device's lanes, which the test prints as `HALF-CONVERSIONS` lines. use super::degrade_notices::on_device; use super::driver_deviations::stage_notes; diff --git a/crates/metal2vulkan/src/device/derive.rs b/crates/metal2vulkan/src/device/derive.rs index 066550176..b5180f00e 100644 --- a/crates/metal2vulkan/src/device/derive.rs +++ b/crates/metal2vulkan/src/device/derive.rs @@ -407,6 +407,9 @@ fn by_identity(desc: &DeviceDescription) -> Vec { } found } + // 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, on every GPU it // drives. Some(vk::DriverId::INTEL_OPEN_SOURCE_MESA) => { diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index 2bbc9df8b..0366a7965 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -1247,6 +1247,21 @@ pub enum DriverWorkaround { /// on every GPU, the others unmeasured. Such a profile rounds a `half` in another form /// (`lower::arith::narrow::controlled_modes`). 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 on the Radeon 780M (RADV PHOENIX): ACO + /// compiled the product's `OpFMul` and the narrowing as one `v_fma_mixlo_f16`, and the + /// product of 2.6822087e-7 and 1.0000001 answered `0x0005` where Metal's `half` of the + /// `float` product is `0x0004` (`runtime_lane::half_conversions`); a sum's narrowing was one + /// `v_fma_mixlo_f16` too. Keyed on RADV (`VK_DRIVER_ID_MESA_RADV`) on every GPU, the others + /// 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 diff --git a/crates/metal2vulkan/src/device/tests/profile.rs b/crates/metal2vulkan/src/device/tests/profile.rs index c9f14b089..f52b79a2d 100644 --- a/crates/metal2vulkan/src/device/tests/profile.rs +++ b/crates/metal2vulkan/src/device/tests/profile.rs @@ -1065,6 +1065,42 @@ fn nvidia_carries_the_folded_half_conversion_pair() { 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; + let profile_of = |desc: &DeviceDescription| { + Device::new(desc.clone(), DevicePolicy::default()) + .unwrap() + .profile() + .clone() + }; + let mut radv = 0; + 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}" + ); + } + } + 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)); +} + /// `DriverWorkaround::RegisterAllocatorOverflowsLargeModules` is keyed on ANV, whatever its GPU /// and release; every committed ANV profile carries it, and no other profile does. The UHD 770's /// description under RADV or NVIDIA's driver loses it. diff --git a/crates/metal2vulkan/src/lower/arith/narrow.rs b/crates/metal2vulkan/src/lower/arith/narrow.rs index 130fee2f9..800f97607 100644 --- a/crates/metal2vulkan/src/lower/arith/narrow.rs +++ b/crates/metal2vulkan/src/lower/arith/narrow.rs @@ -8,7 +8,10 @@ //! 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`]): exact on every such device whose driver keeps the pair (not NVIDIA's, -//! `DriverWorkaround::HalfConversionPairFolded`), with no fact and no note. Elsewhere, where the +//! `DriverWorkaround::HalfConversionPairFolded`), 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 //! 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 @@ -438,6 +441,84 @@ pub fn rounds_unmeasured(m: &TypedModule, meter: &mut Meter) -> Result Result { + let width = |v: Value| -> Option { + 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> = 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 { diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 64bc162db..dda9ea144 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -1841,7 +1841,12 @@ pub enum PrecisionNote { /// note): NVIDIA, whose driver folds the conversion's round trip even under those controls /// (`DriverWorkaround::HalfConversionPairFolded`), MoltenVK, lavapipe, and any device /// without them. Without them Vulkan leaves the conversion's rounding mode and its 16-bit - /// denormals to the device. The recorded + /// 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 /// 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 diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 91d92dc91..3b97fb5eb 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -2792,6 +2792,14 @@ fn compile_kept( && p.takes_driver_deviation(crate::error::DriverDeviation::MetalHalfArithmetic); let native_widening = widens && quantize != crate::spirv::builder::QuantizeForm::Controlled && !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)?; // 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 @@ -2826,7 +2834,7 @@ fn compile_kept( ), (device_quantize, PrecisionNote::NativeHalfQuantize), ( - (converts && !measured_conversion) || native_widening, + (converts && !measured_conversion) || native_widening || fused, PrecisionNote::NativeHalfConversion, ), ]; diff --git a/crates/metal2vulkan/src/tests/engine_native_half.rs b/crates/metal2vulkan/src/tests/engine_native_half.rs index be983a095..f23510ff5 100644 --- a/crates/metal2vulkan/src/tests/engine_native_half.rs +++ b/crates/metal2vulkan/src/tests/engine_native_half.rs @@ -8,8 +8,10 @@ //! 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. `llvm-as` assembles the module; without it the -//! compiling tests skip visibly. +//! 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. use crate::air::{self, SpecRequest}; use crate::device::requirements::VkProperty; @@ -47,23 +49,51 @@ const KERNELS: [(&str, &str); 2] = [ ), ]; +/// Kernels that round `float` arithmetic to `half`: the sum and the product of the two `float`s, and +/// their fused multiply-add (the second added to the product of the two), each narrowed and widened +/// back, and the first narrowed alone. +const ARITHMETIC: [(&str, &str); 4] = [ + ( + "float_sum", + " %s = fadd float %a, %b\n %h = fptrunc float %s to half\n %r = fpext half %h to float\n", + ), + ( + "float_product", + " %s = fmul float %a, %b\n %h = fptrunc float %s to half\n %r = fpext half %h to float\n", + ), + ( + "float_fma", + " %s = call float @air.fma.f32(float %a, float %b, float %b)\n %h = fptrunc float %s to half\n %r = fpext half %h to float\n", + ), + ( + "float_narrow", + " %h = fptrunc float %a to half\n %r = fpext half %h to float\n", + ), +]; + /// The module of every kernel. fn module() -> String { + module_of(&KERNELS) +} + +/// The module of `kernels`. +fn module_of(kernels: &[(&str, &str)]) -> String { let mut s = String::from( "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n", ); - for (name, body) in &KERNELS { + for (name, body) in kernels { s.push_str(&format!( "define void @{name}(ptr addrspace(1) noundef \"air-buffer-no-alias\" %0) {{\nentry:\n %p1 = getelementptr inbounds float, ptr addrspace(1) %0, i64 1\n %p2 = getelementptr inbounds float, ptr addrspace(1) %0, i64 2\n %a = load float, ptr addrspace(1) %0, align 4\n %b = load float, ptr addrspace(1) %p1, align 4\n{body} store float %r, ptr addrspace(1) %p2, align 4\n ret void\n}}\n\n" )); } - let refs: Vec = (0..KERNELS.len()).map(|i| format!("!{}", 20 + i)).collect(); + let refs: Vec = (0..kernels.len()).map(|i| format!("!{}", 20 + i)).collect(); + s.push_str("declare float @air.fma.f32(float, float, float)\n\n"); s.push_str(&format!( "!llvm.module.flags = !{{!0}}\n!air.kernel = !{{{}}}\n!air.version = !{{!17}}\n!air.language_version = !{{!18}}\n\n", refs.join(", ") )); s.push_str("!0 = !{i32 7, !\"air.max_device_buffers\", i32 31}\n!10 = !{}\n!11 = !{!12}\n!12 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"float\", !\"air.arg_name\", !\"io\"}\n!17 = !{i32 2, i32 8, i32 0}\n!18 = !{!\"Metal\", i32 4, i32 0, i32 0}\n"); - for (i, (name, _)) in KERNELS.iter().enumerate() { + for (i, (name, _)) in kernels.iter().enumerate() { s.push_str(&format!("!{} = !{{ptr @{name}, !10, !11}}\n", 20 + i)); } s @@ -822,6 +852,49 @@ fn a_controlled_conversion_rounds_half_where_the_float_controls_allow() { } } +/// 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. +#[test] +fn a_controlled_rounding_of_arithmetic_is_noted_where_the_driver_fuses_it() { + use crate::device::profile::DriverWorkaround; + let Some(bc) = assemble("native-half-arithmetic", &module_of(&ARITHMETIC)) else { + return; + }; + let mut seen = (0, 0); + 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; + } + 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", + "{what}: {:?}", + a.precision + ); + } + } + assert!( + seen.0 > 0 && seen.1 > 0, + "fusing and other controlled profiles: {seen:?}" + ); +} + /// A kernel that reads a `half` from buffer 0 and stores it widened to `float` after the two /// `float`s the other kernels read (bytes 8 to 12), and the `half` itself after that (bytes 12 to /// 14). diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index a7ea69d59..7b680f476 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -13093,6 +13093,7 @@ variant metal2vulkan::device::DriverWorkaround::DiscardDropsSimdgroupStores Disc variant metal2vulkan::device::DriverWorkaround::DontInlineKeepsCalls DontInlineKeepsCalls variant metal2vulkan::device::DriverWorkaround::EarlyTestsDropMultisampledImageWrites EarlyTestsDropMultisampledImageWrites 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 diff --git a/docs/API.md b/docs/API.md index ff1f8be45..f37f52d9c 100644 --- a/docs/API.md +++ b/docs/API.md @@ -4101,7 +4101,11 @@ bound. `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. Also recorded where a `half` read from its bits is the + lavapipe, and any device without them. 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 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 NVIDIA and lavapipe, and `GLSL.std.450 UnpackHalf2x16` and diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 2e7e724b2..65f69c9a0 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -49,7 +49,10 @@ pipeline records `NativeHalfConversion` or `NativeHalfQuantize`; not `NativeHalf 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. +(`DriverWorkaround::HalfConversionPairFolded`), so it takes the native conversion. 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` 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