From 2bc03fa2767727ca2a52c9a8d53c475c1fd7a346 Mon Sep 17 00:00:00 2001 From: Guyliano Buyssens Date: Mon, 23 Nov 2026 13:34:51 +0000 Subject: [PATCH] Recompiler: f16 add / sub / fma rounded once under a directed mode (#111) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Under s_round_mode MODE[3:2] != RNE the f16 add, sub, fma (also fmac / fmamk / fmaak, the packed forms and v_fma_mix*_f16) computed in f32 with RNE and then converted to binary16 in the requested mode: when the exact result does not fit f32 (1.0 + 2^-24 needs 25 bits) the first rounding could land exactly on a binary16 value and the directed rounding had nothing left to do (1.0 + 2^-24 under +inf gave 1.0; the console gives 1 + 2^-10). - PRELUDE_F16_RM (only in programs that change MODE[3:2] and have f16 ops; PRELUDE itself is unchanged, so no other program's HLSL or DXIL cache entry changes): f32_to_f16_rm_sticky folds the sign of the f32 result's rounding error into the binary16 rounding – on a binary16 value or midpoint it decides the direction; add_f16_rm / fma_f16_rm get that error from a TwoSum (the product of two binary16 values is exact in f32), fma_mix_f16_rm from a double TwoSum (f32 sources; a double beyond f32's range is brought to 2^17 / 2^-40 first – the mode alone decides there). An infinite or NaN source gives inf / NaN under every mode (the review's lane 18: +inf under RTZ was taken for a finite overflow and gave 65504). OMOD and CLAMP apply to the result and its error before the rounding. An exactly zero sum takes IEEE's sign (x + -x is +0, -0 under -inf; the f32 sum's RNE zero ignored the mode). - v_mad_f16 does not exist on RDNA2 (not in the ISA tables): its arm goes. - is_f64_rounded_op: exact f64 ops (conversions from f32 / i32 / u32, floor / ceil / trunc / rndne, min / max, frexp_mant) no longer make s_round_mode unsupported (v_fract_f64 = x - floor(x) rounds for a negative x and stays). - GPU tests: the helpers lane by lane (the #128 review's cases: 65536 - 2^-24 under RNE overflows, mix results beyond f32's range, the zero's sign), and the ISA forms under the four modes (the #111 cases, the overflow and subnormal edges, a fma whose f32 sum ties on a binary16 midpoint, OMOD and CLAMP). gpu_s_round_mode_controls_f16_rounding_across_modes: fma(-0, 1, +0) is +0 (DXC's mad(x, 1, 0) folded to x before). --- crates/xcl/src/gpu/recomp/emit.rs | 165 ++++++++++++++++++++++-- crates/xcl/src/gpu/recomp/tests.rs | 200 +++++++++++++++++++++++++++-- 2 files changed, 342 insertions(+), 23 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 8888caeda..0a7300097 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -416,7 +416,6 @@ fn is_f16_rounded_op(name: &str) -> bool { | "v_min3_f16" | "v_max3_f16" | "v_frexp_mant_f16" - | "v_mad_f16" | "v_fmac_f16" | "v_fmamk_f16" | "v_fmaak_f16" @@ -443,7 +442,34 @@ fn is_f64_rounded_op(name: &str) -> bool { name.contains("_f64") && !name.starts_with("v_cmp_") && !name.starts_with("v_cmpx_") - && !matches!(name, "v_cvt_f32_f64" | "v_cvt_i32_f64" | "v_cvt_u32_f64" | "v_frexp_exp_i32_f64") + // exact results (or no f64 result): the rounding mode cannot change them + && !matches!( + name, + "v_cvt_f32_f64" + | "v_cvt_i32_f64" + | "v_cvt_u32_f64" + | "v_cvt_f64_f32" + | "v_cvt_f64_i32" + | "v_cvt_f64_u32" + | "v_frexp_exp_i32_f64" + | "v_frexp_mant_f64" + | "v_trunc_f64" + | "v_floor_f64" + | "v_ceil_f64" + | "v_rndne_f64" + | "v_min_f64" + | "v_max_f64" + ) +} + +/// The factor a VOP3 `OMOD` applies to a float result, as an HLSL literal. +fn omod_scale(omod: u64) -> &'static str { + match omod { + 1 => "2.0f", + 2 => "4.0f", + 3 => "0.5f", + _ => "1.0f", + } } /// HLSL expression converting float expression `e` to a 16-bit half (`0..=0xFFFF`). @@ -2792,6 +2818,10 @@ impl Em { let (a, b, c) = (h(0, hi), h(1, hi), h(2, hi)); let curh = if hi { format!("({cur} >> 16)") } else { format!("({cur} & 0xFFFFu)") }; Some(match name { + // add / fma under MODE[3:2]: rounded once from the f32 result and its error (#111) + "v_pk_add_f16" if dyn_rm => format!("add_f16_rm({}, {}, 1.0f, {clamp}, xcl_fp16_rm)", fh(0, hi), fh(1, hi)), + "v_pk_fma_f16" if dyn_rm => format!("fma_f16_rm({}, {}, {}, 1.0f, {clamp}, xcl_fp16_rm)", fh(0, hi), fh(1, hi), fh(2, hi)), + "v_pk_fmac_f16" if dyn_rm => format!("fma_f16_rm({}, {}, f16tof32({curh}), 1.0f, {clamp}, xcl_fp16_rm)", fh(0, hi), fh(1, hi)), "v_pk_add_f16" => fr(format!("{} + {}", fh(0, hi), fh(1, hi))), "v_pk_mul_f16" => fr(format!("{} * {}", fh(0, hi), fh(1, hi))), "v_pk_fma_f16" => fr(format!("mad({}, {}, {})", fh(0, hi), fh(1, hi), fh(2, hi))), @@ -2956,6 +2986,8 @@ impl Em { }; let si = |i: usize| format!("(((int)({} << 16)) >> 16)", half(i)); let dyn_rm = self.dynamic_f16_rm; + // add / fma under MODE[3:2]: the f32 result and its rounding error, rounded once (#111) + let rm_args = format!("{}, {}, xcl_fp16_rm", omod_scale(m.omod), m.clamp); let fr = |e: String| -> String { let mut s = match m.omod { 1 => format!("(({e}) * 2.0f)"), @@ -2980,6 +3012,13 @@ impl Em { let curh = if plain && m.opsel >> 3 & 1 == 1 { format!("({cur} >> 16)") } else { format!("({cur} & 0xFFFFu)") }; let (a, b, c) = (half(0), half(1), half(2)); let r: String = match name { + "v_add_f16" if dyn_rm => format!("add_f16_rm({}, {}, {rm_args})", fh(0), fh(1)), + "v_sub_f16" if dyn_rm => format!("add_f16_rm({}, -({}), {rm_args})", fh(0), fh(1)), + "v_subrev_f16" if dyn_rm => format!("add_f16_rm({}, -({}), {rm_args})", fh(1), fh(0)), + "v_fma_f16" if dyn_rm => format!("fma_f16_rm({}, {}, {}, {rm_args})", fh(0), fh(1), fh(2)), + "v_fmac_f16" if dyn_rm => format!("fma_f16_rm({}, {}, f16tof32({curh}), {rm_args})", fh(0), fh(1)), + "v_fmamk_f16" if dyn_rm => format!("fma_f16_rm({}, f16tof32({} & 0xFFFFu), {}, {rm_args})", fh(0), u[1], fh(2)), + "v_fmaak_f16" if dyn_rm => format!("fma_f16_rm({}, {}, f16tof32({} & 0xFFFFu), {rm_args})", fh(0), fh(1), u[2]), "v_add_f16" => fr(format!("{} + {}", fh(0), fh(1))), "v_sub_f16" => fr(format!("{} - {}", fh(0), fh(1))), "v_subrev_f16" => fr(format!("{} - {}", fh(1), fh(0))), @@ -2999,10 +3038,6 @@ impl Em { "v_frexp_mant_f16" => fr(format!("frexp_mant({})", fh(0))), "v_frexp_exp_i16_f16" => format!("((uint)frexp_exp({}) & 0xFFFFu)", fh(0)), "v_cndmask_b16" => return Err("VALU 16-bit"), - "v_mad_f16" => { - let rm = if dyn_rm { "xcl_fp16_rm" } else { "0u" }; - fr(format!("mad_nf_f16({}, {}, {}, {rm})", fh(0), fh(1), fh(2))) - } "v_fmac_f16" => fr(format!("mad({}, {}, f16tof32({curh}))", fh(0), fh(1))), "v_fmamk_f16" => fr(format!("mad({}, f16tof32({} & 0xFFFFu), {})", fh(0), u[1], fh(2))), "v_fmaak_f16" => fr(format!("mad({}, {}, f16tof32({} & 0xFFFFu))", fh(0), fh(1), u[2])), @@ -3329,14 +3364,23 @@ impl Em { } s }; + let clamp = fv("CLAMP") == 1; let mut e = format!("mad({}, {}, {})", src(0), src(1), src(2)); - if fv("CLAMP") == 1 { + if clamp { e = format!("saturate({e})"); } + // f16 result under MODE[3:2]: exact product and sum error, rounded once (#111) + let h16 = || { + if self.dynamic_f16_rm { + format!("fma_mix_f16_rm({}, {}, {}, {clamp}, xcl_fp16_rm)", src(0), src(1), src(2)) + } else { + to_f16_expr(false, &e) + } + }; match name { "v_fma_mix_f32" => format!("asuint({e})"), - "v_fma_mixlo_f16" => format!("({cur} & 0xFFFF0000u) | {}", to_f16_expr(self.dynamic_f16_rm, &e)), - _ => format!("({cur} & 0xFFFFu) | ({} << 16)", to_f16_expr(self.dynamic_f16_rm, &e)), + "v_fma_mixlo_f16" => format!("({cur} & 0xFFFF0000u) | {}", h16()), + _ => format!("({cur} & 0xFFFFu) | ({} << 16)", h16()), } } "v_rcp_f32" | "v_rcp_iflag_f32" => fr(format!("rcp({})", fs(0))), @@ -4277,6 +4321,7 @@ impl Em { h.push_str(PRELUDE_SCRATCH); } if self.dynamic_f16_rm { + h.push_str(PRELUDE_F16_RM); h.push_str("static uint xcl_fp16_rm = 0u;\n"); } let mut sg: BTreeSet = self.sgprs.clone(); @@ -5550,6 +5595,108 @@ void xcl_s_barrier() { } "#; +/// Rounding of binary16 results under `MODE[3:2]`; only in programs that write a non-default +/// mode and have f16 ops (`Em::dynamic_f16_rm`), so the other programs' HLSL does not change +/// (`PRELUDE` keeps its plain `f32_to_f16_rm`, which `to_f16_expr` uses, for the same reason: +/// every program's DXIL cache entry would otherwise be rebuilt once). +pub(crate) const PRELUDE_F16_RM: &str = r#" +// IEEE-754 binary32 -> binary16 under RDNA2 MODE[3:2]: 0 = RNE, 1 = +inf, 2 = -inf, 3 = RTZ. +// `sticky` is the sign of (exact value - f) when f is itself a rounded f32 result (TwoSum's error, +// add_f16_rm): the exact value then lies strictly between f and its f32 neighbour, so it decides +// the direction when f sits exactly on a binary16 value or midpoint. 0: f is the exact value. +uint f32_to_f16_rm_sticky(float f, int sticky, uint rm) { + uint x = asuint(f); + uint sign = (x >> 16) & 0x8000u; + uint ax = x & 0x7FFFFFFFu; + if (ax >= 0x7F800000u) return sign | select(ax == 0x7F800000u, 0x7C00u, 0x7E00u | ((ax >> 13) & 0x01FFu)); + if (ax == 0u) return sign; + bool mag_up = (sticky > 0) == (sign == 0u); // the exact value is larger in magnitude than f + bool away = or(and(rm == 1u, sign == 0u), and(rm == 2u, sign != 0u)); // directed: away from zero + if (ax >= 0x47800000u) { + // 65536 and above: past the midpoint 65520 (that one takes the normal path below), so RNE + // overflows whatever the sticky bit says + if (rm == 0u) return sign | 0x7C00u; + return sign | select(away, 0x7C00u, 0x7BFFu); + } + if (ax < 0x33800000u) { + // below the smallest subnormal (2^-24): 0 or 2^-24, 2^-25 is the midpoint + bool inc = select(rm == 0u, or(ax > 0x33000000u, and(ax == 0x33000000u, and(sticky != 0, mag_up))), away); + return sign | (uint)inc; + } + uint h, rem, half_bit; + if (ax >= 0x38800000u) { + h = (((ax >> 23) - 112u) << 10) | ((ax >> 13) & 0x3FFu); + rem = ax & 0x1FFFu; + half_bit = 0x1000u; + } else { + uint sh = 126u - (ax >> 23); + uint sig = 0x00800000u | (ax & 0x007FFFFFu); + h = sig >> sh; + half_bit = 1u << (sh - 1u); + rem = sig & ((1u << sh) - 1u); + } + if (rm == 0u) { + bool tie_up = select(sticky == 0, (h & 1u) != 0u, mag_up); + return sign | (h + (uint)or(rem > half_bit, and(rem == half_bit, tie_up))); + } + // directed, f on a binary16 value: an exact value beyond it rounds past it + if (rem == 0u) return sign | select(sticky == 0, h, select(mag_up, h + (uint)away, h - (uint)(!away))); + return sign | (h + (uint)away); +} +// The sign of an exactly zero sum a + b (IEEE 754): -0 from -0 + -0, and under -inf from +// anything but +0 + +0; +0 otherwise (a cancellation x + -x included) +float zero_sum(float a, float b, uint rm) { + bool pos_a = asuint(a) == 0u, pos_b = asuint(b) == 0u; + bool plus = or(and(pos_a, pos_b), and(rm != 2u, or(a != 0.0f, or(pos_a, pos_b)))); + return asfloat(select(plus, 0u, 0x80000000u)); +} +// The f32 result of a binary16 operation and the exact error of its rounding (TwoSum), scaled by +// OMOD, clamped, rounded once to binary16 under rm. The sum of two binary16 values needs up to 41 +// bits, so the f32 sum rounds and its error decides the direction (#111: 1.0 + 2^-24 under +inf +// gave 1.0 through f32, the console gives 1 + 2^-10). +uint f16_result_rm(float s, float err, float scale, bool clamp, uint rm) { + precise float ss = s * scale; + precise float es = err * scale; + if (clamp) { + if (or(!(ss >= 0.0f), and(ss == 0.0f, es < 0.0f))) { ss = 0.0f; es = 0.0f; } // negative, NaN + else if (or(ss > 1.0f, and(ss == 1.0f, es > 0.0f))) { ss = 1.0f; es = 0.0f; } + } + return f32_to_f16_rm_sticky(ss, select(es > 0.0f, 1, select(es < 0.0f, -1, 0)), rm); +} +uint add_f16_rm(float a, float b, float scale, bool clamp, uint rm) { + precise float s = a + b; + precise float bb = s - a; + precise float err = (a - (s - bb)) + (b - bb); + if (s == 0.0f) s = zero_sum(a, b, rm); // the f32 sum is RNE: its zero's sign ignores the mode + return f16_result_rm(s, err, scale, clamp, rm); +} +// a * b + c fused: the product of two binary16 values is exact in f32 (22 bits) +uint fma_f16_rm(float a, float b, float c, float scale, bool clamp, uint rm) { precise float p = a * b; return add_f16_rm(p, c, scale, clamp, rm); } +// v_fma_mix*_f16 (f32 sources): the product is exact in a double (48 bits), the sum's error comes +// from a double TwoSum; both fold into the f32 result's sticky bit +uint fma_mix_f16_rm(float a, float b, float c, bool clamp, uint rm) { + precise double p = (double)a * (double)b; + precise double cd = (double)c; + precise double s = p + cd; + precise double bb = s - p; + precise double e = (p - (s - bb)) + (cd - bb); + if (s == 0.0) return f16_result_rm(zero_sum((float)p, c, rm), 0.0f, 1.0f, clamp, rm); + precise double sa = abs(s); + // an infinite or NaN result (from such a source: finite f32 sources cannot overflow a + // double) is inf or NaN under every mode – only a finite value beyond binary16's range + // takes the mode's largest finite value below + if (!(sa < 1.0e308)) return f16_result_rm((float)s, 0.0f, 1.0f, clamp, rm); + // beyond binary16's range the result depends on the mode alone: the double is brought to a + // value f32 holds (2^100 * 2^100 would convert to inf and lose RTZ's 65504; 2^-100 * 2^-100 to 0 + // and lose +inf's 2^-24), 2^17 and 2^-40 are exact in f32 + if (sa > 131072.0) s = select(s < 0.0, -131072.0, 131072.0); + if (sa < 9.094947017729282e-13) s = select(s < 0.0, -9.094947017729282e-13, 9.094947017729282e-13); + precise float sf = (float)s; + precise double r = (s - (double)sf) + e; + return f16_result_rm(sf, select(r > 0.0, 1.0f, select(r < 0.0, -1.0f, 0.0f)), 1.0f, clamp, rm); +} +"#; + const PRELUDE: &str = r#" static uint lane_id; // loop iterations a lane may run (`LOOP_GUARD`): far above what a working program needs diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 56d71f0d1..c57aad7b0 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -6867,8 +6867,11 @@ fn gpu_s_round_mode_controls_f16_rounding_across_modes() { assert_eq!(v[14] as u16, rne, "lane {l} ({bits:#010x}) reset to RNE"); assert_eq!(v[15] as u16, rtn, "lane {l} ({bits:#010x}) setreg_imm32 partial -> -inf"); assert_eq!(v[16] as u16, rtp, "lane {l} ({bits:#010x}) setreg_b32 dynamic -> +inf"); - assert_eq!(v[22] as u16, rne, "lane {l} ({bits:#010x}) v_fma_mixlo_f16 RNE"); - assert_eq!(v[25] as u16, rtz, "lane {l} ({bits:#010x}) v_fma_mixlo_f16 RTZ"); + // fma(-0, 1, +0) is +0 (IEEE; the conversion of -0 keeps its sign) – the console's fma does + // not fold to its first operand, DXC's mad(x, 1, 0) did + let (mix_rne, mix_rtz) = if bits == 0x8000_0000 { (0x0000, 0x0000) } else { (rne, rtz) }; + assert_eq!(v[22] as u16, mix_rne, "lane {l} ({bits:#010x}) v_fma_mixlo_f16 RNE"); + assert_eq!(v[25] as u16, mix_rtz, "lane {l} ({bits:#010x}) v_fma_mixlo_f16 RTZ"); } // Verify V_MUL_F16 & V_PK_MUL_F16 honor RNE vs RTZ assert_eq!(r.vgpr[0][20] as u16, 0x7C00, "v_mul_f16 overflow RNE"); @@ -6883,30 +6886,199 @@ fn gpu_s_round_mode_controls_f16_rounding_across_modes() { } #[test] -fn gpu_mad_nf_f16_rounds_intermediate_in_binary16() { +/// The helpers of `PRELUDE_F16_RM` fold a sticky bit (the sign of the f32 result's rounding error) +/// into one binary16 rounding: on a binary16 value or midpoint it decides the direction (#111). +fn gpu_f16_rounding_helpers_fold_the_sticky_bit() { if !gpu_ready() { return; } - // Compile a wave32 kernel containing the recompiler PRELUDE and exercise `mad_nf_f16` directly. let base = prog(&[("V_MOV_B32", "ENC_VOP1", &[("VDST", 0), ("SRC0", V + 0)], None)]); let opt = Options { wave64: false, hw_wave: 32, ..Options::default() }; let mut hlsl = translate(&base, &opt).unwrap().hlsl; - let probe = "\ - if (lane_id == 0u) v0 = f32_to_f16_rm(mad_nf_f16(f16tof32(0x7BFFu), f16tof32(0x3C01u), f16tof32(0xFBFFu), 0u), 0u);\n\ - if (lane_id == 1u) v0 = f32_to_f16_rm(mad_nf_f16(f16tof32(0x7BFFu), f16tof32(0x3C01u), f16tof32(0xFBFFu), 3u), 3u);\n\ - if (lane_id == 2u) v0 = f32_to_f16_rm(mad_nf_f16(f16tof32(0x3C01u), f16tof32(0x3C01u), f16tof32(0xBC02u), 0u), 0u);\n"; + assert!(hlsl.contains("[WaveSize("), "unexpected kernel:\n{hlsl}"); + hlsl = hlsl.replacen("[WaveSize(", &format!("{}[WaveSize(", super::emit::PRELUDE_F16_RM), 1); + // (probe expression, expected binary16) + let probes: &[(&str, u32)] = &[ + // a binary16 value with the exact value just beyond it: directed modes step past it, RNE stays + ("f32_to_f16_rm_sticky(1.0f, 1, 1u)", 0x3C01), + ("f32_to_f16_rm_sticky(1.0f, 1, 0u)", 0x3C00), + ("f32_to_f16_rm_sticky(1.0f, 1, 2u)", 0x3C00), + ("f32_to_f16_rm_sticky(2.0f, -1, 3u)", 0x3FFF), + ("f32_to_f16_rm_sticky(-1.0f, -1, 2u)", 0xBC01), + ("f32_to_f16_rm_sticky(-1.0f, -1, 1u)", 0xBC00), + ("f32_to_f16_rm_sticky(-1.0f, 1, 3u)", 0xBBFF), + // a midpoint with a sticky bit is no tie: 1 + 2^-11 + ("f32_to_f16_rm_sticky(asfloat(0x3F801000u), -1, 0u)", 0x3C00), + ("f32_to_f16_rm_sticky(asfloat(0x3F801000u), 1, 0u)", 0x3C01), + // 65520: the overflow tie + ("f32_to_f16_rm_sticky(asfloat(0x477FF000u), -1, 0u)", 0x7BFF), + ("f32_to_f16_rm_sticky(asfloat(0x477FF000u), 1, 0u)", 0x7C00), + ("f32_to_f16_rm_sticky(asfloat(0x477FF000u), 0, 0u)", 0x7C00), + // 2^-25: the tie below the smallest subnormal + ("f32_to_f16_rm_sticky(asfloat(0x33000000u), 1, 0u)", 0x0001), + ("f32_to_f16_rm_sticky(asfloat(0x33000000u), -1, 0u)", 0x0000), + // the largest finite value, exact value above it + ("f32_to_f16_rm_sticky(65504.0f, 1, 1u)", 0x7C00), + ("f32_to_f16_rm_sticky(65504.0f, 1, 3u)", 0x7BFF), + // the smallest subnormal, exact value below it, toward zero + ("f32_to_f16_rm_sticky(asfloat(0x33800000u), -1, 3u)", 0x0000), + // no sticky: as before + ("f32_to_f16_rm(asfloat(0x3F801000u), 0u)", 0x3C00), + ("f32_to_f16_rm(asfloat(0x3F803000u), 0u)", 0x3C02), + // add_f16_rm: 1 + 2^-24 with OMOD *2 (2 + 2^-23), with CLAMP (1.0) + ("add_f16_rm(1.0f, asfloat(0x33800000u), 2.0f, false, 1u)", 0x4001), + ("add_f16_rm(1.0f, asfloat(0x33800000u), 2.0f, false, 3u)", 0x4000), + ("add_f16_rm(1.0f, asfloat(0x33800000u), 1.0f, true, 1u)", 0x3C00), + ("add_f16_rm(-1.0f, asfloat(0x33800000u), 1.0f, true, 2u)", 0x0000), + // fma_f16_rm RNE tie through f32: 1.5 * (1 + 2^-10) - 2^-24 is below the midpoint 1.5 + 2^-10 + 2^-11 + ("fma_f16_rm(1.5f, f16tof32(0x3C01u), -asfloat(0x33800000u), 1.0f, false, 0u)", 0x3E01), + ("fma_f16_rm(1.5f, f16tof32(0x3C01u), -asfloat(0x33800000u), 1.0f, false, 1u)", 0x3E02), + // fma_mix_f16_rm: f32 sources, 1 * 1 + 2^-30 + ("fma_mix_f16_rm(1.0f, 1.0f, asfloat(0x30800000u), false, 1u)", 0x3C01), + ("fma_mix_f16_rm(1.0f, 1.0f, asfloat(0x30800000u), false, 0u)", 0x3C00), + ("fma_mix_f16_rm(1.0f, 1.0f, asfloat(0x30800000u), true, 1u)", 0x3C00), + // the product of two f32 values is exact in the double: (1 + 2^-23)^2 = 1 + 2^-22 + 2^-46 + ("fma_mix_f16_rm(asfloat(0x3F800001u), asfloat(0x3F800001u), 0.0f, false, 3u)", 0x3C00), + ("fma_mix_f16_rm(asfloat(0x3F800001u), asfloat(0x3F800001u), 0.0f, false, 1u)", 0x3C01), + // #128 review (Foniass): 65536 - 2^-24 is past the midpoint 65520 – RNE overflows; 256 * 256 - 2^-24 + ("f32_to_f16_rm_sticky(65536.0f, -1, 0u)", 0x7C00), + ("fma_f16_rm(f16tof32(0x5C00u), f16tof32(0x5C00u), f16tof32(0x8001u), 1.0f, false, 0u)", 0x7C00), + ("fma_f16_rm(f16tof32(0x5C00u), f16tof32(0x5C00u), f16tof32(0x8001u), 1.0f, false, 3u)", 0x7BFF), + ("add_f16_rm(f16tof32(0x7800u), f16tof32(0x8001u), 2.0f, false, 0u)", 0x7C00), + ("fma_mix_f16_rm(1.0f, 65536.0f, -asfloat(0x30800000u), false, 0u)", 0x7C00), + // mix results beyond f32's range: the mode alone decides + ("fma_mix_f16_rm(asfloat(0x71800000u), asfloat(0x71800000u), 0.0f, false, 3u)", 0x7BFF), + ("fma_mix_f16_rm(asfloat(0x71800000u), asfloat(0x71800000u), 0.0f, false, 0u)", 0x7C00), + ("fma_mix_f16_rm(asfloat(0x0D800000u), asfloat(0x0D800000u), 0.0f, false, 1u)", 0x0001), + ("fma_mix_f16_rm(asfloat(0x0D800000u), asfloat(0x0D800000u), 0.0f, false, 0u)", 0x0000), + // an infinite source: inf under RTZ too (not the largest finite value a finite overflow + // takes), clamped to 1; a NaN source stays a NaN + ("fma_mix_f16_rm(asfloat(0x7F800000u), 1.0f, 0.0f, false, 3u)", 0x7C00), + ("fma_mix_f16_rm(1.0f, 1.0f, asfloat(0xFF800000u), false, 3u)", 0xFC00), + ("fma_mix_f16_rm(asfloat(0x7F800000u), 1.0f, 0.0f, true, 3u)", 0x3C00), + ("(fma_mix_f16_rm(asfloat(0x7FC00000u), 1.0f, 0.0f, false, 3u) & 0x7E00u)", 0x7E00), + // the sign of an exact zero: x + -x is +0, -0 under -inf; -0 + -0 stays -0; +0 + +0 stays +0 + ("add_f16_rm(1.0f, -1.0f, 1.0f, false, 0u)", 0x0000), + ("add_f16_rm(1.0f, -1.0f, 1.0f, false, 2u)", 0x8000), + ("add_f16_rm(-0.0f, -0.0f, 1.0f, false, 0u)", 0x8000), + ("add_f16_rm(0.0f, 0.0f, 1.0f, false, 2u)", 0x0000), + ("add_f16_rm(0.0f, -0.0f, 1.0f, false, 2u)", 0x8000), + ("fma_mix_f16_rm(-0.0f, 1.0f, 0.0f, false, 0u)", 0x0000), + ]; let marker = " v0 = select((((exec_lo >> lane_id) & 1u) != 0u), (v0), v0);\n"; assert!(hlsl.contains(marker), "unexpected kernel body:\n{hlsl}"); - hlsl = hlsl.replace(marker, probe); + // 32 lanes per kernel: the probes go in as many kernels as it takes + for chunk in probes.chunks(32) { + let mut probe = String::new(); + for (l, (e, _)) in chunk.iter().enumerate() { + probe.push_str(&format!(" if (lane_id == {l}u) v0 = {e};\n")); + } + let dxil = super::dxc::compile(&hlsl.replace(marker, &probe), "main", "cs_6_6", &[]).unwrap(); + let mut st = KernelState::default(); + st.sgpr[127] = 0; + let r = runner::run(&dxil, &st, &[]).unwrap(); + for (l, (e, want)) in chunk.iter().enumerate() { + assert_eq!(r.vgpr[l][0], *want, "lane {l}: {e}"); + } + } +} + +#[test] +/// f16 add / sub / fma / pk / mix under `s_round_mode`: the exact result rounded once (#111 – through +/// f32 and RNE, 1.0 + 2^-24 under +inf gave 1.0; the console gives 1 + 2^-10). +fn gpu_f16_add_and_fma_round_once_under_directed_modes() { + if !gpu_ready() { + return; + } + // Per lane: a, b (binary16), m1 * m2 + b for the fma (m2 = 1.0 unless the lane says otherwise), + // expected add / sub [RNE, +inf, -inf, RTZ], expected fma. + struct Case { + a: u32, + b: u32, + m1: u32, + m2: u32, + add: [u32; 4], + fma: [u32; 4], + } + let same = |a, b, r: [u32; 4]| Case { a, b, m1: a, m2: 0x3C00, add: r, fma: r }; + let cases = [ + same(0x3C00, 0x0001, [0x3C00, 0x3C01, 0x3C00, 0x3C00]), // 1 + 2^-24 + same(0x4000, 0x8001, [0x4000, 0x4000, 0x3FFF, 0x3FFF]), // 2 - 2^-24 + same(0xBC00, 0x8001, [0xBC00, 0xBC00, 0xBC01, 0xBC00]), // -1 - 2^-24 + same(0xC000, 0x0001, [0xC000, 0xBFFF, 0xC000, 0xBFFF]), // -2 + 2^-24 + same(0x7BFF, 0x0001, [0x7BFF, 0x7C00, 0x7BFF, 0x7BFF]), // 65504 + 2^-24 + same(0x3C00, 0x3C00, [0x4000, 0x4000, 0x4000, 0x4000]), // exact + same(0x0400, 0x8001, [0x03FF, 0x03FF, 0x03FF, 0x03FF]), // 2^-14 - 2^-24: exact subnormal + same(0x7BFF, 0x5000, [0x7C00, 0x7C00, 0x7BFF, 0x7BFF]), // 65504 + 32 = 65536: overflow + // 1.5 * (1 + 2^-10) - 2^-24: the f32 sum ties and lands on the binary16 midpoint; the exact + // value is below it (add: 1.5 - 2^-24) + Case { a: 0x3E00, b: 0x8001, m1: 0x3E00, m2: 0x3C01, add: [0x3E00, 0x3E00, 0x3DFF, 0x3DFF], fma: [0x3E01, 0x3E02, 0x3E01, 0x3E01] }, + ]; + // Constant across the lanes: packed halves (low: case 0, high: case 1), mix 1 * 1 + 2^-30 (f32). + let pk: [u32; 4] = [0x4000_3C00, 0x4000_3C01, 0x3FFF_3C00, 0x3FFF_3C00]; + let mix: [u32; 4] = [0x3C00, 0x3C01, 0x3C00, 0x3C00]; + // Blocks of results: mode -> VGPR base; results +0 add, +1 fma, +2 pk add, +3 pk fma, +4 mixlo, + // +5 sub, +6 add * 2 (OMOD), +7 add clamped. + let blocks: [(u64, usize, u64); 4] = [(0x4, 1, 10), (0xC, 3, 20), (0x8, 2, 30), (0x0, 0, 40)]; + let mut list: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = Vec::new(); + for &(mode, _, base) in &blocks { + list.push(("S_ROUND_MODE", "ENC_SOPP", vec![("SIMM16", mode)], None)); + // inputs in v50.. (the result blocks take v10..v47) + list.push(("V_ADD_F16", "ENC_VOP2", vec![("VDST", base), ("SRC0", V + 50), ("VSRC1", 51)], None)); + list.push(("V_FMA_F16", "ENC_VOP3", vec![("VDST", base + 1), ("SRC0", V + 52), ("SRC1", V + 53), ("SRC2", V + 51)], None)); + list.push(("V_PK_ADD_F16", "ENC_VOP3P", vec![("VDST", base + 2), ("SRC0", V + 54), ("SRC1", V + 55), ("OP_SEL_HI", 3)], None)); + list.push(("V_PK_FMA_F16", "ENC_VOP3P", vec![("VDST", base + 3), ("SRC0", V + 56), ("SRC1", V + 57), ("SRC2", V + 55), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1)], None)); + list.push(("V_FMA_MIXLO_F16", "ENC_VOP3P", vec![("VDST", base + 4), ("SRC0", V + 58), ("SRC1", V + 59), ("SRC2", V + 60)], None)); + list.push(("V_SUB_F16", "ENC_VOP2", vec![("VDST", base + 5), ("SRC0", V + 50), ("VSRC1", 61)], None)); + list.push(("V_ADD_F16", "ENC_VOP3", vec![("VDST", base + 6), ("SRC0", V + 50), ("SRC1", V + 51), ("OMOD", 1)], None)); + list.push(("V_ADD_F16", "ENC_VOP3", vec![("VDST", base + 7), ("SRC0", V + 50), ("SRC1", V + 51), ("CLAMP", 1)], None)); + } + let list: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(n, e, f, l)| (*n, *e, f.as_slice(), *l)).collect(); + let code = prog(&list); + let opt = Options { wave64: false, hw_wave: 32, ..Options::default() }; + let t = translate(&code, &opt).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + assert!(t.hlsl.contains("add_f16_rm(") && t.hlsl.contains("fma_f16_rm(") && t.hlsl.contains("fma_mix_f16_rm("), "{}", t.hlsl); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); - let dxil = super::dxc::compile(&hlsl, "main", "cs_6_6", &[]).unwrap(); let mut st = KernelState::default(); st.sgpr[127] = 0; + for (l, c) in cases.iter().enumerate() { + let v = &mut st.vgpr[l]; + v[50] = c.a; + v[51] = c.b; + v[52] = c.m1; + v[53] = c.m2; + v[54] = 0x4000_3C00; + v[55] = 0x8001_0001; + v[56] = 0x4000_3C00; + v[57] = 0x3C00_3C00; + v[58] = 0x3F80_0000; + v[59] = 0x3F80_0000; + v[60] = 0x3080_0000; + v[61] = c.b ^ 0x8000; + } let r = runner::run(&dxil, &st, &[]).unwrap(); - - assert_eq!(r.vgpr[0][0], 0x7C00, "mad_nf_f16 RNE overflow: 65504*(1+2^-10)-65504 -> +inf"); - assert_eq!(r.vgpr[1][0], 0x0000, "mad_nf_f16 RTZ clamp: 65504*(1+2^-10)->65504, -65504 -> 0"); - assert_eq!(r.vgpr[2][0], 0x0000, "mad_nf_f16 cancellation: (1+2^-10)^2-(1+2^-9) -> 0 (not 2^-20)"); + for (l, c) in cases.iter().enumerate() { + let v = &r.vgpr[l]; + for &(mode, k, base) in &blocks { + let base = base as usize; + assert_eq!(v[base], c.add[k], "lane {l} mode {mode:#x}: v_add_f16 {:#06x} + {:#06x}", c.a, c.b); + assert_eq!(v[base + 1], c.fma[k], "lane {l} mode {mode:#x}: v_fma_f16 {:#06x} * {:#06x} + {:#06x}", c.m1, c.m2, c.b); + assert_eq!(v[base + 2], pk[k], "lane {l} mode {mode:#x}: v_pk_add_f16"); + assert_eq!(v[base + 3], pk[k], "lane {l} mode {mode:#x}: v_pk_fma_f16"); + assert_eq!(v[base + 4], mix[k], "lane {l} mode {mode:#x}: v_fma_mixlo_f16"); + assert_eq!(v[base + 5], c.add[k], "lane {l} mode {mode:#x}: v_sub_f16"); + } + } + // OMOD * 2 and CLAMP on lane 0 (1 + 2^-24): 2 + 2^-23 rounds like the sum, the clamp gives 1.0 + let omod: [u32; 4] = [0x4000, 0x4001, 0x4000, 0x4000]; + for &(mode, k, base) in &blocks { + let base = base as usize; + assert_eq!(r.vgpr[0][base + 6], omod[k], "mode {mode:#x}: v_add_f16 omod"); + assert_eq!(r.vgpr[0][base + 7], 0x3C00, "mode {mode:#x}: v_add_f16 clamp"); + assert_eq!(r.vgpr[2][base + 7], 0x0000, "mode {mode:#x}: v_add_f16 clamp of a negative sum"); + } } #[test]