diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index ca6fd3d20..ca19e5109 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -393,6 +393,15 @@ on disk; the `VkPipelineCache` still serves the device's own pipelines. 128-iteration loop of one 16-byte device read fully. On an RX 7900 XTX, with neighbouring threads 976 bytes apart in a 64 KiB table, that loop took 207 to 209 µs unrolled against 105 to 113 µs rolled; over 16 KiB and 256 KiB tables the unrolled loop was 7 to 17% faster. +- A `half` `fma` on a device that computes `half` in 16 bits under the 16-bit float controls + (`shaderFloat16`, with 16-bit `RoundingModeRTE`, `DenormPreserve` and + `SignedZeroInfNanPreserve`) is the device's 16-bit `Fma` (`PrecisionNote::NativeFma`). Vulkan + gives `Fma` the precision of a multiply followed by an add, each rounded, where Metal's rounds + once. RADV (Mesa 26.2.6) on an RX 7900 XTX does not round it once: over a chain of 1,024 + dependent `half` `fma`s, 1,622,016 lanes ended up to 9 `half` ulp from Metal's. NVIDIA's driver + on an RTX 3090 and Intel's Windows driver on a UHD 630 matched Metal in every lane of the same + chains. Elsewhere a `half` `fma` is the device's `float` `Fma` on the operands, rounded to + `half`, within one `half` ulp. ## One path for every device diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index c10eb9173..4c1f971c4 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -121,6 +121,11 @@ impl DeviceProfile { self.facts.push_window } + /// Which `half` fused multiply-adds take the device's 16-bit `Fma`. + pub(crate) fn half_fma(&self) -> HalfFma { + self.facts.half_fma + } + /// The profile's fields: internal; the profile is opaque to consumers, who compare /// [`DeviceProfile::fingerprint`] and read its facts through the accessors. pub(crate) fn fields(&self) -> &ProfileFields { @@ -557,6 +562,8 @@ pub(crate) struct ProfileFacts { pub(crate) half_outputs: HalfOutputs, /// How many bytes of push constants a kernel's push window holds. pub(crate) push_window: PushWindow, + /// Which `half` fused multiply-adds take the device's 16-bit `Fma`. + pub(crate) half_fma: HalfFma, } impl ProfileFacts { @@ -568,6 +575,7 @@ impl ProfileFacts { narrow_wrap: NarrowWrap::Every, half_outputs: HalfOutputs::Sixteen, push_window: PushWindow::Guaranteed, + half_fma: HalfFma::Measured, }; /// `Device::from_queries`': each fact the same on every device. @@ -578,6 +586,7 @@ impl ProfileFacts { narrow_wrap: NarrowWrap::Read, half_outputs: HalfOutputs::Widened, push_window: PushWindow::Floor, + half_fma: HalfFma::Native, }; } @@ -606,6 +615,21 @@ pub(crate) enum PushWindow { Floor, } +/// Which `half` fused multiply-adds take the device's 16-bit `Fma` (`lower::arith::fma::half_route`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum HalfFma { + /// Those on a driver measured to compute it as Metal's `half` `fma` + /// (`DriverDeviation::MetalHalfFma`), with no note; elsewhere `OpFmaKHR` on 16 bits where the + /// profile has `shaderFmaFloat16` and computes `half` under the 16-bit float controls, else the + /// device's `float` `Fma` rounded to `half`, noted `NativeFma`: `Device::new`'s profile. + Measured, + /// Every one where the profile computes `half` under the 16-bit float controls (it has + /// `shaderFloat16`, and the controls that make a 16-bit conversion Metal's), noted `NativeFma` + /// as the device's `Fma` is on every route; elsewhere the device's `float` `Fma` rounded to + /// `half`, noted the same. `Device::from_queries`' profile, keyed on no identity. + Native, +} + /// How a `half` color output (a scalar or vector of AIR's `half`) reaches the device /// (`lower::stage_io`'s `half_variable`, `StageIo::half_outputs`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] diff --git a/crates/metal2vulkan/src/device/tests/profile.rs b/crates/metal2vulkan/src/device/tests/profile.rs index ddb5e81f4..2ad7c89ee 100644 --- a/crates/metal2vulkan/src/device/tests/profile.rs +++ b/crates/metal2vulkan/src/device/tests/profile.rs @@ -1225,21 +1225,23 @@ fn large_module_defects_are_keyed_on_anv() { } } -/// The stage bound, two notes, the narrow wrap and the push window are facts of the profile, on -/// every committed profile: `Device::new` bounds a stage only where its driver's identity names a stage-size defect -/// (`StageBound::Defects`), notes the controlled `half` pair only where its driver fuses arithmetic -/// into the narrowing (`HalfPairNote::Fused`), records implementation-defined reconvergence as -/// the stage's field alone (`ReconvergenceNote::Field`) and masks every narrow result -/// (`NarrowWrap::Every`) and pushes 128 bytes to a kernel (`PushWindow::Guaranteed`); -/// `Device::from_queries` bounds every stage, notes every pair, notes the reconvergence, masks -/// only the narrow results a use reads and pushes 256 bytes (`Every`, `Every`, `Noted`, `Read`, -/// `Floor`). The facts key the fingerprint: a profile of the same fields with another fact is -/// another profile. +/// The stage bound, two notes, the narrow wrap, the push window and the `half` fused multiply-add +/// are facts of the profile, on every committed profile: `Device::new` bounds a stage only where +/// its driver's identity names a stage-size defect (`StageBound::Defects`), notes the controlled +/// `half` pair only where its driver fuses arithmetic into the narrowing (`HalfPairNote::Fused`), +/// records implementation-defined reconvergence as the stage's field alone +/// (`ReconvergenceNote::Field`), masks every narrow result (`NarrowWrap::Every`), pushes 128 bytes +/// to a kernel (`PushWindow::Guaranteed`) and takes the 16-bit `Fma` only where its driver is +/// measured (`HalfFma::Measured`); `Device::from_queries` bounds every stage, notes every pair, +/// notes the reconvergence, masks only the narrow results a use reads, pushes 256 bytes and takes +/// the 16-bit `Fma` under the 16-bit float controls (`Every`, `Every`, `Noted`, `Read`, `Floor`, +/// `Native`). The facts key the fingerprint: a profile of the same fields with another fact is +/// another profile, the `half` fused multiply-add's included. #[test] fn the_profiles_facts_follow_its_constructor() { use crate::device::profile::{ - DeviceProfile, HalfPairNote, NarrowWrap, ProfileFacts, PushWindow, ReconvergenceNote, - StageBound, + DeviceProfile, HalfFma, HalfPairNote, NarrowWrap, ProfileFacts, PushWindow, + ReconvergenceNote, StageBound, }; for (stem, text) in committed_profiles() { let desc = DeviceDescription::from_khronos_json(&text, None).unwrap(); @@ -1266,17 +1268,26 @@ fn the_profiles_facts_follow_its_constructor() { (PushWindow::Guaranteed, PushWindow::Floor), "{stem}" ); + let fmas = (old.profile().half_fma(), queries.profile().half_fma()); + assert_eq!(fmas, (HalfFma::Measured, HalfFma::Native), "{stem}"); let fields = queries.profile().fields().clone(); - let facts = ProfileFacts { - stage_bound: StageBound::Defects, - ..ProfileFacts::EVERY - }; - let other = DeviceProfile::of(fields, facts); - assert_ne!( - other.fingerprint(), - queries.profile().fingerprint(), - "{stem}" - ); + for facts in [ + ProfileFacts { + stage_bound: StageBound::Defects, + ..ProfileFacts::EVERY + }, + ProfileFacts { + half_fma: HalfFma::Measured, + ..ProfileFacts::EVERY + }, + ] { + let other = DeviceProfile::of(fields.clone(), facts); + assert_ne!( + other.fingerprint(), + queries.profile().fingerprint(), + "{stem}" + ); + } } } diff --git a/crates/metal2vulkan/src/lower/arith/fma.rs b/crates/metal2vulkan/src/lower/arith/fma.rs index 1f8929106..c2df28a5a 100644 --- a/crates/metal2vulkan/src/lower/arith/fma.rs +++ b/crates/metal2vulkan/src/lower/arith/fma.rs @@ -27,9 +27,21 @@ //! the device's, as the controlled rounding's are. Every other `half` one takes [`Route::Native`]: the device's `float` `Fma` //! of the operands held in `float`, whose product is exact there, rounded to `half`. //! +//! Those three are `Device::new`'s (`HalfFma::Measured`). On a profile `Device::from_queries` +//! built (`HalfFma::Native`), which reads no driver identity, a `half` one takes +//! [`Route::F16Native`] where the profile computes `half` under the 16-bit float controls +//! ([`narrow::half_controls`]): the device's `Fma` on 16-bit floats between the same exact +//! conversions, which the module's 16-bit holding then removes (`spirv::half_hold`), so the +//! operands and the result stay 16-bit floats. Its precision is Vulkan's for `Fma`, inherited from +//! an `OpFMul` followed by an `OpFAdd`, each correctly rounded to `half` under the controls' +//! `RoundingModeRTE`, where Metal's rounds once: noted `PrecisionNote::NativeFma`, as +//! [`Route::Native`] is. `OpFmaKHR` is not taken there: `shaderFmaFloat16` is not a query that may +//! choose a second form. Every other `half` one on that profile takes [`Route::Native`]. +//! //! An extended-range blend computes its own correctly rounded multiply-adds ([`half_sum`], //! [`float_fma_exact`]): the blend the device cannot do, in plain arithmetic. +use crate::device::profile::HalfFma; use crate::device::DeviceProfile; use crate::error::DriverDeviation; use crate::lower::arith::legal::{FloatFmt, Form, Held}; @@ -51,6 +63,10 @@ pub enum Route { /// A `half` fused multiply-add by `OpFmaKHR` on 16-bit floats under the 16-bit float /// controls, correctly rounded by the Vulkan spec ([`half_route`]). F16Khr, + /// A `half` fused multiply-add by the device's `Fma` on 16-bit floats under the 16-bit float + /// controls, on `Device::from_queries`' profile: within Vulkan's precision rather than rounded + /// once (`PrecisionNote::NativeFma`) ([`half_route`]). + F16Native, /// The device's `GLSL.std.450 Fma` on the `float` lanes (a `half`'s held in `float`, its /// result rounded to `half`), within Vulkan's precision rather than rounded once /// (`PrecisionNote::NativeFma`). @@ -72,6 +88,8 @@ pub const F16: &str = "arith.fma.f16"; /// See [`KHR`]. pub const F16_KHR: &str = "arith.fma.f16.khr"; /// See [`KHR`]. +pub const F16_NATIVE: &str = "arith.fma.f16.native"; +/// See [`KHR`]. pub const NATIVE: &str = "arith.fma.native"; /// The `float` route profile `p` offers: `OpFmaKHR` where `shaderFmaFloat32` is enabled, else the @@ -84,18 +102,24 @@ pub fn float_route(p: &DeviceProfile) -> Route { } } -/// The `half` route profile `p` offers: [`Route::F16`] where the driver is measured to compute a -/// 16-bit `Fma` as Metal's own `half` `fma` (`DriverDeviation::MetalHalfFma`) and `shaderFloat16` -/// is enabled, else [`Route::F16Khr`] where `shaderFmaFloat16` is and the profile computes under -/// the 16-bit float controls (`narrow::half_controls`), else the device's `float` `Fma` -/// rounded to `half` ([`Route::Native`]). +/// The `half` route profile `p` offers. On `Device::new`'s profile (`HalfFma::Measured`): +/// [`Route::F16`] where the driver is measured to compute a 16-bit `Fma` as Metal's own `half` +/// `fma` (`DriverDeviation::MetalHalfFma`) and `shaderFloat16` is enabled, else [`Route::F16Khr`] +/// where `shaderFmaFloat16` is and the profile computes under the 16-bit float controls +/// (`narrow::half_controls`). On `Device::from_queries`' (`HalfFma::Native`): [`Route::F16Native`] +/// where the profile computes under those controls. Elsewhere the device's `float` `Fma` rounded +/// to `half` ([`Route::Native`]). pub fn half_route(p: &DeviceProfile) -> Route { - if p.takes_driver_deviation(DriverDeviation::MetalHalfFma) && p.fields().leaf.float16 { - Route::F16 - } else if p.fields().leaf.fma16 && narrow::half_controls(p) { - Route::F16Khr - } else { - Route::Native + let leaf = &p.fields().leaf; + match p.half_fma() { + HalfFma::Measured + if p.takes_driver_deviation(DriverDeviation::MetalHalfFma) && leaf.float16 => + { + Route::F16 + } + HalfFma::Measured if leaf.fma16 && narrow::half_controls(p) => Route::F16Khr, + HalfFma::Native if narrow::half_controls(p) => Route::F16Native, + HalfFma::Measured | HalfFma::Native => Route::Native, } } @@ -141,16 +165,18 @@ impl Fma { Route::Khr => KHR, Route::F16 => F16, Route::F16Khr => F16_KHR, + Route::F16Native => F16_NATIVE, Route::Native => NATIVE, } } - /// An upper estimate of the SPIR-V words per use: the instruction; on [`Route::F16`] and - /// [`Route::F16Khr`] the three conversions, the instruction and the widening. + /// An upper estimate of the SPIR-V words per use: the instruction; on [`Route::F16`], + /// [`Route::F16Khr`] and [`Route::F16Native`] the three conversions, the instruction and the + /// widening. pub fn words(self) -> u32 { match self.route { Route::Khr => 16, - Route::F16 | Route::F16Khr => 32, + Route::F16 | Route::F16Khr | Route::F16Native => 32, // The instruction, and a `half` result's rounding. Route::Native => 64, } @@ -164,7 +190,9 @@ pub fn emit(fb: &mut FunctionBuilder<'_>, fma: Fma, args: &[Value]) -> BResult fb.fma(a, b, c), - (Route::F16, Some(FloatFmt::Half)) => f16(fb, fma.form.lanes, [a, b, c], false), + (Route::F16 | Route::F16Native, Some(FloatFmt::Half)) => { + f16(fb, fma.form.lanes, [a, b, c], false) + } (Route::F16Khr, Some(FloatFmt::Half)) => f16(fb, fma.form.lanes, [a, b, c], true), // The device's `Fma`; on `half` operands held in `float` the product is exact, so only // the sum's rounding and the rounding to `half` differ from Metal's one rounding. @@ -178,11 +206,12 @@ pub fn emit(fb: &mut FunctionBuilder<'_>, fma: Fma, args: &[Value]) -> BResult, lanes: u8, diff --git a/crates/metal2vulkan/src/lower/arith/mod.rs b/crates/metal2vulkan/src/lower/arith/mod.rs index 83ae45aec..0445fcad8 100644 --- a/crates/metal2vulkan/src/lower/arith/mod.rs +++ b/crates/metal2vulkan/src/lower/arith/mod.rs @@ -715,8 +715,8 @@ pub struct ArithPlan { /// (`FloatFunctions::Metal`): the mode Metal compiles this entry in ([`libm::module_mode`], /// decided by [`finish`]). `None` on any other profile. pub metal_functions: Option, - /// Whether a selected fused multiply-add takes the device's `Fma` ([`fma::Route::Native`]), - /// whose note [`finish`] records. + /// Whether a selected fused multiply-add takes the device's `Fma` ([`fma::Route::Native`], or + /// [`fma::Route::F16Native`] on 16-bit floats), whose note [`finish`] records. pub native_fma: bool, /// How the module emits a multiply the device must round on its own, decided by [`finish`] from /// the same fact as [`ArithPlan::metal_functions`]: a device whose `float` functions are @@ -808,11 +808,12 @@ impl ArithPlan { self.extended_range = true; } - /// Record fused multiply-add `fma`, selected: the device's 16-bit `Fma` - /// ([`ArithPlan::f16_fma`]), or the device's `Fma` ([`ArithPlan::native_fma`]). + /// Record fused multiply-add `fma`, selected: the device's 16-bit `Fma` measured to be Metal's + /// ([`ArithPlan::f16_fma`]), or the device's `Fma`, on `float` or on 16-bit floats + /// ([`ArithPlan::native_fma`]). pub fn take_fma(&mut self, fma: fma::Fma) { self.f16_fma |= fma.route == fma::Route::F16; - self.native_fma |= fma.route == fma::Route::Native; + self.native_fma |= matches!(fma.route, fma::Route::Native | fma::Route::F16Native); } } @@ -2414,11 +2415,14 @@ fn function_notes( } /// The note of fused multiply-add `fma`: `NativeFma` where it takes the device's `Fma` -/// ([`fma::Route::Native`]), which [`finish`] records for every such route a family takes. +/// ([`fma::Route::Native`], [`fma::Route::F16Native`]), which [`finish`] records for every such +/// route a family takes. fn native_fma(fma: fma::Fma) -> OpNotes { match fma.route { - fma::Route::Native => OpNotes::everywhere(BTreeSet::from([PrecisionNote::NativeFma])), - _ => OpNotes::default(), + fma::Route::Native | fma::Route::F16Native => { + OpNotes::everywhere(BTreeSet::from([PrecisionNote::NativeFma])) + } + fma::Route::Khr | fma::Route::F16 | fma::Route::F16Khr => OpNotes::default(), } } diff --git a/crates/metal2vulkan/src/lower/arith/tests/fused.rs b/crates/metal2vulkan/src/lower/arith/tests/fused.rs index dfb803e70..f8fbf2ec6 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/fused.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/fused.rs @@ -480,14 +480,15 @@ fn half_triples() -> Vec<[u64; 3]> { out } -/// A `half` fused multiply-add on 16-bit floats, by the device's `Fma` ([`Route::F16`]) or by -/// `OpFmaKHR` ([`Route::F16Khr`]), rounds once on the interpreter: the operands convert to 16 bits -/// exactly and the result widens exactly. The device's `float` `Fma` rounded to `half` +/// A `half` fused multiply-add on 16-bit floats, by the device's `Fma` ([`Route::F16`], +/// [`Route::F16Native`]) or by `OpFmaKHR` ([`Route::F16Khr`]), rounds once on the interpreter, +/// whose `Fma` rounds once (a device's on [`Route::F16Native`] may not, noted): the operands +/// convert to 16 bits exactly and the result widens exactly. The device's `float` `Fma` rounded to `half` /// ([`Route::Native`]) rounds the sum twice, so it is within one `half` unit in the last place. #[test] fn half_fused_multiply_add_rounds_on_its_route() { let triples = half_triples(); - for route in [Route::F16, Route::F16Khr] { + for route in [Route::F16, Route::F16Khr, Route::F16Native] { for lanes in [1u8, 2] { let fma = Fma { form: vec(float(16), lanes), diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 24a931a90..bec910f78 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -1845,11 +1845,13 @@ pub enum PrecisionNote { /// `half` one where the device's 16-bit `Fma` is not measured to be Metal's and the device has /// no 16-bit `OpFmaKHR` under the 16-bit float controls, is the device's `GLSL.std.450 Fma` /// (on the `half` operands held in `float`, its result rounded to `half`), where Metal's rounds - /// once. **Recorded bound:** a `half` result within one unit in its last place of + /// once. On a device `Device::from_queries` made that computes `half` in 16 bits under the + /// 16-bit float controls, a `half` one is the device's 16-bit `Fma` on the `half` operands. + /// **Recorded bound:** a `half` result held in `float` within one unit in its last place of /// Metal's (the product of two `half` values is exact in `float`, so only the two roundings - /// differ); a `float` one within half a unit in the last place of the product plus half a - /// unit in the last place of the result (Vulkan lets `Fma` round the product and then the - /// sum). Validation derives no tolerance from it. + /// differ); a `float` one, and a 16-bit one, within half a unit in the last place of the + /// product plus half a unit in the last place of the result, in its own format (Vulkan lets + /// `Fma` round the product and then the sum). Validation derives no tolerance from it. NativeFma, /// Native device sampling (a texel conversion): the module hands a read, sample or gather /// with a `float` result the device's own conversion of the texel's codes, off Apple's GPUs diff --git a/crates/metal2vulkan/src/tests/engine_arith.rs b/crates/metal2vulkan/src/tests/engine_arith.rs index 0079fb62e..34b7a9b95 100644 --- a/crates/metal2vulkan/src/tests/engine_arith.rs +++ b/crates/metal2vulkan/src/tests/engine_arith.rs @@ -18,6 +18,7 @@ use crate::air::{self, SpecRequest}; use crate::device::profile::{DeviceProfile, DriverWorkaround, FloatFunctions}; use crate::device::requirements::VkFeature; +use crate::device::requirements::VkProperty; use crate::device::{Device, DeviceDescription, DevicePolicy}; use crate::error::{Capability, Error, Feature, LowerFamily, Needs}; use crate::library::FunctionConstantValues; @@ -29,7 +30,8 @@ use crate::pipeline::artifact::PrecisionNote; use crate::pipeline::compile::{plan_bitcode, EntryRef}; use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage}; use crate::pipeline::testing::{ - compile, exact_maths, link_and_validate, llvm_assemble, meter, profile, AssembleError, Scratch, + compile, description, exact_maths, link_and_validate, llvm_assemble, meter, profile, + AssembleError, Scratch, }; use crate::spirv::interp::{run, Buffer, Config, Resources}; @@ -1347,29 +1349,8 @@ fn fused_multiply_adds_take_the_profiles_route() { needs: &[], note: None, }; - // 0x400a * 0x0bec + 0xbc9f: the exact sum rounds to 0xbc9f, the float sum to a half - // midpoint that rounds away. - let half_kernel = Kernel { - name: "fma_half_rounds_once", - body: format!( - "{}{}{} %h = bitcast i16 %t to half\n %g = bitcast i16 %s to half\n %u = bitcast i16 %v to half\n %x = call half @air.fma.f16(half %h, half %g, half %u)\n %r = fpext half %x to float\n", - on("t", 16, 0x400A), - on("s", 16, 0x0BEC), - on("v", 16, 0xBC9F) - ), - float: true, - want: Some((-1183.0f32 / 1024.0).to_bits()), - needs: &[], - note: None, - }; - let ks = [float_kernel, half_kernel]; - let text = module(&ks).replace( - DECLS, - &format!( - "{DECLS}declare float @air.fma.f32(float, float, float)\ndeclare <2 x float> @air.fma.v2f32(<2 x float>, <2 x float>, <2 x float>)\ndeclare half @air.fma.f16(half, half, half)\n" - ), - ); - let Some(bitcode) = assemble("fma-routes", &text) else { + let ks = [float_kernel, half_fma_kernel()]; + let Some(bitcode) = assemble("fma-routes", &fma_module(&ks)) else { return; }; // (profile, OpFmaKHR of the float kernel, whether the routes are the device's `Fma`). @@ -1419,6 +1400,134 @@ fn fused_multiply_adds_take_the_profiles_route() { } } +/// The `half` fused multiply-add of `0x400a`, `0x0bec` and `0xbc9f`, read from their bits, stored +/// widened: the exact sum rounds to `0xbc9f` (`-1183 / 1024`), the `float` sum to a `half` +/// midpoint that rounds away (`-1182 / 1024`). +fn half_fma_kernel() -> Kernel { + Kernel { + name: "fma_half_rounds_once", + body: format!( + "{}{}{} %h = bitcast i16 %t to half\n %g = bitcast i16 %s to half\n %u = bitcast i16 %v to half\n %x = call half @air.fma.f16(half %h, half %g, half %u)\n %r = fpext half %x to float\n", + on("t", 16, 0x400A), + on("s", 16, 0x0BEC), + on("v", 16, 0xBC9F) + ), + float: true, + want: Some((-1183.0f32 / 1024.0).to_bits()), + needs: &[], + note: None, + } +} + +/// The generated module with every kernel of `ks` and the fused multiply-adds they call. +fn fma_module(ks: &[Kernel]) -> String { + module(ks).replace( + DECLS, + &format!( + "{DECLS}declare float @air.fma.f32(float, float, float)\ndeclare <2 x float> @air.fma.v2f32(<2 x float>, <2 x float>, <2 x float>)\ndeclare half @air.fma.f16(half, half, half)\n" + ), + ) +} + +/// The `GLSL.std.450 Fma`s of module `words` whose result is a 16-bit float or a vector of them, +/// and its `NoContraction` decorations. +fn fma16_and_marks(words: &[u32]) -> (usize, usize) { + const GLSL_FMA: u32 = 50; + const NO_CONTRACTION: u32 = 42; + let (mut half, mut fmas, mut marks) = (std::collections::BTreeSet::new(), 0, 0); + let mut i = 5; + while i < words.len() { + let (len, opcode) = ((words[i] >> 16) as usize, words[i] & 0xFFFF); + assert!(len > 0 && i + len <= words.len(), "malformed module"); + let op = |o: crate::spv::Op| opcode == o as u32; + let float16 = op(crate::spv::Op::TypeFloat) && words[i + 2] == 16; + if float16 || (op(crate::spv::Op::TypeVector) && half.contains(&words[i + 2])) { + half.insert(words[i + 1]); + } else if op(crate::spv::Op::ExtInst) && words[i + 4] == GLSL_FMA { + fmas += usize::from(half.contains(&words[i + 1])); + } else if op(crate::spv::Op::Decorate) && words[i + 2] == NO_CONTRACTION { + marks += 1; + } + i += len; + } + (fmas, marks) +} + +/// 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 +/// `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. The same +/// captures through `Device::new` keep their routes ([`fused_multiply_adds_take_the_profiles_route`], +/// `lower::arith::tests::fused`). +#[test] +fn a_half_fused_multiply_add_is_the_devices_16_bit_fma_on_from_queries() { + use crate::lower::arith::fma::{half_route, Route}; + use crate::lower::arith::narrow::half_controls; + let ks = [half_fma_kernel()]; + let Some(bitcode) = assemble("fma-from-queries", &fma_module(&ks)) else { + return; + }; + let mut sixteen = Vec::new(); + for stem in [ + "amd-rdna3-radv", + "intel-irisxe-anv", + "nvidia-rtx50-linux", + "lavapipe", + "vk12-floor", + ] { + let what = format!("fma_half_rounds_once on {stem} (from_queries)"); + let desc = description(stem).expect("description"); + let device = + Device::from_queries(desc, exact_maths()).unwrap_or_else(|e| panic!("{what}: {e}")); + let p = device.profile(); + let controls = half_controls(p); + let route = if controls { + Route::F16Native + } else { + Route::Native + }; + assert_eq!(half_route(p), route, "{what}"); + let a = compile(&bitcode, "fma_half_rounds_once", p) + .unwrap_or_else(|e| panic!("{what}: {e:?}")); + let (_, words) = link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); + assert!( + a.precision.contains(&PrecisionNote::NativeFma), + "{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"); + sixteen.push(stem); + } else { + assert_eq!(fmas, 0, "{what}: 16-bit Fma"); + } + assert_eq!( + count_op(&words, crate::spv::Op::FmaKHR), + 0, + "{what}: OpFmaKHR" + ); + let got = interpret(&bitcode, "fma_half_rounds_once", p); + let want = if controls { -1183.0f32 } else { -1182.0f32 } / 1024.0; + assert_eq!(got, want.to_bits(), "{what}: {got:#x}"); + } + assert_eq!( + sixteen, + ["amd-rdna3-radv", "intel-irisxe-anv", "nvidia-rtx50-linux"], + "the profiles under the 16-bit float controls" + ); +} + /// `` `%name` of opaque lanes `vals` (each `fadd , -0.0`, a `half` lane truncated /// from its exact `float`). fn opaque_vector(name: &str, half: bool, vals: &[f32]) -> String { diff --git a/docs/API.md b/docs/API.md index e3b2c6a3e..cbaf5e47f 100644 --- a/docs/API.md +++ b/docs/API.md @@ -5219,7 +5219,11 @@ bound. `float` fused multiply-add on a device without `OpFmaKHR`, or a `half` one where the device's 16-bit `Fma` is not measured to be Metal's and the device has no 16-bit `OpFmaKHR` under the 16-bit float controls, is the device's `GLSL.std.450 Fma` (on the `half` operands held in - `float`, its result rounded to `half`), where Metal's rounds once. + `float`, its result rounded to `half`), where Metal's rounds once. On a device + `Device::from_queries` made that computes `half` in 16 bits under the 16-bit float controls, a + `half` one is the device's 16-bit `Fma` on the `half` operands. Recorded bound: a `half` result + held in `float` within one `half` ulp of Metal's; a `float` one, and a 16-bit one, within half an + ulp of the product plus half an ulp of the result, in its own format. - `metal2vulkan-degrade-device-texel-conversion` (precision). `PrecisionNote::DeviceTexelConversion`: Native device sampling (a texel conversion): the module hands a read, sample or gather with a `float` result the device's own conversion of the texel's