From e393b10cb73bbf5ff048ac5e32d952652ce09235 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 11 Nov 2026 13:36:20 -0800 Subject: [PATCH] Half + - * on the device's 16-bit arithmetic take the AIR's own contraction A half fadd, fsub or fmul on the device's 16-bit arithmetic (ArithStrategy::F16: MoltenVK, measured, and the float-controls profiles) was always kept apart: a sum or difference decorated NoContraction and a product as Fma(a, b, -0.0) decorated NoContraction, whatever the AIR's flags allowed. That holds Metal's exact half bits at the cost of every fusion the flags allow (AGENTS.md rule 1: the device's native arithmetic). It now decides as float does (contraction()): an operation whose flags carry both contract and reassoc is undecorated, its product a plain OpFMul, and the device's compiler groups and fuses it; any other keeps today's form. Notes mirror float's: note_rewrites already records FastMathRewrites where a neighbour can be rewritten. On MoltenVK, Metal's fast compile folds an undecorated 16-bit operation's conversions away and answers the float result unrounded (the MetalHalfArithmetic measurement), so there a fast operation records FastMathRewrites, whose doc (and docs/API.md's catalogue entry and the FAST-PATHS device-gap row) now says so, and requires no MetalHalfArithmetic, which the kept form still requires. On an owned proxy (hnq_half_layer_composite) on the Iris Xe, the step-1 prototype of this form cut the SIMD8 cycle estimate from 58584 to 33092. Tests: f16_binary's rounded-result and one-instruction tests under both contractions; half_arithmetic_on_the_device_takes_the_airs_contraction compiles fast, contract-only and flagless half + - * on every profile that computes them in 16 bits and checks the instruction, its decoration, the note, the requirement and the interpreted answers. --- .../metal2vulkan/src/device/driver_facts.rs | 5 +- crates/metal2vulkan/src/error/mod.rs | 5 +- crates/metal2vulkan/src/lower/arith/mod.rs | 38 +++-- crates/metal2vulkan/src/lower/arith/ops.rs | 30 ++-- .../src/lower/arith/tests/narrow.rs | 57 ++++--- crates/metal2vulkan/src/pipeline/artifact.rs | 5 +- .../src/tests/engine_native_half.rs | 152 ++++++++++++++++++ docs/API.md | 11 +- docs/FAST-PATHS.md | 2 +- 9 files changed, 252 insertions(+), 53 deletions(-) diff --git a/crates/metal2vulkan/src/device/driver_facts.rs b/crates/metal2vulkan/src/device/driver_facts.rs index 3d8e25cb5..fa9afdcc7 100644 --- a/crates/metal2vulkan/src/device/driver_facts.rs +++ b/crates/metal2vulkan/src/device/driver_facts.rs @@ -193,7 +193,10 @@ pub(crate) fn among( /// differs. The same operations undecorated differ in the fast and relaxed modes, which fold the /// narrowings and the widening away (3,468,601,344 pairs for a sum, 4,014,926,892 for a product, /// 6,140 for a quotient); so does SPIRV-Cross's `NoContraction` `OpFMul`, `spvFMul`, which answers -/// `+0` for a `-0` product (126,974 pairs). The translation emits none of them. The sums read every +/// `+0` for a `-0` product (126,974 pairs). The translation emits the undecorated `OpFAdd`, +/// `OpFSub` and `OpFMul` only for an operation whose AIR flags carry `contract` and `reassoc`, the +/// AIR's own contraction, and records `PrecisionNote::FastMathRewrites` for it; never the decorated +/// `OpFMul`. The sums read every /// `half` through the device's widening (`x + -0` of every `x`), which every `half` read from its /// bits takes on a profile with `shaderFloat16` (`lower::arith::narrow::from_bits`), so a module /// that reads one requires this fact for its denormals; Metal's own widening, read on the M3 Max diff --git a/crates/metal2vulkan/src/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index 988689e1f..439f3133d 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -659,7 +659,10 @@ pub enum DriverDeviation { /// denormals kept, an exact zero sum `+0` unless both addends are `-0`, and every NaN result /// `0x7E00`, in every math mode. Where the profile also has `shaderFloat16`, a `half` `fadd`, /// `fsub` or `fmul` converts its operands (each a `half`, so exactly) to 16 bits, takes that - /// kept instruction and widens its result. Unmeasured, it takes the same instruction under the + /// kept instruction and widens its result; one whose flags carry `contract` and `reassoc` takes + /// the instruction undecorated instead, the AIR's own contraction, outside the measurement + /// (Metal's fast compile folds its conversions away, `PrecisionNote::FastMathRewrites`), and + /// requires nothing for it. Unmeasured, it takes the same instruction under the /// 16-bit float controls that make it Metal's by the Vulkan spec (`QuantizeForm::Controlled`), /// and elsewhere computes the result in `float` and rounds it to `half` as every `half` /// rounds (`narrow::round`, noted `NativeHalfConversion` or `NativeHalfQuantize` where that diff --git a/crates/metal2vulkan/src/lower/arith/mod.rs b/crates/metal2vulkan/src/lower/arith/mod.rs index 1bef352f2..1bd2af1ad 100644 --- a/crates/metal2vulkan/src/lower/arith/mod.rs +++ b/crates/metal2vulkan/src/lower/arith/mod.rs @@ -23,10 +23,11 @@ //! and `double` are native (`f64` needs `shaderFloat64`), and `half` and `bfloat` are held widened //! in an `f32` that is always a value of the narrow format ([`narrow`]): each operation rounds its //! `f32` result back to the format, so no profile needs `shaderFloat16`; where the device's 16-bit -//! `+ - *` is Metal's `half` arithmetic and the profile has `shaderFloat16`, a `half` `+ - *` is -//! that instruction, kept apart, between exact conversions instead ([`ArithStrategy::F16`]): where +//! `+ - *`, kept apart, is Metal's `half` arithmetic and the profile has `shaderFloat16`, a `half` +//! `+ - *` is that instruction between exact conversions instead ([`ArithStrategy::F16`]): where //! it is measured to be, and where the 16-bit float controls the module then declares make it so -//! by the Vulkan spec ([`narrow::controlled_modes`]). +//! by the Vulkan spec ([`narrow::controlled_modes`]). Its contraction is the AIR's own, as +//! `float`'s is: kept apart unless its flags carry both `contract` and `reassoc`. //! //! Precision: a `half` rounding keeps half denormals, as Metal does; a `float` or `half` fused //! multiply-add (`air.fma`, `llvm.fma`, and `llvm.fmuladd`, which Metal fuses) rounds once where @@ -198,10 +199,13 @@ pub enum ArithStrategy { /// A `half` `fadd`, `fsub` or `fmul` on lanes of `form` by the device's 16-bit arithmetic, /// Metal's own in the forms that keep it apart (measured, `DriverDeviation::MetalHalfArithmetic`, /// or by the Vulkan spec under the 16-bit float controls, [`ops::f16_binary`]): the operands - /// narrowed to 16 bits, exactly, the instruction kept apart, and its result widened, exactly. + /// narrowed to 16 bits, exactly, the instruction, and its result widened, exactly. `contract` + /// is the AIR's own, as for [`ArithStrategy::Float`] ([`contraction`]): `Allowed` leaves the + /// instruction to the device's compiler, `Forbidden` keeps it apart. F16 { op: AirBin, form: Form, + contract: Contraction, }, /// `fneg` on floats of `form`: the device's `OpFNegate`. FNeg { @@ -1478,12 +1482,22 @@ fn select_in( let s = S::FastDivide { form: f, contract }; with_nan(cx, s, Some(nan::NanAnswer::Canonical)) } else if let Some(basis) = f16_arithmetic(cx.profile, *op, f) { - // The device's own `half` arithmetic, Metal's in the forms that keep it - // apart, which the AIR's flags allow whatever they are. Only the measured - // basis is a property the module requires; the float controls are modes - // its entry declares. - cx.families.arith.f16_arith |= basis == F16Basis::Measured; - let s = S::F16 { op: *op, form: f }; + // The device's own `half` arithmetic, its contraction the AIR's own as + // `float`'s is. Kept apart, it is Metal's: measured, a property the + // module requires, or under the float controls its entry declares. + // Left to the device's compiler on MoltenVK, Metal's fast compile folds + // its conversions away and answers the `float` result unrounded + // (measured with `DriverDeviation::MetalHalfArithmetic`), noted. + let kept = contract == Contraction::Forbidden; + cx.families.arith.f16_arith |= basis == F16Basis::Measured && kept; + if basis == F16Basis::Measured && !kept { + cx.precision.insert(PrecisionNote::FastMathRewrites); + } + let s = S::F16 { + op: *op, + form: f, + contract, + }; with_nan(cx, s, nan::binary_answer(*op, fmt)) } else { // A `half` chain's operation held at `float` precision: its operands, @@ -3043,9 +3057,9 @@ fn value( let (p, q) = (a(cx, 0)?, a(cx, 1)?); ops::float_binary(fb, *op, *form, *contract, p, q)? } - S::F16 { op, form } => { + S::F16 { op, form, contract } => { let (p, q) = (a(cx, 0)?, a(cx, 1)?); - ops::f16_binary(fb, *op, form.lanes, p, q)? + ops::f16_binary(fb, *op, form.lanes, *contract, p, q)? } S::FastDivide { contract, .. } => { let (p, q) = (a(cx, 0)?, a(cx, 1)?); diff --git a/crates/metal2vulkan/src/lower/arith/ops.rs b/crates/metal2vulkan/src/lower/arith/ops.rs index 98c9ff27f..e32eff20a 100644 --- a/crates/metal2vulkan/src/lower/arith/ops.rs +++ b/crates/metal2vulkan/src/lower/arith/ops.rs @@ -285,18 +285,23 @@ pub fn f16_binary_words(f: Form) -> u32 { /// (the double rounding is innocuous). A NaN's bits are the device's, as the controlled rounding's /// are. /// -/// The instruction is always kept apart, whatever the AIR's flags allow: a sum or difference -/// decorated `NoContraction` (SPIRV-Cross writes its `[[clang::optnone]]` `spvFAdd` or `spvFSub`), -/// a product as `Fma(a, b, -0.0)` decorated `NoContraction`, the product's value whether the -/// device fuses it or not. Undecorated, Metal's fast and relaxed compiles fold the narrowings and -/// the widening away and answer the `float` sum, difference or product of the widened operands; a -/// `NoContraction` `OpFMul`, which SPIRV-Cross writes as `fma(l, r, 0)`, answers `+0` for a `-0` -/// product. Keeping each operation apart is one of the values the flags allow, the one the widened -/// lowering gives. +/// The instruction takes the AIR's own contraction, as `float` arithmetic does +/// ([`float_binary`]): one whose flags carry both `contract` and `reassoc` +/// (`Contraction::Allowed`) is undecorated, a product a plain `OpFMul`, and the device's compiler +/// groups and fuses it with its neighbours as it chooses. On MoltenVK, Metal's fast and relaxed +/// compiles fold such an operation's narrowings and widening away and answer the `float` sum, +/// difference or product of the widened operands, unrounded (measured with +/// `DriverDeviation::MetalHalfArithmetic`), which selection records as +/// `PrecisionNote::FastMathRewrites`. Any other (`Contraction::Forbidden`) is kept apart: a sum or +/// difference decorated `NoContraction` (SPIRV-Cross writes its `[[clang::optnone]]` `spvFAdd` or +/// `spvFSub`), a product as `Fma(a, b, -0.0)` decorated `NoContraction`, the product's value +/// whether the device fuses it or not; a `NoContraction` `OpFMul`, which SPIRV-Cross writes as +/// `fma(l, r, 0)`, answers `+0` for a `-0` product. pub fn f16_binary( fb: &mut FunctionBuilder<'_>, op: AirBin, lanes: u8, + contract: Contraction, a: Value, b: Value, ) -> BResult { @@ -310,10 +315,11 @@ pub fn f16_binary( let (h, w) = (float_ty(fb, 16)?, float_ty(fb, 32)?); let x = fb.convert(ConvOp::FConvert, a, h)?; let y = fb.convert(ConvOp::FConvert, b, h)?; - let r = match op { - AirBin::FAdd => fb.binary_no_contraction(BinOp::FAdd, x, y)?, - AirBin::FSub => fb.binary_no_contraction(BinOp::FSub, x, y)?, - AirBin::FMul => { + let r = match (op, contract) { + (AirBin::FAdd, _) => fb.binary_with(BinOp::FAdd, x, y, contract)?, + (AirBin::FSub, _) => fb.binary_with(BinOp::FSub, x, y, contract)?, + (AirBin::FMul, Contraction::Allowed) => fb.binary(BinOp::FMul, x, y)?, + (AirBin::FMul, Contraction::Forbidden) => { let e = fb.module().ty(Type::Float { width: 16 })?; let s = fb.module().constant(Constant::Scalar { ty: e, diff --git a/crates/metal2vulkan/src/lower/arith/tests/narrow.rs b/crates/metal2vulkan/src/lower/arith/tests/narrow.rs index c903ae5ed..d08fec118 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/narrow.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/narrow.rs @@ -2208,9 +2208,10 @@ fn half_arithmetic_on_the_device_follows_the_profile() { } /// The device's `half` `+ - *` ([`ops::f16_binary`]) is the exact result rounded once to `half`, on -/// the interpreter's correctly rounded 16-bit arithmetic: the operands narrow and the result widens -/// exactly (a NaN stays a NaN), on scalars and vectors, and the product kept apart as `Fma(a, b, -/// -0.0)` keeps a `-0` product. +/// the interpreter's correctly rounded 16-bit arithmetic, kept apart or left to the device's +/// compiler: the operands narrow and the result widens exactly (a NaN stays a NaN), on scalars and +/// vectors, and the product, kept apart as `Fma(a, b, -0.0)` or a plain `OpFMul`, keeps a `-0` +/// product. #[test] fn half_arithmetic_on_the_device_is_the_rounded_result() { let vals: Vec = half_values(); @@ -2226,12 +2227,16 @@ fn half_arithmetic_on_the_device_is_the_rounded_result() { AirBin::FSub => a - b, _ => a * b, }; - for op in [AirBin::FAdd, AirBin::FSub, AirBin::FMul] { + let contracts = [Contraction::Forbidden, Contraction::Allowed]; + for (op, contract) in [AirBin::FAdd, AirBin::FSub, AirBin::FMul] + .into_iter() + .flat_map(|op| contracts.map(|c| (op, c))) + { check_accept( - &format!("{op:?} on the device's half"), + &format!("{op:?} on the device's half, {contract:?}"), &[h, h], h, - &|fb, x| ops::f16_binary(fb, op, 1, x[0], x[1]), + &|fb, x| ops::f16_binary(fb, op, 1, contract, x[0], x[1]), &pairs(&vals, &few), &|c| { Some(vec![nbits( @@ -2254,12 +2259,15 @@ fn half_arithmetic_on_the_device_is_the_rounded_result() { ] }) .collect(); - for op in [AirBin::FAdd, AirBin::FSub, AirBin::FMul] { + for (op, contract) in [AirBin::FAdd, AirBin::FSub, AirBin::FMul] + .into_iter() + .flat_map(|op| contracts.map(|c| (op, c))) + { check_accept( - &format!("{op:?} on {lanes} lanes of the device's half"), + &format!("{op:?} on {lanes} lanes of the device's half, {contract:?}"), &[v, v], v, - &|fb, x| ops::f16_binary(fb, op, lanes, x[0], x[1]), + &|fb, x| ops::f16_binary(fb, op, lanes, contract, x[0], x[1]), &cases, &|c| { Some( @@ -2278,10 +2286,11 @@ fn half_arithmetic_on_the_device_is_the_rounded_result() { /// rounding of the module's own: no conversion barrier (`narrow::rounds_by_conversion` finds none), /// and the only instructions computing 16-bit values are the operation and at most two narrowings /// of its operands: an operand the module widened from a 16-bit float is that float, narrowed by -/// nothing (`FunctionBuilder::convert`); the operation is always kept apart: a sum or difference -/// decorated `NoContraction`, a product `Fma(a, b, -0.0)` decorated `NoContraction`, never an -/// `OpFMul` (undecorated, Metal's fast compile answers the widened operands' `float` product; -/// decorated, SPIRV-Cross's `spvFMul` answers `+0` for a `-0` product). +/// nothing (`FunctionBuilder::convert`). Its contraction is the AIR's own: kept apart +/// (`Contraction::Forbidden`), a sum or difference decorated `NoContraction` and a product +/// `Fma(a, b, -0.0)` decorated `NoContraction`, never an `OpFMul` (decorated, SPIRV-Cross's +/// `spvFMul` answers `+0` for a `-0` product); left to the device's compiler +/// (`Contraction::Allowed`), an undecorated `OpFAdd`, `OpFSub` or `OpFMul`, and no `Fma`. #[test] fn half_arithmetic_on_the_device_is_one_16_bit_instruction() { use crate::spirv::serialize::serialize; @@ -2299,12 +2308,13 @@ fn half_arithmetic_on_the_device_is_one_16_bit_instruction() { const NO_CONTRACTION: u32 = 42; const FMA: u32 = 50; let h = half(); - for lanes in [1u8, 4] { + let contracts = [Contraction::Forbidden, Contraction::Allowed]; + for (lanes, contract) in [1u8, 4].into_iter().flat_map(|l| contracts.map(|c| (l, c))) { let v = vec(h, lanes); for op in [AirBin::FAdd, AirBin::FSub, AirBin::FMul] { - let what = format!("{op:?} on {lanes} lanes"); + let what = format!("{op:?} on {lanes} lanes, {contract:?}"); let m = kernel(&[v, v], v, &|fb, x| { - ops::f16_binary(fb, op, lanes, x[0], x[1]) + ops::f16_binary(fb, op, lanes, contract, x[0], x[1]) }) .expect("kernel"); let mut meter = crate::budget::Meter::new(&crate::budget::Budget::default()); @@ -2356,10 +2366,11 @@ fn half_arithmetic_on_the_device_is_one_16_bit_instruction() { }) }) .collect(); - let want = match op { - AirBin::FAdd => (OP_FADD, 0), - AirBin::FSub => (OP_FSUB, 0), - _ => (OP_EXT_INST, FMA), + let want = match (op, contract) { + (AirBin::FAdd, _) => (OP_FADD, 0), + (AirBin::FSub, _) => (OP_FSUB, 0), + (_, Contraction::Allowed) => (OP_FMUL, 0), + (_, Contraction::Forbidden) => (OP_EXT_INST, FMA), }; let shapes: Vec<(u32, u32)> = computed.iter().map(|&(c, g, _)| (c, g)).collect(); let (last, before) = shapes.split_last().expect("the operation"); @@ -2372,7 +2383,11 @@ fn half_arithmetic_on_the_device_is_one_16_bit_instruction() { .last() .map(|&(_, _, id)| id) .expect("the operation"); - assert!(decorated.contains(&op_id), "{what}: NoContraction"); + assert_eq!( + decorated.contains(&op_id), + contract == Contraction::Forbidden, + "{what}: NoContraction" + ); } } } diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 560d7dd99..48b93b2a3 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -792,7 +792,10 @@ pub enum PrecisionNote { /// `HalfChainPolicy::AtExits` (the default), a chain of such `half` additions, subtractions and /// products is held at `float` precision between the roundings where its values leave it /// (`lower::arith::half_chain`): the result may differ from the rounded operations' by the - /// roundings skipped, and a value inside the chain past `half`'s range stays finite. + /// roundings skipped, and a value inside the chain past `half`'s range stays finite. On + /// MoltenVK, a `half` addition, subtraction or product carrying both flags is the device's + /// 16-bit instruction left undecorated, whose conversions Metal's fast compile folds away: it + /// answers the `float` result of the widened operands, unrounded, with the same bound. /// Recorded on every device. FastMathRewrites, /// A tessellation pipeline's vertex order: Metal's clockwise output winding is declared diff --git a/crates/metal2vulkan/src/tests/engine_native_half.rs b/crates/metal2vulkan/src/tests/engine_native_half.rs index f23510ff5..e76def3ac 100644 --- a/crates/metal2vulkan/src/tests/engine_native_half.rs +++ b/crates/metal2vulkan/src/tests/engine_native_half.rs @@ -1001,3 +1001,155 @@ fn a_half_read_from_memory_is_the_devices_widening_on_every_profile() { } assert_eq!(forms.len(), 3, "a profile of each form: {forms:?}"); } + +/// Kernels of one `half` `+ - *` each on the two `float`s narrowed: under fast math (`contract` and +/// `reassoc`, left to the device's compiler), under `contract` alone and with no flag (kept +/// apart). +const CONTRACTION: [(&str, &str); 5] = [ + ( + "fast_sum", + " %ha = fptrunc float %a to half\n %hb = fptrunc float %b to half\n %hs = fadd fast half %ha, %hb\n %r = fpext half %hs to float\n", + ), + ( + "fast_difference", + " %ha = fptrunc float %a to half\n %hb = fptrunc float %b to half\n %hs = fsub fast half %ha, %hb\n %r = fpext half %hs to float\n", + ), + ( + "fast_product", + " %ha = fptrunc float %a to half\n %hb = fptrunc float %b to half\n %hs = fmul fast half %ha, %hb\n %r = fpext half %hs to float\n", + ), + ( + "contract_sum", + " %ha = fptrunc float %a to half\n %hb = fptrunc float %b to half\n %hs = fadd contract half %ha, %hb\n %r = fpext half %hs to float\n", + ), + ( + "kept_product", + " %ha = fptrunc float %a to half\n %hb = fptrunc float %b to half\n %hs = fmul half %ha, %hb\n %r = fpext half %hs to float\n", + ), +]; + +/// The 16-bit `OpFAdd`, `OpFSub`, `OpFMul` and `GLSL.std.450 Fma` of `words`: each opcode (the +/// `Fma` as `Op::ExtInst`) and whether it is decorated `NoContraction`. +fn f16_arithmetic(words: &[u32]) -> Vec<(crate::spv::Op, bool)> { + use crate::spirv_binary::{parse_bytes, Operand}; + use crate::spv::{Decoration, Op}; + let bytes: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let parsed = parse_bytes(&bytes).expect("parse"); + let word = |o: Option<&Operand>| match o { + Some(Operand::Word(w) | Operand::IdRef(w)) => Some(*w), + _ => None, + }; + let mut half = std::collections::HashSet::new(); + let mut no_contraction = std::collections::HashSet::new(); + for i in &parsed.instructions { + match i.opcode { + Op::TypeFloat if word(i.operands.first()) == Some(16) => half.extend(i.result_id), + Op::TypeVector if word(i.operands.first()).is_some_and(|e| half.contains(&e)) => { + half.extend(i.result_id) + } + Op::Decorate if word(i.operands.get(1)) == Some(Decoration::NoContraction as u32) => { + no_contraction.extend(word(i.operands.first())); + } + _ => {} + } + } + let fma = |i: &crate::spirv_binary::Instruction| { + matches!(i.operands.get(1), Some(Operand::LiteralExtInstInteger(n)) + if *n == GlslOp::Fma.to_spirv() as u32) + }; + parsed + .instructions + .iter() + .filter(|i| i.result_type.is_some_and(|t| half.contains(&t))) + .filter(|i| { + matches!(i.opcode, Op::FAdd | Op::FSub | Op::FMul) + || (i.opcode == Op::ExtInst && fma(i)) + }) + .map(|i| { + let kept = i.result_id.is_some_and(|id| no_contraction.contains(&id)); + (i.opcode, kept) + }) + .collect() +} + +/// A `half` `+ - *` on the device's 16-bit arithmetic (`ops::f16_binary`) takes the AIR's own +/// contraction, as a `float` one does, on every profile that computes it so (MoltenVK, measured, +/// and the float-controls profiles): under fast math its one 16-bit instruction is undecorated, a +/// product a plain `OpFMul`; under `contract` alone or no flag it is kept apart, decorated +/// `NoContraction`, a product `Fma(a, b, -0.0)`. A lone operation has no neighbour to be rewritten +/// with, so a float-controls profile notes nothing, as for `float`; on MoltenVK, whose Metal compile +/// folds an undecorated one's conversions away, a fast one records `FastMathRewrites` and needs no +/// `MetalHalfArithmetic`, which a kept one requires. On the interpreter each answers the rounded +/// result either way. +#[test] +fn half_arithmetic_on_the_device_takes_the_airs_contraction() { + use crate::spv::Op; + let Some(bc) = assemble("half-contraction", &module_of(&CONTRACTION)) else { + return; + }; + let (mut measured_seen, mut controlled_seen) = (0, 0); + for (stem, p) in &committed_profiles().expect("profiles") { + let measured = p.fields().leaf.float16 + && p.takes_driver_deviation(DriverDeviation::MetalHalfArithmetic); + let controlled = quantize_form(p) == QuantizeForm::Controlled; + if !measured && !controlled { + continue; + } + measured_seen += usize::from(measured); + controlled_seen += usize::from(controlled && !measured); + for (name, _) in &CONTRACTION { + let what = format!("{name} on {stem}"); + let allowed = name.starts_with("fast_"); + 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 want = match (name.ends_with("product"), allowed) { + (false, _) if name.ends_with("difference") => Op::FSub, + (false, _) => Op::FAdd, + (true, true) => Op::FMul, + (true, false) => Op::ExtInst, + }; + assert_eq!( + f16_arithmetic(&a.module.words), + vec![(want, !allowed)], + "{what}" + ); + assert_eq!( + a.precision.contains(&PrecisionNote::FastMathRewrites), + measured && allowed, + "{what}: {:?}", + a.precision + ); + assert_eq!( + a.requirements + .properties + .contains(&VkProperty::MetalHalfArithmetic), + measured && !allowed, + "{what}: {:?}", + a.requirements.properties + ); + } + let run = |name: &str, x: [f32; 2]| interpret(&bc, name, p, x); + let (x, y) = (1.0 + 2f32.powi(-10), 2f32.powi(-11)); + for name in ["fast_sum", "contract_sum"] { + assert_eq!( + run(name, [x, y]), + 1.0 + 2f32.powi(-9), + "{name} on {stem}: a tie to even" + ); + } + assert_eq!(run("fast_difference", [x, y]), 1.0, "{stem}: a tie to even"); + for name in ["fast_product", "kept_product"] { + assert_eq!(run(name, [x, x]), 1.0 + 2f32.powi(-9), "{name} on {stem}"); + let z = run(name, [-0.0, 1.0]); + assert!(z == 0.0 && z.is_sign_negative(), "{name} on {stem}: {z}"); + } + } + assert!( + measured_seen >= 1, + "the MoltenVK capture computes it, measured" + ); + assert!( + controlled_seen >= 2, + "the float-controls profiles compute it" + ); +} diff --git a/docs/API.md b/docs/API.md index b24bc94be..4ba30b862 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3795,10 +3795,13 @@ bound. any other is kept apart (`NoContraction`); Metal's compiler groups and fuses by its own choice. On a device without `shaderFloat16`, a chain of such `half` additions, subtractions and products is held at `float` precision between the roundings where its values leave it - (`HalfChainPolicy::AtExits`, the default; `HalfChainPolicy::EachOperation` rounds each). - Cost: a sum of mixed signs grouped otherwise, or a multiply-add fused on one side alone, differs - from Metal's by any amount relative to the result; a held `half` chain by the roundings it - skips, a value inside it past `half`'s range staying finite. + (`HalfChainPolicy::AtExits`, the default; `HalfChainPolicy::EachOperation` rounds each). On + MoltenVK a `half` addition, subtraction or product carrying both flags is the 16-bit instruction + left undecorated, whose conversions Metal's fast compile folds away: the `float` result, + unrounded. Cost: a sum of mixed signs grouped otherwise, or a multiply-add fused on one side + alone, differs from Metal's by any amount relative to the result; a held `half` chain, or a + MoltenVK `half` operation left to the compiler, by the roundings it skips, a value inside it past + `half`'s range staying finite. - `metal2vulkan-degrade-tessellation-winding` (precision). `PrecisionNote::TessellationWinding`: A tessellation pipeline's vertex order: Metal's clockwise output winding is declared `VertexOrderCcw` and its counter-clockwise one `VertexOrderCw`, as MoltenVK maps them under diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 7c7f091c9..d4f3effa3 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -62,7 +62,7 @@ known. The rest of the differences are docs/API.md section 9's precision notes. | The maths library (`sin`, `exp`, `log`, `pow`, `sinh`, `cosh`, `tanh`, `atan2`...) on `float` and `half`, fast divisions and Metal's fast reciprocal, a `half` fused multiply-add, and a `float` one without `OpFmaKHR` are the device's instructions on every device whose `float` functions are not Metal's own (every device but MoltenVK, whose functions are Metal's in a fast-math entry; a `half` function is the `float` instruction rounded on every device); Metal's precise division (an `fdiv` without `arcp`, or on `half`) is the device's `OpFDiv` on every device. `fabs`, `sign` and `fract` are `FAbs`, `FSign` and `Fract`, their special operands (a NaN, an infinity, a signed zero, an `f32` denormal) the instruction's; the fast `sin`, `cos`, `tan`, `sinh`, `cosh`, `tanh` and `atanh` are `Sin`, `Cos`, `Tan`, `Sinh`, `Cosh`, `Tanh` and `Atanh`, not MSL Table 8.2's formulas (`fast::sin(1e7)` is the device's sine, Metal's `+0`; `fast::tanh(45)` is `1`, Metal's NaN); a `half` function's signed zeros and NaN signs are its `float` instruction's (`half` `sin(-0)` is `-0`, Metal's `+0`), and on every device a `half` `fmod`'s zero remainder is its `float` remainder's (`fmod(-2, 0.5)` is `-0`, Metal's `+0`); `pow`, `powr` and `atan2` add only C99's special values that `GLSL.std.450` leaves undefined, by the device's comparisons (`pow(x, 1)` is the device's `Pow`, Metal's `x`; a NaN operand's NaN is the device's sum of the operands); `round` is C99's from `Trunc` on every device (`round(-0.3)` is `-0`, Metal's `+0`). | The device's arithmetic is the contract: no routine computes Metal's answer, and no select reads a special operand as Metal does, where the device has an instruction. | Vulkan's precision table (`Sin` 2^-11 absolute in [-π, π], `Exp` 3 + 2·\|x\| ulp, `Log` 3 ulp or 2^-21 absolute in [0.5, 2], `Pow` from `Exp2(y · Log2 x)`, `FAbs`, `FSign` and `Fract` correct or correctly rounded, `Atan` 4096 ulp) against Metal's 4-6 ulp; division 2.5 ulp; `fma` one `half` ulp (a `float` one may round twice). `NativeTranscendentals` (`native-transcendentals`), `NativeDivision` (`native-division`), `NativeFma` (`native-fma`) | | `dot`, `mix` and `fast::sqrt` are the device's `OpDot`, `FMix` and `Sqrt` on every device, not Metal's fused chain, its two fused multiply-adds and `x · rsqrt(x)`: a `float` one on MoltenVK reaches Metal's own `dot`, `mix` and `fast::sqrt`, a `half` one is the instruction on its `float` container, rounded once; a `dot` of other than two to four lanes sums the `OpDot` of each chunk of up to four lanes. | The device's order is the contract. | `float` `dot` of n lanes within (3n − 1)·2^-24·Σ\|aᵢbᵢ\|, `mix` within 2^-21 of its two terms, `fast::sqrt` 4.5 ulp. `NativeDot` (`native-dot`), `NativeMix` (`native-mix`), `NativeTranscendentals` (`native-transcendentals`); a `dot` of other than two to four lanes within Vulkan's precision of its chunks' `OpDot` and sum, `DeviceArithmetic` (`device-arithmetic`) | | A filter emulated by fetches sums its taps in the device's arithmetic on every device: Metal's bicubic filter on every format (the Catmull-Rom weights computed in `f32` from the fraction, the sixteen taps summed by the device's multiply and add, a 32-bit float format's or a level under four texels' bilinear filter by its `FMix`), and an extended-range texture's linear, 3D and linear-mip-filter samples (`FMix` of the decoded taps at the `f32` fractions); a `half` result is the device's narrowing. Metal's fixed-point weight table, its exact grid sums rounded half up, its float accumulators and its sixty-fourth level fractions are not reproduced. The footprint, the addressing, the filter each format selects, the level and the format's clamp stay Metal's. | The device's arithmetic is the contract (rule 1); the device has no cubic filter on any committed profile (`VK_EXT_filter_cubic`), and no format holds the extended-range codes. | A few grid steps (`1/4080` at 8 bits), up to `2.1e-3` on an extended-range sRGB bicubic sample (`xr_bicubic::WEIGHTS_BOUND`), up to `1/64` of the levels' difference under a linear mip filter. `BicubicFilterArithmetic` (`bicubic-filter-arithmetic`) | -| Fast-math sums, differences and products group, and a multiply contracts into an addition, as the device's compiler groups and fuses them, on every device, MoltenVK included: each operation is emitted in the AIR's order, one carrying both `contract` and `reassoc` undecorated and any other `NoContraction`. Metal's compiler takes its own grouping (its rank order of a sum's leaves, its pairing of a product's lane-uniform factors) and its own fusion pairs. | The device's grouping is the contract: what the AIR's flags allow, the device's compiler chooses; nothing reproduces Metal's choice. | Unbounded relative to the result where a sum of mixed signs is grouped otherwise, or a multiply-add is fused on one side alone; each operation kept apart is exact as written. `FastMathRewrites` (`fast-math-rewrites`) | +| Fast-math sums, differences and products group, and a multiply contracts into an addition, as the device's compiler groups and fuses them, on every device, MoltenVK included: each operation is emitted in the AIR's order, one carrying both `contract` and `reassoc` undecorated and any other `NoContraction`, a `half` one on the device's 16-bit arithmetic too (its product a plain `OpFMul` when undecorated). Metal's compiler takes its own grouping (its rank order of a sum's leaves, its pairing of a product's lane-uniform factors) and its own fusion pairs. On MoltenVK an undecorated 16-bit `half` operation is computed in `float`: Metal's fast compile folds its conversions away. | The device's grouping is the contract: what the AIR's flags allow, the device's compiler chooses; nothing reproduces Metal's choice. | Unbounded relative to the result where a sum of mixed signs is grouped otherwise, or a multiply-add is fused on one side alone; each operation kept apart is exact as written; a MoltenVK `half` one left to the compiler by the rounding it skips. `FastMathRewrites` (`fast-math-rewrites`) | | `air.pack` and `air.unpack` of a normalized format are the device's conversion: `GLSL.std.450`'s `Pack`/`Unpack` `Unorm4x8`, `Snorm4x8`, `Unorm2x16` and `Snorm2x16`, and for `rgb10a2` and `rgb565` their definition by the device's `NClamp`, multiply, `RoundEven` (a pack) and multiply by the reciprocal (an unpack); `unorm4x8_srgb`'s colour is the MSL transfer functions by the device's `Pow` around the 8-bit instruction, as is an 8-bit sRGB storage texture's write through its UNORM alias. A `float` one of the four named formats on MoltenVK reaches Metal's own; on MoltenVK on the Apple M3 Max's macOS 27 identity (`DriverDeviation::MetalPackConversions`) so do `rgb565` in `float` and, in `half`, `unorm4x8`, `snorm4x8`, `rgb10a2` and `rgb565` both ways and `unorm2x16` and `snorm2x16` packed, measured to answer Metal's at every code and every `half` (`runtime_lane::pack_conversions`). The same conversions serve an implicit imageblock access of a normalized attachment (a `half` load rounding the unpacked `float` once more), the interlocked storage form's 8-bit sRGB attachment and sRGB word, and a snapshot's normalized codes (`c` times the `f32` nearest `1/D`). So does every conversion of an extended-range, padded 10-bit or bfloat texel, which no Vulkan format holds (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10`, `R10Unorm_X6`, `RG10Unorm_X12`, their sRGB twins, `RGB10A2Unorm_sRGB`, the bfloat formats; every device): a read `float(c - 384)` (a padded code's `float(c)`) times the `f32` nearest `1/510` (`1/1023`), a write `RoundEven` of the clamped value's `f32` product plus 384, an sRGB twin's colour the MSL transfer by the device's `Pow` on the magnitude, a `half` result the device's narrowing, a bfloat NaN as it is. | The device's conversion is the contract. | A packed code within one of Metal's, apart only where `clamp(c)·scale` lies within its rounding of a half-integer (`Round`'s tie is the device's); an unpacked value within 2.5 ulp of the correctly rounded quotient; a decoded sRGB colour within half a twelve-bit step (`1/8190`) of Metal's table step `k/4095`, beyond its `Pow`'s bound; a NaN channel's code the device's (Metal's: 0). An extended-range or padded value within one `f32` ulp of Metal's quotient, a code within one of Metal's exact product, an sRGB twin's decoded value within half a `2^-13` step of Metal's table (`R10Unorm_X6_sRGB`'s and `RGB10A2Unorm_sRGB`'s colour 1.64 steps) and its code within one (theirs within two below `0.0031308`, where Metal rounds the value to `2^-13` before its table), a `half` result within one `half` ulp (Metal rounds ties away from zero, a bfloat sample's `half` toward zero), a bfloat NaN the device's (Metal's: `0x7fc00000`, a write `0x7fc0`). `DevicePackConversion` (`device-pack-conversion`) | | Off MoltenVK a `float` multiply, a fused multiply-add by `OpFmaKHR`, and a `float` `ldexp` (whose result below `2^-126` is that multiply's product) round before Metal's flush: Metal flushes a result whose exact value lies below `2^-126` before rounding it, so a result whose exact value lies within half a unit below `2^-126` answers `2^-126` of its sign where Metal answers the zero of its sign. | Every device measured off MoltenVK (RADV, ANV, NVIDIA, lavapipe) rounds first; its multiply is the contract. | Announced once per device as it is made: `float-tininess-after-rounding` | | `f32` denormals in a `float` operation on a device not measured to read them as Metal does (`DriverDeviation::MetalFloatDenormals`: lavapipe, and every unmeasured device), in `floor`, `ceil`, `fneg` and `fabs` on a device not measured to read them as Metal's do (`DriverDeviation::MetalUnaryDenormals`: every device but MoltenVK on the Apple M3 Max's macOS 27 identity), and on every device in a nearest pixel sample's texel `floor(x)` (which Metal's sampler reads from a subnormal `x` itself, a negative one as texel -1, where MoltenVK's `floor` reads it as the zero of its sign: recorded only where the `s` or `t` mode is repeat, clamp to zero or clamp to the border, which read texel -1 apart from texel 0, through a constexpr sampler of such a mode, through a runtime slot under a pipeline made for a nearest pixel state and announced where the bound state's mode is such, through an argument buffer as `argument-pixel-sampler-scaling`), in the maths functions (`sign` and `fract` among them, and the zero and sign tests of `pow`, `powr` and `atan2`) and the device's order of the rows above, and in a conversion to or from `double`. Metal reads them as zero and flushes a denormal result. | The device's reading is the contract: Vulkan lets each device keep or flush them, and Metal runs no `double`, so its reading of a conversion is not measured. | `DeviceDenormals` (`device-denormals`) |