f16 add / FMA under a directed rounding mode are rounded twice (through f32) #111

Open
opened 2026-11-26 04:10:35 +00:00 by github-bot · 8 comments
Owner

@⁠Foniass on GitHub · 2026-11-23 11:46 UTC · original

Follow-up to #91 / #73, found while testing #91 on an RTX 5070 Ti.

With a directed f16 rounding mode (s_round_mode MODE[3:2] = RTZ, +inf or -inf), f16 add / sub / FMA results are rounded twice: the operation runs in f32 (RNE), and then f32_to_f16_rm (to_f16_expr, emit.rs) rounds that f32 value to f16 in the requested mode. When the exact result isn't representable in f32, the first RNE step can land exactly on an f16 value, and the directed step then has nothing left to round.

Measured on the GPU (same results natively and in the split wave64 form):

mode instruction inputs XCL correct
s_round_mode 0x4 (+inf) v_add_f16 0x3C00 (1.0) + 0x0001 (2⁻²⁴) 0x3C00 0x3C01
s_round_mode 0xC (RTZ) v_add_f16 0x4000 (2.0) + 0x8001 (−2⁻²⁴) 0x4000 0x3FFF
s_round_mode 0xC (RTZ) v_fma_f16 2.0 × 1.0 + (−2⁻²⁴) 0x4000 0x3FFF
  • Affected: v_add_f16 / v_sub_f16 / v_subrev_f16, v_fma_f16, v_fmac_f16 / v_fmamk_f16 / v_fmaak_f16, v_pk_add_f16 / v_pk_fma_f16 / v_pk_fmac_f16, v_fma_mix*_f16.
  • Not affected: v_mul_f16 and v_cvt_f16_f32, whose f32 intermediate is exact, and RNE mode, where double rounding through f32 is harmless (24 ≥ 2·11 + 2).
  • Why it matters: per #73, 0xC (f16/f64 RTZ) is 95% of the retail pack's s_round_mode uses, so f16 add / FMA under RTZ is the main case #91 handles. It's much closer than before (always RNE) but not exact. #91's tests cover conversion, multiply and the mix instruction, whose inputs are exact, so they don't catch this.
  • Possible fix: an f16 sum is always exact in f64 (at most 41 significant bits), so add/sub can be computed in double and rounded once to f16 with the directed mode. FMA needs the exact error term (TwoSum / FMA residual, or round-to-odd in f64) before the directed rounding.

Two smaller notes from the same review:

  • V_MAD_F16 is in neither rdna2_spec.rs nor rdna2_xbox.rs (encode("V_MAD_F16", …) fails), so the v_mad_f16 arm in emit.rs can't be reached. gpu_mad_nf_f16_rounds_intermediate_in_binary16 tests the HLSL helper directly.
  • is_f64_rounded_op counts every _f64 name except compares and three conversions, so s_round_mode 0xC followed by an exact v_cvt_f64_f32 is reported unsupported ("non-default f64 round mode"). The pack still translates 100%, so this has no effect today.
**@⁠Foniass** on GitHub · 2026-11-23 11:46 UTC · [original](https://github.com/xcl-dev/xcl/issues/111) Follow-up to #91 / #73, found while testing #91 on an RTX 5070 Ti. With a directed f16 rounding mode (`s_round_mode` MODE[3:2] = RTZ, +inf or -inf), f16 **add / sub / FMA** results are rounded twice: the operation runs in f32 (RNE), and then `f32_to_f16_rm` (`to_f16_expr`, `emit.rs`) rounds that f32 value to f16 in the requested mode. When the exact result isn't representable in f32, the first RNE step can land exactly on an f16 value, and the directed step then has nothing left to round. Measured on the GPU (same results natively and in the split wave64 form): | mode | instruction | inputs | XCL | correct | |---|---|---|---|---| | `s_round_mode 0x4` (+inf) | `v_add_f16` | `0x3C00` (1.0) + `0x0001` (2⁻²⁴) | `0x3C00` | `0x3C01` | | `s_round_mode 0xC` (RTZ) | `v_add_f16` | `0x4000` (2.0) + `0x8001` (−2⁻²⁴) | `0x4000` | `0x3FFF` | | `s_round_mode 0xC` (RTZ) | `v_fma_f16` | 2.0 × 1.0 + (−2⁻²⁴) | `0x4000` | `0x3FFF` | - **Affected:** `v_add_f16` / `v_sub_f16` / `v_subrev_f16`, `v_fma_f16`, `v_fmac_f16` / `v_fmamk_f16` / `v_fmaak_f16`, `v_pk_add_f16` / `v_pk_fma_f16` / `v_pk_fmac_f16`, `v_fma_mix*_f16`. - **Not affected:** `v_mul_f16` and `v_cvt_f16_f32`, whose f32 intermediate is exact, and RNE mode, where double rounding through f32 is harmless (24 ≥ 2·11 + 2). - **Why it matters:** per #73, `0xC` (f16/f64 RTZ) is 95% of the retail pack's `s_round_mode` uses, so f16 add / FMA under RTZ is the main case #91 handles. It's much closer than before (always RNE) but not exact. #91's tests cover conversion, multiply and the mix instruction, whose inputs are exact, so they don't catch this. - **Possible fix:** an f16 sum is always exact in f64 (at most 41 significant bits), so add/sub can be computed in double and rounded once to f16 with the directed mode. FMA needs the exact error term (TwoSum / FMA residual, or round-to-odd in f64) before the directed rounding. Two smaller notes from the same review: - `V_MAD_F16` is in neither `rdna2_spec.rs` nor `rdna2_xbox.rs` (`encode("V_MAD_F16", …)` fails), so the `v_mad_f16` arm in `emit.rs` can't be reached. `gpu_mad_nf_f16_rounds_intermediate_in_binary16` tests the HLSL helper directly. - `is_f64_rounded_op` counts every `_f64` name except compares and three conversions, so `s_round_mode 0xC` followed by an exact `v_cvt_f64_f32` is reported unsupported ("non-default f64 round mode"). The pack still translates 100%, so this has no effect today.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 04:10:35 +00:00
Author
Owner

@⁠gefydev on GitHub · 2026-11-23 12:48 UTC · original

@⁠Foniass are you fixing this one yourself? If not, I can take the add / sub / FMA part: add and sub in f64 and rounded once to f16 in the directed mode (exact, as you say). For FMA the f64 product is exact (22 bits), but product + addend is not always: c = 2^15 with a product of -2^-40 gives exactly c in f64, and RTZ needs c - 1 ulp. So I would take the exact error of that sum (TwoSum) and move the f64 result one ulp towards it when it is not zero, then round once to f16. I would test it on a GTX 1650. I will wait for your answer so we do not do it twice.

**@⁠gefydev** on GitHub · 2026-11-23 12:48 UTC · [original](https://github.com/xcl-dev/xcl/issues/111#issuecomment-7101664923) @⁠Foniass are you fixing this one yourself? If not, I can take the add / sub / FMA part: add and sub in f64 and rounded once to f16 in the directed mode (exact, as you say). For FMA the f64 product is exact (22 bits), but product + addend is not always: c = 2^15 with a product of -2^-40 gives exactly c in f64, and RTZ needs c - 1 ulp. So I would take the exact error of that sum (TwoSum) and move the f64 result one ulp towards it when it is not zero, then round once to f16. I would test it on a GTX 1650. I will wait for your answer so we do not do it twice.
Author
Owner

@⁠ic3bear-ai on GitHub · 2026-11-23 23:59 UTC · original

Two additions from a run on an RTX 3070. Both concern the default mode. The issue lists it under Not affected: "RNE mode, where double rounding through f32 is harmless (24 ≥ 2·11 + 2)".

1. In the default mode the f16 step is not round-to-nearest in the code as it is. That reasoning needs the second rounding to be RNE too (and, see 2, holds for add / sub only). Without a dynamic mode, though, to_f16_expr emits the legacy f32tof16, not f32_to_f16_rm, and on this GPU that rounds toward zero. The comment at to_f16_rounded_expr says so as well.

Tested on main at 9ab7d76: RTX 3070 (driver 616.92), Windows 11 build 26200, debug build, DXC 1.8.2502.11. The GPU test is against an exact reference: f16 values as integers in units of 2^-24, a + b and a·b + c exact in i128, rounded to nearest even in integer arithmetic. It's IEEE as documented for RDNA2, not a comparison with console hardware. Results before the fix (1600 per form, wave32; the fma forms include the pinned cases from point 2):

wrong
v_add_f16 / with neg, abs / with omod ×2 438 / 500 / 485
v_sub_f16 / v_subrev_f16 / v_sub_f16 with abs on both 532 / 532 / 696
v_fma_f16 / with neg, abs / clamp / omod ×0.5 746 / 588 / 46 / 747
v_fmac_f16 / v_fmamk_f16 / v_fmaak_f16 746 / 844 / 721
v_pk_add_f16 lo / hi 452 / 435
v_pk_fma_f16 lo / hi / with neg lo / neg_hi 727 / 743 / 512 / 491
v_pk_fmac_f16 lo / hi 727 / 743
v_mul_f16, v_pk_mul_f16 lo / hi (control) 0

The 40 failures the test prints are all one ulp toward zero, e.g. v_add_f16(0x03ff, 0xbc00) (−1 + 6.1e-5) gives 0xbbff instead of 0xbc00.

One GPU and one driver. I don't know whether other NVIDIA GPUs or AMD's f32tof16 truncate too.

2. For fma, RNE double rounding through f32 is not harmless, even with an RNE second step. The 2p + 2 result covers +, −, ×, ÷ and √ of p-bit operands, not a·b + c (the product has 22 bits). Counterexample: fma(0x3100, 0x7162, 0x0300) = 1722.5 + 4.6e-5. The exact value is just above an f16 tie, so it must round to 1723 (0x66bb); through f32 the addend is lost, and the tie goes to 0x66ba.

A CPU simulation ("f32 fma, then f16 RNE" against the exact reference) found 710 such cases in 31.8 M. The inputs were biased toward ties, so that says little about the rate in real shaders. So the fma fix is needed in the default mode as well, not only the directed ones.

What I tried locally (not pushed), for #128 or whoever takes this: round-to-odd, as the issue suggests, but in binary32 rather than f64:

  • TwoSum of the exact f32 product and the addend; if inexact, truncate and set the lowest bit; then f32_to_f16_rm.
  • binary32 has ≥ 11 + 2 bits, so by Boldo & Melquiond (2008) this is exact in any final mode.

Results:

  • the CPU simulation: 0 wrong;
  • the GPU test: 0 wrong in all 24 forms, also with XCL_FUZZ_ITERS=5000 (160 000 per form);
  • the pinned tie cases (10 for fma, one each for fmamk / fmaak): they fail with "f32 RNE, then f16" and pass with round-to-odd;
  • the test catches deliberately broken translations: fmamk with K as the addend, and omod ×0.5 applied as ×2, each fail only their own form;
  • cargo test --workspace --no-fail-fast -- --test-threads=4: 653 passed, 1 failed, 40 ignored, 2 SKIPPED (no wave64). The failure is a separate test of mine for partial-wave reductions (#152), which fails on main by design.

That's a sample, not a proof.

Not tested:

  • the directed modes;
  • the console's own clamp / omod semantics. The test follows the emitter's reading (omod, then clamp, on the exact result, then one rounding); a clamped NaN gives 0 (the D3D clamp rule) and a clamped −0 may give either zero;
  • other GPUs, and wave64;
  • whether other drivers keep the precise TwoSum as written;
  • the cost in shaders.

The test is below, in case it helps check #128 or an AMD GPU.

Comment written with Claude Code (Claude Opus 5.5) from runs on the hardware above; I checked the results.

The test (paste into crates/xcl/src/gpu/recomp/tests.rs, before fn hwreg_imm; it uses the file's existing f16_to_f64, Rng, gpu_waves, kernel_wave, prog)

Run with cargo test -p xcl --lib f16_ -- --nocapture; XCL_FUZZ_ITERS=5000 for more cases.

/// A finite f16 as an exact integer in units of 2^-24 (every f16 is a multiple of 2^-24, at most
/// 65504 = 2^40 units); None for inf / NaN.
fn f16_exact(h: u16) -> Option<i128> {
    let (e, m) = ((h >> 10) & 0x1F, (h & 0x3FF) as i128);
    let mag = match e {
        31 => return None,
        0 => m,
        _ => (m | 0x400) << (e - 1),
    };
    Some(if h & 0x8000 != 0 { -mag } else { mag })
}

/// An exact value in units of 2^-`u` (u >= 24) rounded to f16, to nearest, ties to even (the
/// RDNA default, MODE.FP_ROUND f16 = 0), overflowing to inf; `neg_zero`: the sign of an exact
/// zero.
fn f16_round_exact(v: i128, u: u32, neg_zero: bool) -> u16 {
    let sign = if v < 0 || (v == 0 && neg_zero) { 0x8000u16 } else { 0 };
    let m = v.unsigned_abs();
    let bits = |x: u128| 127 - x.leading_zeros(); // 2^bits <= x
    // the quantum, in units: 2^-24 below the smallest normal (2^-14), else 2^(exponent - 10)
    let min_normal = 1u128 << (u - 14);
    let q_log = if m < min_normal { u - 24 } else { bits(m) - 10 };
    let mut k = m >> q_log;
    if q_log > 0 {
        let (r, half) = (m & ((1u128 << q_log) - 1), 1u128 << (q_log - 1));
        if r > half || (r == half && k & 1 == 1) {
            k += 1;
        }
    }
    let rounded = k << q_log;
    if rounded < min_normal {
        return sign | (rounded >> (u - 24)) as u16;
    }
    let l = bits(rounded);
    let e = l as i32 - u as i32 + 15;
    if e >= 31 {
        return sign | 0x7C00;
    }
    sign | (e as u16) << 10 | ((rounded >> (l - 10)) as u16 & 0x3FF)
}

#[test]
fn f16_exact_reference_round_trips() {
    for h in 0..=u16::MAX {
        if let Some(v) = f16_exact(h) {
            assert_eq!(v as f64 / 2f64.powi(24), f16_to_f64(h), "{h:#06x}");
            for u in [24, 48] {
                assert_eq!(f16_round_exact(v << (u - 24), u, h & 0x8000 != 0), h, "{h:#06x} in units of 2^-{u}");
            }
        }
    }
    // in units of 2^-48: 1.0 = 2^48, its ulp 2^38
    let (one, ulp) = (1i128 << 48, 1i128 << 38);
    let r = |v: i128| f16_round_exact(v, 48, false);
    assert_eq!(r(one + ulp / 2), 0x3C00, "a tie to the even 1.0");
    assert_eq!(r(one + 3 * ulp / 2), 0x3C02, "a tie to the even 1 + 2^-9");
    assert_eq!(r(one + ulp / 2 + 1), 0x3C01, "just above the tie");
    assert_eq!(r(one + ulp / 2 - 1), 0x3C00, "just below the tie");
    assert_eq!(r(-(one + ulp / 2 + 1)), 0xBC01);
    let max = f16_exact(0x7BFF).unwrap() << 24; // 65504; 65520 is the tie with 2^16
    assert_eq!(r(max + (16 << 48)), 0x7C00, "65520 rounds to inf");
    assert_eq!(r(max + (16 << 48) - 1), 0x7BFF);
    assert_eq!(r(1 << 23), 0x0000, "half the smallest subnormal: a tie to 0");
    assert_eq!(r((1 << 23) + 1), 0x0001);
    assert_eq!(r(3 << 23), 0x0002, "1.5 subnormal quanta: a tie to the even 2");
    assert_eq!(f16_round_exact(0, 48, true), 0x8000);
}

/// f16 arithmetic against an exact CPU reference (`f16_exact` / `f16_round_exact`) on random
/// operands: v_add / sub / subrev / mul / fma / fmac / fmamk / fmaak_f16 and v_pk_add / mul / fma /
/// fmac_f16 (both halves), plain and with abs / neg / neg_hi inputs, clamp and omod
/// (`f16_reference`), default mode (round to nearest even, f16 denormals kept). A NaN result
/// only has to be a NaN.
/// One wave of operands per dispatch in 50 dispatches, or n with XCL_FUZZ_ITERS=n.
#[test]
fn gpu_f16_arithmetic_random() {
    for wave64 in gpu_waves() {
        f16_arithmetic_random(wave64);
    }
}

/// The literals of `f16_arithmetic_random`'s v_fmamk_f16 / v_fmaak_f16: with a = 0x3100, they
/// make the first `HARD_FMA` case (b = 0x0300 for fmamk, pinned in a lane; lane 0's b = 0x7162
/// for fmaak).
const FMAMK_K: u16 = 0x7162;
const FMAAK_K: u16 = 0x0300;

/// f16 fma operands that double rounding through binary32 gets wrong (`f16_arithmetic_random`).
const HARD_FMA: [(u16, u16, u16); 10] = [
    (0xa300, 0xec46, 0x001e),
    (0x3100, 0x7162, 0x0300),
    (0x9168, 0x6e4a, 0xe216),
    (0x4102, 0xf100, 0x8ce2),
    (0xe3f0, 0xc437, 0xb47f),
    (0x44c9, 0xf200, 0x07e4),
    (0x5051, 0xa0b1, 0xcbb0),
    (0x552a, 0x5500, 0x05aa),
    (0xd224, 0xd480, 0x0329),
    (0xd860, 0x5dd0, 0x096b),
];

/// The exactly rounded f16 result of `op` ("add", "sub", "subrev", "mul", "fma": a·b + c) on
/// f16 bits (input modifiers already applied to the bits), then the output modifiers as the
/// emitter applies them (`Em::out_mods`, the repo's reading of the ISA, not checked on a
/// console): `omod` (1: ×2, 2: ×4, 3: ×0.5) scales the exact result, `clamp` limits it to
/// [0, 1], then one rounding to nearest even. None: a NaN. With `clamp` a NaN gives 0 (the
/// D3D / AMD clamp rule: assumed, not checked on a console).
fn f16_reference(op: &str, a: u16, b: u16, c: u16, omod: u64, clamp: bool) -> Option<u16> {
    let (x, y) = if op == "subrev" { (b, a) } else { (a, b) };
    let y = if op == "sub" || op == "subrev" { y ^ 0x8000 } else { y };
    let neg = |h: u16| h & 0x8000 != 0;
    let scale = [1.0, 2.0, 4.0, 0.5][omod as usize & 3];
    // exact in units of 2^-u, with the sign of an exact zero
    let exact = match (op, f16_exact(x), f16_exact(y), f16_exact(c)) {
        ("mul", Some(p), Some(q), _) => Some((p * q, 48, neg(x) != neg(y))),
        // a·b + c in units of 2^-48 (|a·b| <= 2^80)
        ("fma", Some(p), Some(q), Some(s)) => Some((p * q + (s << 24), 48, (p * q == 0 && s == 0) && neg(x) != neg(y) && neg(c))),
        ("fma", ..) | ("mul", ..) => None,
        (_, Some(p), Some(q), _) => Some((p + q, 24, p == 0 && q == 0 && neg(x) && neg(y))),
        _ => None,
    };
    let Some((v, u, nz)) = exact else {
        // an operand is inf or NaN: f64 gives the inf or the NaN
        let (fx, fy, fc) = (f16_to_f64(x), f16_to_f64(y), f16_to_f64(c));
        let r = match op {
            "mul" => fx * fy,
            "fma" => fx.mul_add(fy, fc),
            _ => fx + fy,
        } * scale;
        return match (r.is_nan(), clamp) {
            (true, true) => Some(0),
            (true, false) => None,
            (false, true) => Some(if r > 0.0 { 0x3C00 } else { 0 }),
            (false, false) => Some(if r > 0.0 { 0x7C00 } else { 0xFC00 }),
        };
    };
    let (v, u) = match omod & 3 {
        1 => (v << 1, u),
        2 => (v << 2, u),
        3 => (v, u + 1),
        _ => (v, u),
    };
    if clamp {
        if v <= 0 {
            return Some(0);
        }
        if v >= 1 << u {
            return Some(0x3C00);
        }
    }
    Some(f16_round_exact(v, u, nz))
}

fn f16_arithmetic_random(wave64: bool) {
    let iters: usize = std::env::var("XCL_FUZZ_ITERS").ok().and_then(|s| s.parse().ok()).unwrap_or(50);
    // v10..v14 = add, sub, subrev, mul, fma of the low halves of v0, v1 (v2); v15..v17 =
    // pk_add, pk_mul, pk_fma of v3, v4 (v5); v18 += v0 · v1 (fmac, v18 = v2 before), v19 +=
    // v3 · v4 (pk_fmac, v19 = v5 before)
    let p = prog(&[
        ("V_ADD_F16", "ENC_VOP2", &[("VDST", 10), ("SRC0", V), ("VSRC1", 1)], None),
        ("V_SUB_F16", "ENC_VOP2", &[("VDST", 11), ("SRC0", V), ("VSRC1", 1)], None),
        ("V_SUBREV_F16", "ENC_VOP2", &[("VDST", 12), ("SRC0", V), ("VSRC1", 1)], None),
        ("V_MUL_F16", "ENC_VOP2", &[("VDST", 13), ("SRC0", V), ("VSRC1", 1)], None),
        ("V_FMA_F16", "ENC_VOP3", &[("VDST", 14), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 2)], None),
        ("V_PK_ADD_F16", "ENC_VOP3P", &[("VDST", 15), ("SRC0", V + 3), ("SRC1", V + 4), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1)], None),
        ("V_PK_MUL_F16", "ENC_VOP3P", &[("VDST", 16), ("SRC0", V + 3), ("SRC1", V + 4), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1)], None),
        ("V_PK_FMA_F16", "ENC_VOP3P", &[("VDST", 17), ("SRC0", V + 3), ("SRC1", V + 4), ("SRC2", V + 5), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1)], None),
        ("V_FMAC_F16", "ENC_VOP2", &[("VDST", 18), ("SRC0", V), ("VSRC1", 1)], None),
        ("V_PK_FMAC_F16", "ENC_VOP2", &[("VDST", 19), ("SRC0", V + 3), ("VSRC1", 4)], None),
        // modifiers: v20 = -a + |b|, v21 = -a·|b| - c, v22 = clamp(a·b + c), v23 = 2(a + b),
        // v24 = (a·b + c) / 2, v25 = |a| - |b|, v26 = pk_fma with -a (low) and -c (high);
        // literals: v27 = a·K + b (fmamk), v28 = a·b + K (fmaak)
        ("V_ADD_F16", "ENC_VOP3", &[("VDST", 20), ("SRC0", V), ("SRC1", V + 1), ("NEG", 1), ("ABS", 2)], None),
        ("V_FMA_F16", "ENC_VOP3", &[("VDST", 21), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 2), ("NEG", 5), ("ABS", 2)], None),
        ("V_FMA_F16", "ENC_VOP3", &[("VDST", 22), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 2), ("CLAMP", 1)], None),
        ("V_ADD_F16", "ENC_VOP3", &[("VDST", 23), ("SRC0", V), ("SRC1", V + 1), ("OMOD", 1)], None),
        ("V_FMA_F16", "ENC_VOP3", &[("VDST", 24), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 2), ("OMOD", 3)], None),
        ("V_SUB_F16", "ENC_VOP3", &[("VDST", 25), ("SRC0", V), ("SRC1", V + 1), ("ABS", 3)], None),
        ("V_PK_FMA_F16", "ENC_VOP3P", &[("VDST", 26), ("SRC0", V + 3), ("SRC1", V + 4), ("SRC2", V + 5), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1), ("NEG", 1), ("NEG_HI", 4)], None),
        ("V_FMAMK_F16", "ENC_VOP2", &[("VDST", 27), ("SRC0", V), ("VSRC1", 1)], Some(FMAMK_K as u32)),
        ("V_FMAAK_F16", "ENC_VOP2", &[("VDST", 28), ("SRC0", V), ("VSRC1", 1)], Some(FMAAK_K as u32)),
    ]);
    let (dxil, mem) = kernel_wave(&p, wave64);
    let n = if wave64 { 64 } else { 32 };
    let mut rng = Rng(0x0F16_0F16_2468_ACE1);
    // a random half: a third any bits (NaN / inf included), a third near 1 (the sums and
    // products that round), the rest special values
    let gen = |rng: &mut Rng| -> u16 {
        match rng.below(3) {
            0 => rng.next() as u16,
            1 => (rng.next() as u16 & 0x83FF) | ((13 + rng.below(5) as u16) << 10),
            _ => [0u16, 0x8000, 0x7C00, 0xFC00, 0x7E00, 0x0001, 0x8001, 0x03FF, 0x0400, 0x3C00, 0xBC00, 0x7BFF, 0x3C01, 0x1400][rng.below(14) as usize],
        }
    };
    let mut bad: Vec<String> = Vec::new();
    let mut counts: std::collections::BTreeMap<&str, (usize, usize)> = Default::default();
    for _ in 0..iters {
        let mut st = KernelState::default();
        let mut ins = Vec::new();
        for (l, r) in st.vgpr.iter_mut().take(n).enumerate() {
            let mut h: [u16; 9] = std::array::from_fn(|_| gen(&mut rng));
            // fma operands whose product is an f16 tie that c moves off it by less than binary32
            // keeps: rounded to nearest in binary32, then to f16, they go the wrong way (from a
            // CPU search against the exact reference); in the scalar and both packed halves
            if let Some(&(x, y, z)) = HARD_FMA.get(l) {
                (h[0], h[1], h[2], h[3], h[5], h[7], h[4], h[6], h[8]) = (x, y, z, x, y, z, x, y, z);
            }
            if l == HARD_FMA.len() {
                // v_fmamk_f16's tie: a·K + b = 0x3100 · 0x7162 + 0x0300
                (h[0], h[1]) = (0x3100, 0x0300);
            }
            r[0] = h[0] as u32 | (rng.next() as u32) << 16;
            r[1] = h[1] as u32 | (rng.next() as u32) << 16;
            r[2] = h[2] as u32 | (rng.next() as u32) << 16;
            r[3] = h[3] as u32 | (h[4] as u32) << 16;
            r[4] = h[5] as u32 | (h[6] as u32) << 16;
            r[5] = h[7] as u32 | (h[8] as u32) << 16;
            r[18] = r[2];
            r[19] = r[5];
            ins.push(h);
        }
        let r = runner::run(&dxil, &st, &mem).unwrap();
        for (l, h) in ins.iter().enumerate() {
            let v = &r.vgpr[l];
            // input modifiers on the bits: abs clears the sign, neg flips it (after abs)
            let (ng, ab) = (|x: u16| x ^ 0x8000, |x: u16| x & 0x7FFF);
            // (name, op, a, b, c, omod, clamp, result)
            let cases: [(&str, &str, u16, u16, u16, u64, bool, u16); 24] = [
                ("v_add_f16", "add", h[0], h[1], 0, 0, false, v[10] as u16),
                ("v_sub_f16", "sub", h[0], h[1], 0, 0, false, v[11] as u16),
                ("v_subrev_f16", "subrev", h[0], h[1], 0, 0, false, v[12] as u16),
                ("v_mul_f16", "mul", h[0], h[1], 0, 0, false, v[13] as u16),
                ("v_fma_f16", "fma", h[0], h[1], h[2], 0, false, v[14] as u16),
                ("v_pk_add_f16 lo", "add", h[3], h[5], 0, 0, false, v[15] as u16),
                ("v_pk_add_f16 hi", "add", h[4], h[6], 0, 0, false, (v[15] >> 16) as u16),
                ("v_pk_mul_f16 lo", "mul", h[3], h[5], 0, 0, false, v[16] as u16),
                ("v_pk_mul_f16 hi", "mul", h[4], h[6], 0, 0, false, (v[16] >> 16) as u16),
                ("v_pk_fma_f16 lo", "fma", h[3], h[5], h[7], 0, false, v[17] as u16),
                ("v_pk_fma_f16 hi", "fma", h[4], h[6], h[8], 0, false, (v[17] >> 16) as u16),
                ("v_fmac_f16", "fma", h[0], h[1], h[2], 0, false, v[18] as u16),
                ("v_pk_fmac_f16 lo", "fma", h[3], h[5], h[7], 0, false, v[19] as u16),
                ("v_pk_fmac_f16 hi", "fma", h[4], h[6], h[8], 0, false, (v[19] >> 16) as u16),
                ("v_add_f16 neg / abs", "add", ng(h[0]), ab(h[1]), 0, 0, false, v[20] as u16),
                ("v_fma_f16 neg / abs", "fma", ng(h[0]), ab(h[1]), ng(h[2]), 0, false, v[21] as u16),
                ("v_fma_f16 clamp", "fma", h[0], h[1], h[2], 0, true, v[22] as u16),
                ("v_add_f16 omod x2", "add", h[0], h[1], 0, 1, false, v[23] as u16),
                ("v_fma_f16 omod x0.5", "fma", h[0], h[1], h[2], 3, false, v[24] as u16),
                ("v_sub_f16 abs / abs", "sub", ab(h[0]), ab(h[1]), 0, 0, false, v[25] as u16),
                ("v_pk_fma_f16 neg lo", "fma", ng(h[3]), h[5], h[7], 0, false, v[26] as u16),
                ("v_pk_fma_f16 neg_hi", "fma", h[4], h[6], ng(h[8]), 0, false, (v[26] >> 16) as u16),
                ("v_fmamk_f16", "fma", h[0], FMAMK_K, h[1], 0, false, v[27] as u16),
                ("v_fmaak_f16", "fma", h[0], h[1], FMAAK_K, 0, false, v[28] as u16),
            ];
            for (name, op, a, b, c, omod, clamp, got) in cases {
                let e = counts.entry(name).or_default();
                e.0 += 1;
                let want = f16_reference(op, a, b, c, omod, clamp);
                let ok = match want {
                    None => got & 0x7C00 == 0x7C00 && got & 0x3FF != 0,
                    // a clamped zero: the ISA does not say which sign; either is accepted
                    Some(w) if clamp && w & 0x7FFF == 0 => got & 0x7FFF == 0,
                    Some(w) => got == w,
                };
                if !ok {
                    e.1 += 1;
                    bad.push(format!("{name}({a:#06x}, {b:#06x}{}) = {got:#06x}, want {}", if op == "fma" { format!(", {c:#06x}") } else { String::new() }, want.map_or("NaN".into(), |w| format!("{w:#06x}"))));
                }
            }
        }
    }
    println!("wave{n}: (checked, wrong) per instruction: {counts:?}");
    bad.sort();
    bad.dedup();
    for b in bad.iter().take(40) {
        println!("  {b}");
    }
    assert!(bad.is_empty(), "{} distinct f16 results differ from the exact reference", bad.len());
}
**@⁠ic3bear-ai** on GitHub · 2026-11-23 23:59 UTC · [original](https://github.com/xcl-dev/xcl/issues/111#issuecomment-7117582950) Two additions from a run on an RTX 3070. Both concern the **default** mode. The issue lists it under **Not affected**: "RNE mode, where double rounding through f32 is harmless (24 ≥ 2·11 + 2)". **1. In the default mode the f16 step is not round-to-nearest in the code as it is.** That reasoning needs the second rounding to be RNE too (and, see 2, holds for add / sub only). Without a dynamic mode, though, `to_f16_expr` emits the legacy `f32tof16`, not `f32_to_f16_rm`, and on this GPU that rounds toward zero. The comment at `to_f16_rounded_expr` says so as well. Tested on `main` at `9ab7d76`: RTX 3070 (driver 616.92), Windows 11 build 26200, debug build, DXC 1.8.2502.11. The GPU test is against an exact reference: f16 values as integers in units of 2^-24, `a + b` and `a·b + c` exact in `i128`, rounded to nearest even in integer arithmetic. It's IEEE as documented for RDNA2, not a comparison with console hardware. Results before the fix (1600 per form, wave32; the fma forms include the pinned cases from point 2): | | wrong | |---|---| | `v_add_f16` / with neg, abs / with omod ×2 | 438 / 500 / 485 | | `v_sub_f16` / `v_subrev_f16` / `v_sub_f16` with abs on both | 532 / 532 / 696 | | `v_fma_f16` / with neg, abs / clamp / omod ×0.5 | 746 / 588 / 46 / 747 | | `v_fmac_f16` / `v_fmamk_f16` / `v_fmaak_f16` | 746 / 844 / 721 | | `v_pk_add_f16` lo / hi | 452 / 435 | | `v_pk_fma_f16` lo / hi / with neg lo / neg_hi | 727 / 743 / 512 / 491 | | `v_pk_fmac_f16` lo / hi | 727 / 743 | | `v_mul_f16`, `v_pk_mul_f16` lo / hi (control) | 0 | The 40 failures the test prints are all one ulp toward zero, e.g. `v_add_f16(0x03ff, 0xbc00)` (−1 + 6.1e-5) gives `0xbbff` instead of `0xbc00`. One GPU and one driver. I don't know whether other NVIDIA GPUs or AMD's `f32tof16` truncate too. **2. For fma, RNE double rounding through f32 is not harmless, even with an RNE second step.** The 2p + 2 result covers +, −, ×, ÷ and √ of p-bit operands, not a·b + c (the product has 22 bits). Counterexample: `fma(0x3100, 0x7162, 0x0300)` = 1722.5 + 4.6e-5. The exact value is just above an f16 tie, so it must round to 1723 (`0x66bb`); through f32 the addend is lost, and the tie goes to `0x66ba`. A CPU simulation ("f32 fma, then f16 RNE" against the exact reference) found 710 such cases in 31.8 M. The inputs were biased toward ties, so that says little about the rate in real shaders. So the fma fix is needed in the default mode as well, not only the directed ones. **What I tried locally (not pushed), for #128 or whoever takes this:** round-to-odd, as the issue suggests, but in binary32 rather than f64: - TwoSum of the exact f32 product and the addend; if inexact, truncate and set the lowest bit; then `f32_to_f16_rm`. - binary32 has ≥ 11 + 2 bits, so by Boldo & Melquiond (2008) this is exact in any final mode. Results: - the CPU simulation: 0 wrong; - the GPU test: 0 wrong in all 24 forms, also with `XCL_FUZZ_ITERS=5000` (160 000 per form); - the pinned tie cases (10 for fma, one each for fmamk / fmaak): they fail with "f32 RNE, then f16" and pass with round-to-odd; - the test catches deliberately broken translations: fmamk with K as the addend, and omod ×0.5 applied as ×2, each fail only their own form; - `cargo test --workspace --no-fail-fast -- --test-threads=4`: 653 passed, 1 failed, 40 ignored, 2 SKIPPED (no wave64). The failure is a separate test of mine for partial-wave reductions (#152), which fails on `main` by design. That's a sample, not a proof. Not tested: - the directed modes; - the console's own clamp / omod semantics. The test follows the emitter's reading (omod, then clamp, on the exact result, then one rounding); a clamped NaN gives 0 (the D3D clamp rule) and a clamped −0 may give either zero; - other GPUs, and wave64; - whether other drivers keep the `precise` TwoSum as written; - the cost in shaders. The test is below, in case it helps check #128 or an AMD GPU. Comment written with Claude Code (Claude Opus 5.5) from runs on the hardware above; I checked the results. <details><summary>The test (paste into <code>crates/xcl/src/gpu/recomp/tests.rs</code>, before <code>fn hwreg_imm</code>; it uses the file's existing <code>f16_to_f64</code>, <code>Rng</code>, <code>gpu_waves</code>, <code>kernel_wave</code>, <code>prog</code>)</summary> Run with `cargo test -p xcl --lib f16_ -- --nocapture`; `XCL_FUZZ_ITERS=5000` for more cases. ```rust /// A finite f16 as an exact integer in units of 2^-24 (every f16 is a multiple of 2^-24, at most /// 65504 = 2^40 units); None for inf / NaN. fn f16_exact(h: u16) -> Option<i128> { let (e, m) = ((h >> 10) & 0x1F, (h & 0x3FF) as i128); let mag = match e { 31 => return None, 0 => m, _ => (m | 0x400) << (e - 1), }; Some(if h & 0x8000 != 0 { -mag } else { mag }) } /// An exact value in units of 2^-`u` (u >= 24) rounded to f16, to nearest, ties to even (the /// RDNA default, MODE.FP_ROUND f16 = 0), overflowing to inf; `neg_zero`: the sign of an exact /// zero. fn f16_round_exact(v: i128, u: u32, neg_zero: bool) -> u16 { let sign = if v < 0 || (v == 0 && neg_zero) { 0x8000u16 } else { 0 }; let m = v.unsigned_abs(); let bits = |x: u128| 127 - x.leading_zeros(); // 2^bits <= x // the quantum, in units: 2^-24 below the smallest normal (2^-14), else 2^(exponent - 10) let min_normal = 1u128 << (u - 14); let q_log = if m < min_normal { u - 24 } else { bits(m) - 10 }; let mut k = m >> q_log; if q_log > 0 { let (r, half) = (m & ((1u128 << q_log) - 1), 1u128 << (q_log - 1)); if r > half || (r == half && k & 1 == 1) { k += 1; } } let rounded = k << q_log; if rounded < min_normal { return sign | (rounded >> (u - 24)) as u16; } let l = bits(rounded); let e = l as i32 - u as i32 + 15; if e >= 31 { return sign | 0x7C00; } sign | (e as u16) << 10 | ((rounded >> (l - 10)) as u16 & 0x3FF) } #[test] fn f16_exact_reference_round_trips() { for h in 0..=u16::MAX { if let Some(v) = f16_exact(h) { assert_eq!(v as f64 / 2f64.powi(24), f16_to_f64(h), "{h:#06x}"); for u in [24, 48] { assert_eq!(f16_round_exact(v << (u - 24), u, h & 0x8000 != 0), h, "{h:#06x} in units of 2^-{u}"); } } } // in units of 2^-48: 1.0 = 2^48, its ulp 2^38 let (one, ulp) = (1i128 << 48, 1i128 << 38); let r = |v: i128| f16_round_exact(v, 48, false); assert_eq!(r(one + ulp / 2), 0x3C00, "a tie to the even 1.0"); assert_eq!(r(one + 3 * ulp / 2), 0x3C02, "a tie to the even 1 + 2^-9"); assert_eq!(r(one + ulp / 2 + 1), 0x3C01, "just above the tie"); assert_eq!(r(one + ulp / 2 - 1), 0x3C00, "just below the tie"); assert_eq!(r(-(one + ulp / 2 + 1)), 0xBC01); let max = f16_exact(0x7BFF).unwrap() << 24; // 65504; 65520 is the tie with 2^16 assert_eq!(r(max + (16 << 48)), 0x7C00, "65520 rounds to inf"); assert_eq!(r(max + (16 << 48) - 1), 0x7BFF); assert_eq!(r(1 << 23), 0x0000, "half the smallest subnormal: a tie to 0"); assert_eq!(r((1 << 23) + 1), 0x0001); assert_eq!(r(3 << 23), 0x0002, "1.5 subnormal quanta: a tie to the even 2"); assert_eq!(f16_round_exact(0, 48, true), 0x8000); } /// f16 arithmetic against an exact CPU reference (`f16_exact` / `f16_round_exact`) on random /// operands: v_add / sub / subrev / mul / fma / fmac / fmamk / fmaak_f16 and v_pk_add / mul / fma / /// fmac_f16 (both halves), plain and with abs / neg / neg_hi inputs, clamp and omod /// (`f16_reference`), default mode (round to nearest even, f16 denormals kept). A NaN result /// only has to be a NaN. /// One wave of operands per dispatch in 50 dispatches, or n with XCL_FUZZ_ITERS=n. #[test] fn gpu_f16_arithmetic_random() { for wave64 in gpu_waves() { f16_arithmetic_random(wave64); } } /// The literals of `f16_arithmetic_random`'s v_fmamk_f16 / v_fmaak_f16: with a = 0x3100, they /// make the first `HARD_FMA` case (b = 0x0300 for fmamk, pinned in a lane; lane 0's b = 0x7162 /// for fmaak). const FMAMK_K: u16 = 0x7162; const FMAAK_K: u16 = 0x0300; /// f16 fma operands that double rounding through binary32 gets wrong (`f16_arithmetic_random`). const HARD_FMA: [(u16, u16, u16); 10] = [ (0xa300, 0xec46, 0x001e), (0x3100, 0x7162, 0x0300), (0x9168, 0x6e4a, 0xe216), (0x4102, 0xf100, 0x8ce2), (0xe3f0, 0xc437, 0xb47f), (0x44c9, 0xf200, 0x07e4), (0x5051, 0xa0b1, 0xcbb0), (0x552a, 0x5500, 0x05aa), (0xd224, 0xd480, 0x0329), (0xd860, 0x5dd0, 0x096b), ]; /// The exactly rounded f16 result of `op` ("add", "sub", "subrev", "mul", "fma": a·b + c) on /// f16 bits (input modifiers already applied to the bits), then the output modifiers as the /// emitter applies them (`Em::out_mods`, the repo's reading of the ISA, not checked on a /// console): `omod` (1: ×2, 2: ×4, 3: ×0.5) scales the exact result, `clamp` limits it to /// [0, 1], then one rounding to nearest even. None: a NaN. With `clamp` a NaN gives 0 (the /// D3D / AMD clamp rule: assumed, not checked on a console). fn f16_reference(op: &str, a: u16, b: u16, c: u16, omod: u64, clamp: bool) -> Option<u16> { let (x, y) = if op == "subrev" { (b, a) } else { (a, b) }; let y = if op == "sub" || op == "subrev" { y ^ 0x8000 } else { y }; let neg = |h: u16| h & 0x8000 != 0; let scale = [1.0, 2.0, 4.0, 0.5][omod as usize & 3]; // exact in units of 2^-u, with the sign of an exact zero let exact = match (op, f16_exact(x), f16_exact(y), f16_exact(c)) { ("mul", Some(p), Some(q), _) => Some((p * q, 48, neg(x) != neg(y))), // a·b + c in units of 2^-48 (|a·b| <= 2^80) ("fma", Some(p), Some(q), Some(s)) => Some((p * q + (s << 24), 48, (p * q == 0 && s == 0) && neg(x) != neg(y) && neg(c))), ("fma", ..) | ("mul", ..) => None, (_, Some(p), Some(q), _) => Some((p + q, 24, p == 0 && q == 0 && neg(x) && neg(y))), _ => None, }; let Some((v, u, nz)) = exact else { // an operand is inf or NaN: f64 gives the inf or the NaN let (fx, fy, fc) = (f16_to_f64(x), f16_to_f64(y), f16_to_f64(c)); let r = match op { "mul" => fx * fy, "fma" => fx.mul_add(fy, fc), _ => fx + fy, } * scale; return match (r.is_nan(), clamp) { (true, true) => Some(0), (true, false) => None, (false, true) => Some(if r > 0.0 { 0x3C00 } else { 0 }), (false, false) => Some(if r > 0.0 { 0x7C00 } else { 0xFC00 }), }; }; let (v, u) = match omod & 3 { 1 => (v << 1, u), 2 => (v << 2, u), 3 => (v, u + 1), _ => (v, u), }; if clamp { if v <= 0 { return Some(0); } if v >= 1 << u { return Some(0x3C00); } } Some(f16_round_exact(v, u, nz)) } fn f16_arithmetic_random(wave64: bool) { let iters: usize = std::env::var("XCL_FUZZ_ITERS").ok().and_then(|s| s.parse().ok()).unwrap_or(50); // v10..v14 = add, sub, subrev, mul, fma of the low halves of v0, v1 (v2); v15..v17 = // pk_add, pk_mul, pk_fma of v3, v4 (v5); v18 += v0 · v1 (fmac, v18 = v2 before), v19 += // v3 · v4 (pk_fmac, v19 = v5 before) let p = prog(&[ ("V_ADD_F16", "ENC_VOP2", &[("VDST", 10), ("SRC0", V), ("VSRC1", 1)], None), ("V_SUB_F16", "ENC_VOP2", &[("VDST", 11), ("SRC0", V), ("VSRC1", 1)], None), ("V_SUBREV_F16", "ENC_VOP2", &[("VDST", 12), ("SRC0", V), ("VSRC1", 1)], None), ("V_MUL_F16", "ENC_VOP2", &[("VDST", 13), ("SRC0", V), ("VSRC1", 1)], None), ("V_FMA_F16", "ENC_VOP3", &[("VDST", 14), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 2)], None), ("V_PK_ADD_F16", "ENC_VOP3P", &[("VDST", 15), ("SRC0", V + 3), ("SRC1", V + 4), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1)], None), ("V_PK_MUL_F16", "ENC_VOP3P", &[("VDST", 16), ("SRC0", V + 3), ("SRC1", V + 4), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1)], None), ("V_PK_FMA_F16", "ENC_VOP3P", &[("VDST", 17), ("SRC0", V + 3), ("SRC1", V + 4), ("SRC2", V + 5), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1)], None), ("V_FMAC_F16", "ENC_VOP2", &[("VDST", 18), ("SRC0", V), ("VSRC1", 1)], None), ("V_PK_FMAC_F16", "ENC_VOP2", &[("VDST", 19), ("SRC0", V + 3), ("VSRC1", 4)], None), // modifiers: v20 = -a + |b|, v21 = -a·|b| - c, v22 = clamp(a·b + c), v23 = 2(a + b), // v24 = (a·b + c) / 2, v25 = |a| - |b|, v26 = pk_fma with -a (low) and -c (high); // literals: v27 = a·K + b (fmamk), v28 = a·b + K (fmaak) ("V_ADD_F16", "ENC_VOP3", &[("VDST", 20), ("SRC0", V), ("SRC1", V + 1), ("NEG", 1), ("ABS", 2)], None), ("V_FMA_F16", "ENC_VOP3", &[("VDST", 21), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 2), ("NEG", 5), ("ABS", 2)], None), ("V_FMA_F16", "ENC_VOP3", &[("VDST", 22), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 2), ("CLAMP", 1)], None), ("V_ADD_F16", "ENC_VOP3", &[("VDST", 23), ("SRC0", V), ("SRC1", V + 1), ("OMOD", 1)], None), ("V_FMA_F16", "ENC_VOP3", &[("VDST", 24), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 2), ("OMOD", 3)], None), ("V_SUB_F16", "ENC_VOP3", &[("VDST", 25), ("SRC0", V), ("SRC1", V + 1), ("ABS", 3)], None), ("V_PK_FMA_F16", "ENC_VOP3P", &[("VDST", 26), ("SRC0", V + 3), ("SRC1", V + 4), ("SRC2", V + 5), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1), ("NEG", 1), ("NEG_HI", 4)], None), ("V_FMAMK_F16", "ENC_VOP2", &[("VDST", 27), ("SRC0", V), ("VSRC1", 1)], Some(FMAMK_K as u32)), ("V_FMAAK_F16", "ENC_VOP2", &[("VDST", 28), ("SRC0", V), ("VSRC1", 1)], Some(FMAAK_K as u32)), ]); let (dxil, mem) = kernel_wave(&p, wave64); let n = if wave64 { 64 } else { 32 }; let mut rng = Rng(0x0F16_0F16_2468_ACE1); // a random half: a third any bits (NaN / inf included), a third near 1 (the sums and // products that round), the rest special values let gen = |rng: &mut Rng| -> u16 { match rng.below(3) { 0 => rng.next() as u16, 1 => (rng.next() as u16 & 0x83FF) | ((13 + rng.below(5) as u16) << 10), _ => [0u16, 0x8000, 0x7C00, 0xFC00, 0x7E00, 0x0001, 0x8001, 0x03FF, 0x0400, 0x3C00, 0xBC00, 0x7BFF, 0x3C01, 0x1400][rng.below(14) as usize], } }; let mut bad: Vec<String> = Vec::new(); let mut counts: std::collections::BTreeMap<&str, (usize, usize)> = Default::default(); for _ in 0..iters { let mut st = KernelState::default(); let mut ins = Vec::new(); for (l, r) in st.vgpr.iter_mut().take(n).enumerate() { let mut h: [u16; 9] = std::array::from_fn(|_| gen(&mut rng)); // fma operands whose product is an f16 tie that c moves off it by less than binary32 // keeps: rounded to nearest in binary32, then to f16, they go the wrong way (from a // CPU search against the exact reference); in the scalar and both packed halves if let Some(&(x, y, z)) = HARD_FMA.get(l) { (h[0], h[1], h[2], h[3], h[5], h[7], h[4], h[6], h[8]) = (x, y, z, x, y, z, x, y, z); } if l == HARD_FMA.len() { // v_fmamk_f16's tie: a·K + b = 0x3100 · 0x7162 + 0x0300 (h[0], h[1]) = (0x3100, 0x0300); } r[0] = h[0] as u32 | (rng.next() as u32) << 16; r[1] = h[1] as u32 | (rng.next() as u32) << 16; r[2] = h[2] as u32 | (rng.next() as u32) << 16; r[3] = h[3] as u32 | (h[4] as u32) << 16; r[4] = h[5] as u32 | (h[6] as u32) << 16; r[5] = h[7] as u32 | (h[8] as u32) << 16; r[18] = r[2]; r[19] = r[5]; ins.push(h); } let r = runner::run(&dxil, &st, &mem).unwrap(); for (l, h) in ins.iter().enumerate() { let v = &r.vgpr[l]; // input modifiers on the bits: abs clears the sign, neg flips it (after abs) let (ng, ab) = (|x: u16| x ^ 0x8000, |x: u16| x & 0x7FFF); // (name, op, a, b, c, omod, clamp, result) let cases: [(&str, &str, u16, u16, u16, u64, bool, u16); 24] = [ ("v_add_f16", "add", h[0], h[1], 0, 0, false, v[10] as u16), ("v_sub_f16", "sub", h[0], h[1], 0, 0, false, v[11] as u16), ("v_subrev_f16", "subrev", h[0], h[1], 0, 0, false, v[12] as u16), ("v_mul_f16", "mul", h[0], h[1], 0, 0, false, v[13] as u16), ("v_fma_f16", "fma", h[0], h[1], h[2], 0, false, v[14] as u16), ("v_pk_add_f16 lo", "add", h[3], h[5], 0, 0, false, v[15] as u16), ("v_pk_add_f16 hi", "add", h[4], h[6], 0, 0, false, (v[15] >> 16) as u16), ("v_pk_mul_f16 lo", "mul", h[3], h[5], 0, 0, false, v[16] as u16), ("v_pk_mul_f16 hi", "mul", h[4], h[6], 0, 0, false, (v[16] >> 16) as u16), ("v_pk_fma_f16 lo", "fma", h[3], h[5], h[7], 0, false, v[17] as u16), ("v_pk_fma_f16 hi", "fma", h[4], h[6], h[8], 0, false, (v[17] >> 16) as u16), ("v_fmac_f16", "fma", h[0], h[1], h[2], 0, false, v[18] as u16), ("v_pk_fmac_f16 lo", "fma", h[3], h[5], h[7], 0, false, v[19] as u16), ("v_pk_fmac_f16 hi", "fma", h[4], h[6], h[8], 0, false, (v[19] >> 16) as u16), ("v_add_f16 neg / abs", "add", ng(h[0]), ab(h[1]), 0, 0, false, v[20] as u16), ("v_fma_f16 neg / abs", "fma", ng(h[0]), ab(h[1]), ng(h[2]), 0, false, v[21] as u16), ("v_fma_f16 clamp", "fma", h[0], h[1], h[2], 0, true, v[22] as u16), ("v_add_f16 omod x2", "add", h[0], h[1], 0, 1, false, v[23] as u16), ("v_fma_f16 omod x0.5", "fma", h[0], h[1], h[2], 3, false, v[24] as u16), ("v_sub_f16 abs / abs", "sub", ab(h[0]), ab(h[1]), 0, 0, false, v[25] as u16), ("v_pk_fma_f16 neg lo", "fma", ng(h[3]), h[5], h[7], 0, false, v[26] as u16), ("v_pk_fma_f16 neg_hi", "fma", h[4], h[6], ng(h[8]), 0, false, (v[26] >> 16) as u16), ("v_fmamk_f16", "fma", h[0], FMAMK_K, h[1], 0, false, v[27] as u16), ("v_fmaak_f16", "fma", h[0], h[1], FMAAK_K, 0, false, v[28] as u16), ]; for (name, op, a, b, c, omod, clamp, got) in cases { let e = counts.entry(name).or_default(); e.0 += 1; let want = f16_reference(op, a, b, c, omod, clamp); let ok = match want { None => got & 0x7C00 == 0x7C00 && got & 0x3FF != 0, // a clamped zero: the ISA does not say which sign; either is accepted Some(w) if clamp && w & 0x7FFF == 0 => got & 0x7FFF == 0, Some(w) => got == w, }; if !ok { e.1 += 1; bad.push(format!("{name}({a:#06x}, {b:#06x}{}) = {got:#06x}, want {}", if op == "fma" { format!(", {c:#06x}") } else { String::new() }, want.map_or("NaN".into(), |w| format!("{w:#06x}")))); } } } } println!("wave{n}: (checked, wrong) per instruction: {counts:?}"); bad.sort(); bad.dedup(); for b in bad.iter().take(40) { println!(" {b}"); } assert!(bad.is_empty(), "{} distinct f16 results differ from the exact reference", bad.len()); } ``` </details>
Author
Owner

@⁠joeypercia on GitHub · 2026-11-24 02:36 UTC · original

Two answers to the open points from @⁠ic3bear-ai's default-mode report above, measured on main cb868b2, Windows 11 Pro 26200, Rust 1.100.0 MSVC, debug, DXC 1.8.2502.11:

1. AMD and Ada truncate too. f32tof16 rounds toward zero on an RTX 4070 Ti (616.56) and on an AMD RDNA2 iGPU (Ryzen 7 7800X3D, 26.11.2), wave64 and wave32.

2. It's wider than add / sub / fma. Every f16 result that goes through to_f16_expr truncates in the default mode, including the unary ones. A GPU test against an exact reference (inexact results only, 100 dispatches, counts as [nearest even, toward zero, neither]):

RTX 4070 Ti, wave32 RDNA2, wave64
v_add_f16 61 / 1219 / 0 0 / 2532 / 0
v_sqrt_f16 0 / 723 / 0 0 / 1439 / 0
v_rcp_f16 0 / 1438 / 0 0 / 2884 / 0
v_rsq_f16 1 / 751 / 0 0 / 1498 / 0
v_exp_f16 0 / 1671 / 0 0 / 3336 / 0
v_log_f16 0 / 728 / 0 0 / 1455 / 0
v_ldexp_f16 0 / 1156 / 0 0 / 2339 / 0
v_mul_f16 (control, #166) 1635 / 0 / 0 3221 / 0 / 0

(The 61 nearest-even v_add_f16 results on the 4070 Ti are sums that are inexact in f32 already.)

Fix. to_f16_expr takes f32_to_f16_rm(e, 0u) in the default mode too, the helper #166 already uses for v_mul_f16:

fn to_f16_expr(dynamic_rm: bool, e: &str) -> String {
    to_f16_rounded_expr(dynamic_rm, e)
}

With it, every count above becomes nearest even on both GPUs. cargo test --workspace --no-fail-fast: 686 passed, 0 failed, 41 ignored on both (the existing s_round_mode and fma f16 tests included). The test, gpu_f16_results_round_to_nearest_even_by_default, fails on main and passes with the fix.

Not covered: the fma double rounding from point 2 above, which needs the exact sum (#128's TwoSum work); the directed modes (#128); v_sin/v_cos_f16 and the packed forms; and the other f32tof16 call sites in emit.rs (exports and d16 stores, lines ~1662, 2108, 2333, 5166), which I haven't checked. No regression run, since I have no title.

@⁠ic3bear-ai, @⁠gbuyssens: happy for either of you to fold this into your work, or I can open it as a PR with the test if someone with a title can add the xcl-smoke runs.

AI use: Claude Code (Claude Opus 5.5) wrote the test, the fix and this comment; all numbers are from the runs described.

**@⁠joeypercia** on GitHub · 2026-11-24 02:36 UTC · [original](https://github.com/xcl-dev/xcl/issues/111#issuecomment-7120304391) Two answers to the open points from @⁠ic3bear-ai's default-mode report above, measured on `main` `cb868b2`, Windows 11 Pro 26200, Rust 1.100.0 MSVC, debug, DXC 1.8.2502.11: **1. AMD and Ada truncate too.** `f32tof16` rounds toward zero on an RTX 4070 Ti (616.56) and on an AMD RDNA2 iGPU (Ryzen 7 7800X3D, 26.11.2), wave64 and wave32. **2. It's wider than add / sub / fma.** Every f16 result that goes through `to_f16_expr` truncates in the default mode, including the unary ones. A GPU test against an exact reference (inexact results only, 100 dispatches, counts as [nearest even, toward zero, neither]): | | RTX 4070 Ti, wave32 | RDNA2, wave64 | |---|---|---| | `v_add_f16` | 61 / **1219** / 0 | 0 / **2532** / 0 | | `v_sqrt_f16` | 0 / **723** / 0 | 0 / **1439** / 0 | | `v_rcp_f16` | 0 / **1438** / 0 | 0 / **2884** / 0 | | `v_rsq_f16` | 1 / **751** / 0 | 0 / **1498** / 0 | | `v_exp_f16` | 0 / **1671** / 0 | 0 / **3336** / 0 | | `v_log_f16` | 0 / **728** / 0 | 0 / **1455** / 0 | | `v_ldexp_f16` | 0 / **1156** / 0 | 0 / **2339** / 0 | | `v_mul_f16` (control, #166) | **1635** / 0 / 0 | **3221** / 0 / 0 | (The 61 nearest-even `v_add_f16` results on the 4070 Ti are sums that are inexact in f32 already.) **Fix.** `to_f16_expr` takes `f32_to_f16_rm(e, 0u)` in the default mode too, the helper #166 already uses for `v_mul_f16`: ```rust fn to_f16_expr(dynamic_rm: bool, e: &str) -> String { to_f16_rounded_expr(dynamic_rm, e) } ``` With it, every count above becomes nearest even on both GPUs. `cargo test --workspace --no-fail-fast`: 686 passed, 0 failed, 41 ignored on both (the existing `s_round_mode` and fma f16 tests included). The test, `gpu_f16_results_round_to_nearest_even_by_default`, fails on `main` and passes with the fix. **Not covered:** the fma double rounding from point 2 above, which needs the exact sum (#128's TwoSum work); the directed modes (#128); `v_sin`/`v_cos_f16` and the packed forms; and the other `f32tof16` call sites in `emit.rs` (exports and d16 stores, lines ~1662, 2108, 2333, 5166), which I haven't checked. No regression run, since I have no title. @⁠ic3bear-ai, @⁠gbuyssens: happy for either of you to fold this into your work, or I can open it as a PR with the test if someone with a title can add the `xcl-smoke` runs. AI use: Claude Code (Claude Opus 5.5) wrote the test, the fix and this comment; all numbers are from the runs described.
Author
Owner

@⁠joeypercia on GitHub · 2026-11-24 03:18 UTC · original

Correction to my comment above: the to_f16_expr change I proposed is not safe on its own. As #655 (@⁠acaracargo) shows, it regresses v_fract_f16: fract_f clamps the f32 result to just below 1.0, and narrowing that to nearest even lands on 1.0 in f16 (x = −2⁻¹⁴ gives 0x3c00 instead of 0x3bff). With truncation the clamp happened to survive. So the default-mode fix also needs v_fract_f16 to clamp after the narrowing (to 0x3bff), and #655's test should go in alongside it. My measurements above still stand; only the one-line fix as written needs that extra case.

AI use: Claude Code (Claude Opus 5.5) wrote this; the regression itself is from #655's run, I haven't re-measured it.

**@⁠joeypercia** on GitHub · 2026-11-24 03:18 UTC · [original](https://github.com/xcl-dev/xcl/issues/111#issuecomment-7120965651) Correction to my comment above: the `to_f16_expr` change I proposed is not safe on its own. As #655 (@⁠acaracargo) shows, it regresses `v_fract_f16`: `fract_f` clamps the f32 result to just below 1.0, and narrowing that to nearest even lands on 1.0 in f16 (x = −2⁻¹⁴ gives `0x3c00` instead of `0x3bff`). With truncation the clamp happened to survive. So the default-mode fix also needs `v_fract_f16` to clamp after the narrowing (to `0x3bff`), and #655's test should go in alongside it. My measurements above still stand; only the one-line fix as written needs that extra case. AI use: Claude Code (Claude Opus 5.5) wrote this; the regression itself is from #655's run, I haven't re-measured it.
Author
Owner

@⁠acaracargo on GitHub · 2026-11-24 03:24 UTC · original

Thanks for pointing this out. That's exactly why I included the fract edge case in #655. Glad the test was useful! @⁠joeypercia

**@⁠acaracargo** on GitHub · 2026-11-24 03:24 UTC · [original](https://github.com/xcl-dev/xcl/issues/111#issuecomment-7121054473) Thanks for pointing this out. That's exactly why I included the fract edge case in #655. Glad the test was useful! @⁠joeypercia
Author
Owner

@⁠Anon64 on GitHub · 2026-11-24 06:28 UTC · original

@⁠joeypercia if you open the PR for the default-mode to_f16_expr fix (with the v_fract_f16 clamp and #655's test), I can make the two scripts/smoke.ps1 runs on a retail title, the PR's head commit and the main it is based on, and post the xcl-smoke blocks there for Regression run, as for #672. Same machine as then: RTX 3060 12 GB, wave32.

It overlaps #696, which sends only add / sub through the same helper: your change covers those too, so if it lands first, #696 can be closed.

Written with Claude Code (Claude Opus 5.5).

**@⁠Anon64** on GitHub · 2026-11-24 06:28 UTC · [original](https://github.com/xcl-dev/xcl/issues/111#issuecomment-7123965334) @⁠joeypercia if you open the PR for the default-mode `to_f16_expr` fix (with the `v_fract_f16` clamp and #655's test), I can make the two `scripts/smoke.ps1` runs on a retail title, the PR's head commit and the `main` it is based on, and post the `xcl-smoke` blocks there for **Regression run**, as for #672. Same machine as then: RTX 3060 12 GB, wave32. It overlaps #696, which sends only add / sub through the same helper: your change covers those too, so if it lands first, #696 can be closed. Written with Claude Code (Claude Opus 5.5).
Author
Owner

@⁠joeypercia on GitHub · 2026-11-24 06:40 UTC · original

@⁠Anon64 thanks, it's up as #842: to_f16_expr rounds to nearest even in the default mode, v_fract_f16 keeps its result at 0x3BFF (the #655 case, with its own test that fails without the clamp), and it covers #696's add / sub. Head feaeb7b, based on main beaa245; whenever you have time for the two xcl-smoke runs.

Written with Claude Code (Claude Opus 5.5).

**@⁠joeypercia** on GitHub · 2026-11-24 06:40 UTC · [original](https://github.com/xcl-dev/xcl/issues/111#issuecomment-7124169150) @⁠Anon64 thanks, it's up as #842: `to_f16_expr` rounds to nearest even in the default mode, `v_fract_f16` keeps its result at `0x3BFF` (the #655 case, with its own test that fails without the clamp), and it covers #696's add / sub. Head `feaeb7b`, based on `main` `beaa245`; whenever you have time for the two `xcl-smoke` runs. Written with Claude Code (Claude Opus 5.5).
Author
Owner

@⁠malzaharhub-ctrl on GitHub · 2026-11-24 23:36 UTC · original

I've been working on the default round-to-nearest-even F16 FMA double-rounding issue described in this discussion.

I now have a local implementation covering:

  • v_fma_f16
  • v_fmac_f16
  • v_fmamk_f16
  • v_fmaak_f16
  • v_pk_fma_f16
  • v_pk_fmac_f16

The implementation uses TwoSum error recovery and sticky-aware final binary16 rounding.

Testing performed on an AMD Radeon RX 7900 XTX:

  • 4,800 random finite binary16 FMA results compared against an exact integer-based RNE reference across Wave32 and Wave64.
  • Known double-rounding regression cases.
  • Additional overflow-boundary regression.
  • All six FMA variants covered.
  • 127 GPU recompiler tests passed, 17 ignored.
  • Full scripts/test.ps1 completed successfully (exit code 0).

I have noticed the ongoing work in PR #128 and PR #842. My implementation addresses the default-RNE FMA single-rounding gap, rather than replacing the directed-rounding work.

Would you prefer this to be developed as an extension of PR #128, or submitted as a separate PR coordinated with the existing changes?

I haven't committed or pushed the local implementation yet.

AI assistance disclosure: AI assisted with implementation development, test design and test scripts. I applied the changes locally and ran the reported tests on the hardware stated above.

**@⁠malzaharhub-ctrl** on GitHub · 2026-11-24 23:36 UTC · [original](https://github.com/xcl-dev/xcl/issues/111#issuecomment-7147596471) I've been working on the default round-to-nearest-even F16 FMA double-rounding issue described in this discussion. I now have a local implementation covering: - `v_fma_f16` - `v_fmac_f16` - `v_fmamk_f16` - `v_fmaak_f16` - `v_pk_fma_f16` - `v_pk_fmac_f16` The implementation uses TwoSum error recovery and sticky-aware final binary16 rounding. Testing performed on an AMD Radeon RX 7900 XTX: - 4,800 random finite binary16 FMA results compared against an exact integer-based RNE reference across Wave32 and Wave64. - Known double-rounding regression cases. - Additional overflow-boundary regression. - All six FMA variants covered. - 127 GPU recompiler tests passed, 17 ignored. - Full `scripts/test.ps1` completed successfully (exit code 0). I have noticed the ongoing work in PR #128 and PR #842. My implementation addresses the default-RNE FMA single-rounding gap, rather than replacing the directed-rounding work. Would you prefer this to be developed as an extension of PR #128, or submitted as a separate PR coordinated with the existing changes? I haven't committed or pushed the local implementation yet. **AI assistance disclosure:** AI assisted with implementation development, test design and test scripts. I applied the changes locally and ran the reported tests on the hardware stated above.
This discussion has been locked. Commenting is limited to contributors.
No description provided.