From 9fff1ee7324567cd7a2d814079d7d528c5338c3f Mon Sep 17 00:00:00 2001 From: Rachel Amber <77208679+Holastor@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:02:07 +0500 Subject: [PATCH 1/2] shader: lower v_div_fmas_f32, reject unverified v_fma_f16 and v_div_scale_f32 Lower v_div_fmas_f32 using double precision with Knuth 2Sum remainder tracking to guarantee strict single-rounding, avoiding double-rounding midpoint tie errors and preventing premature underflow before scaling by 2^32. Reject unverified v_fma_f16 and v_div_scale_f32 instructions until native RDNA2 readback confirms binary16 rounding, high-half preservation, and prescaling behavior. Add WARP draw tests with integer readback covering midpoint single-rounding (0x3fc00001 / 0x4fc00001), cancellation (-2^-46), pre-scale underflow (2^-151 -> 2^-119), denormal scale boundary (2^-127 -> 2^-95), and normal arithmetic with clamp, accompanied by four negative mutation controls. --- docs/experiments.md | 36 +++++ tests/pixel_aot_check.py | 224 ++++++++++++++++++++++++++++++ tests/rdna2_tools_check.py | 69 +++++++++ tools/pixel_aot.py | 88 ++++++++++++ tools/scan_unsupported_shaders.py | 1 + 5 files changed, 418 insertions(+) diff --git a/docs/experiments.md b/docs/experiments.md index 1850cf62..52188e47 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -4345,3 +4345,39 @@ ctest --preset dev --no-tests=error -R '^pixel_aot_(warp|hardware)$' -V Python-only controls check HLSL wave-intrinsic translation, register tracking, and scanner recognition without requiring a GPU. + +## Vector float math division FMA and unverified prescaling + +`pixel_aot` rejects `v_div_scale_f32` and `v_fma_f16` (including explicit `_e64` +spellings). Both instructions remain recognized by the scanner, but are not +reported as supported lowerings until verified by source-built native RDNA +readbacks. For `v_div_scale_f32`, a denominator-only threshold cannot reproduce its +numerator-dependent result and VCC flag (e.g., denominator 1 with numerator 2^100 +takes the RDNA 2 opcode 365 exponent-gap branch scaling by 2^64 with VCC set). +For `v_fma_f16`, the halfway case `0x3c69 * 0x3faa + 0x89d1` distinguishes single +rounding to binary16 (`0x4039`) from intermediate rounding through float32 (`0x403a`), +and destination high-half preservation remains unmeasured without a source-built +native RDNA readback. + +`v_div_fmas_f32` evaluates `div_fmas32(src0, src1, src2, vcc)` using double precision +with Knuth 2Sum remainder tracking to guarantee strict single-rounding across WARP and +desktop hardware targets, avoiding double-rounding midpoint tie errors and preventing +premature float32 underflow before scaling by 2^32 (`4294967296.0`) when VCC is true. +An offscreen draw through the integer readback target (`check_valu_div_fmas_draw`) with +runtime constant-buffer inputs tests both VCC conditions and clamping across five cases: +- Midpoint single-rounding: `(0x3f800001, 0x3fc00000, 0x8d800000)` produces exact sum + 1.5 + 3*2^-24 - 2^-100 strictly below the midpoint, rounding down to `0x3fc00001` + (`0x4fc00001` scaled by 2^32), whereas uncorrected double rounding rounds to even + (`0x3fc00002` / `0x4fc00002`); +- Cancellation: `(0x3f800001, 0x3f7ffffe, 0xbf800000)` produces exact product + addend + -2^-46 (`0xa8800000` unscaled, `0xb8800000` scaled by 2^32), where unfused float32 `mad` + rounds `1 - 2^-46` prematurely to 1.0 yielding zero; +- Pre-scale underflow: `(0x00800000, 0x33000000, 0)` produces 2^-151 before scale, which + would underflow float32 to zero if rounded early, but scales to 2^-119 (`0x04000000`); +- Denormal scale boundary: 2^-126 * 0.5 = 2^-127 (`0x00400000`) before scaling by 2^32 to + 2^-95 (`0x10000000`); +- Normal arithmetic: 2.0 * 0.5 + 1.0 = 2.0 (`0x40000000` unscaled, `0x50000000` scaled, + `0x3f800000` clamped). +Four negative controls verify that omitting the 2^32 scale, substituting unfused `mad`, +omitting the 2Sum midpoint correction (double-rounding), or flushing intermediate +subnormals (`ftz`) report pixel mismatches under `--check-pixel-case`. diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index f160cdf0..d4a6202c 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -2868,6 +2868,20 @@ def check_scalar_select64_draw(directory, compiler, renderer, backend): run_pixel_batch(renderer, backend, shader, scc_cases) +def valu_div_fmas_program(): + return with_constants([ + "v_mov_b32_e32 v19, 2.0", + "v_mov_b32_e32 v20, 4.0", + "v_mov_b32_e32 v21, v19", + "v_cmp_lt_f32 vcc_lo, 1.0, 0", + "v_div_fmas_f32 v12, v21, 0.5, 1.0", + "v_div_fmas_f32 v13, v21, 0.5, 1.0 clamp", + "v_cmp_lt_f32 vcc_lo, 0, 1.0", + "v_div_fmas_f32 v14, 1.0, 2.0, 3.0", + "v_div_fmas_f32 v15, 0x00800000, 0.5, 0", + ]) + + SCALAR64_SETS = ( # (a_lo, a_hi, b_lo, b_hi, sh_lo, sh_hi, bfm_w, bfm_off, bfe_src, bfe_ctrl_a, bfe_ctrl_b, alt) (0x89abcdef, 0x91234567, 0x55aa55aa, 0x7fffffff, 5, 37, 12, 28, 0x9a345f50, 0x00080004, 0x00100018, 0x55aa55aa), @@ -8318,6 +8332,118 @@ def check_controls(directory): must_reject(translate, with_constants(["v_madak_f32_dpp v12, v13, v14, 0x3e800000 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf"])) must_reject(translate, with_constants(["v_madmk_f32_sdwa v12, v13, 0x3e800000, v14 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:DWORD"])) + # 3-operand vector float math: v_div_fmas_f32 and rejection of unverified v_fma_f16 / v_div_scale_f32 + for opcode in ("v_fma_f16", "v_fma_f16_e64"): + for insn in ( + f"{opcode} v22, v19, v20, v21", + f"{opcode} v22, v19, v20, v21 op_sel:[0,0,0]", + f"{opcode} v22, v19, v20, v21 clamp", + ): + try: + translate(with_constants([insn])) + except ValueError as error: + assert "Unverified v_fma_f16" in str(error), error + else: + raise AssertionError(f"Unverified {insn} was accepted") + + # Rounding controls for binary16: independent case where RNE and RTZ differ. + val_diff = 1.0 + 2.0 ** -11 + 2.0 ** -12 + rne_packed = struct.unpack("> 13) & 1u)) >> 13; return sign | min(((exponent - 113u) << 10) + rounded, 0x7c00u); } +// v_div_fmas_f32: fused multiply-add with conditional 2^32 scale when condition is true. +// Uses double precision with Knuth 2Sum remainder tracking to guarantee strict single-rounding +// across all backends (including WARP), resolving float32 midpoint ties faithfully and preventing +// premature underflow before scaling. +float div_fmas32_core(float s0, float s1, float s2, bool cond, bool clamp_res) { + precise double p = (double)s0 * (double)s1; + precise double s = p + (double)s2; + precise double v = s - p; + precise double err = (p - (s - v)) + ((double)s2 - v); + + double scale = cond ? 4294967296.0 : 1.0; + precise double s_sc = s * scale; + precise double err_sc = err * scale; + + uint u0, u1; + asuint(s_sc, u0, u1); + uint exp = (u1 >> 20) & 0x7ffu; + if (exp >= 897u && exp <= 1150u) { + if ((u0 & 0x1fffffffu) == 0x10000000u && err_sc != 0.0) { + if ((s_sc > 0.0 && err_sc > 0.0) || (s_sc < 0.0 && err_sc < 0.0)) { + if (++u0 == 0u) ++u1; + } else { + if (u0-- == 0u) --u1; + } + s_sc = asdouble(u0, u1); + } + } else if (exp < 897u && exp >= 874u) { + uint shift = 897u - exp; + uint mask = (1u << (29u - shift)) - 1u; + uint guard = 1u << (28u - shift); + if ((u0 & mask) == guard && err_sc != 0.0) { + if ((s_sc > 0.0 && err_sc > 0.0) || (s_sc < 0.0 && err_sc < 0.0)) { + if (++u0 == 0u) ++u1; + } else { + if (u0-- == 0u) --u1; + } + s_sc = asdouble(u0, u1); + } + } + if (clamp_res) { + s_sc = clamp(s_sc, 0.0, 1.0); + } + return (float)s_sc; +} +float div_fmas32(float s0, float s1, float s2, bool cond) { + return div_fmas32_core(s0, s1, s2, cond, false); +} +float div_fmas32_clamp(float s0, float s1, float s2, bool cond) { + return div_fmas32_core(s0, s1, s2, cond, true); +} """ @@ -1594,6 +1644,23 @@ def parse_fma_mix(rest): if any(hi and not f16 for f16, hi in zip(op_sel, op_sel_hi)): raise ValueError("High-half selection requires an f16 operand") return operands, op_sel, op_sel_hi, clamp + + +def parse_div_fmas(rest): + parts_ = rest.split(", ") + if len(parts_) != 3: + raise ValueError("Invalid div_fmas operand count") + last_op, _, mod_text = parts_[-1].partition(" ") + operands = [*parts_[:-1], last_op] + clamp = False + for mod in mod_text.split(): + if mod == "clamp": + if clamp: + raise ValueError("Duplicate clamp modifier") + clamp = True + else: + raise ValueError(f"Unsupported div_fmas modifier {mod}") + return operands, clamp def dot_word(token, scalar, vector, pending, sample_dest, *, allow_f16=False): """Return a 32-bit uint HLSL expression for one VOP3P dot-product source operand.""" if allow_f16 and token in INLINE_F16: @@ -3238,6 +3305,27 @@ def sample_coord(reg): packed = f"(mix{i}_p & 0x0000ffffu) | (pack16_rne(mix{i}) << 16)" vector[dst] = f"alu{i}" lines.append(f" precise float alu{i} = asfloat({packed});") + elif re.fullmatch(r"v_fma_f16(?:_e64)? .+", line): + raise ValueError("Unverified v_fma_f16 binary16 FMA semantics") + elif re.fullmatch(r"v_div_scale_f32(?:_e64)? .+", line): + raise ValueError("Unverified v_div_scale_f32 prescaling and VCC semantics") + elif m := match(r"v_div_fmas_f32(?:_e64)? (v\d+), (.+)"): + dst, rest = m.groups() + if mask != "entry" or not 0 <= int(dst[1:]) <= 255: + raise ValueError("Invalid div_fmas operation") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + tokens, clamp = parse_div_fmas(rest) + condition = scalar.get("vcc") + if condition is None: + condition = scalar.get("vcc_lo") + if condition is None or not isinstance(condition, tuple) or condition[0] != "condition": + raise ValueError("Divide FMA requires a tracked VCC condition") + values = [fp_operand(t, scalar, vector, pending, sample_dest) for t in tokens] + func = "div_fmas32_clamp" if clamp else "div_fmas32" + expr = f"{func}({values[0]}, {values[1]}, {values[2]}, {condition[1]})" + vector[dst] = f"alu{i}" + lines.append(f" precise float alu{i} = {expr};") elif m := match(r"(v_dot2_f32_f16|v_dot2_i32_i16|v_dot2_u32_u16|v_dot4_i32_i8|v_dot4_u32_u8|v_dot8_i32_i4|v_dot8_u32_u4) (v\d+), (.+)"): op, dst, rest = m.groups() if mask != "entry" or not 0 <= int(dst[1:]) <= 255: diff --git a/tools/scan_unsupported_shaders.py b/tools/scan_unsupported_shaders.py index d5451638..572f6a37 100644 --- a/tools/scan_unsupported_shaders.py +++ b/tools/scan_unsupported_shaders.py @@ -146,6 +146,7 @@ rf"v_cmp_class_f16_e64\s+{PIXEL_LANE_MASK},\s+{F16_MOD},\s+(?:-?\d+|0x[0-9a-f]{{1,8}}|[vs]\d+)", rf"v_cndmask_b32(?:_e32|_e64)?\s+v\d+,\s+[^,]+,\s+[^,]+,\s+{PIXEL_LANE_MASK}", r"v_fma_mix(?:_f32|lo_f16|hi_f16)\s+v\d+,\s+.+", + r"v_div_fmas_f32(?:_e64)?\s+v\d+,\s+[^,\s]+,\s+[^,\s]+,\s+[^,\s]+(?:\s+clamp)?", r"(?:v_dot2_f32_f16|v_dot2_i32_i16|v_dot2_u32_u16|v_dot4_i32_i8|v_dot4_u32_u8|v_dot8_i32_i4|v_dot8_u32_u4)\s+v\d+,\s+.+", r"v_cvt_pkrtz_f16_f32_e32\s+v\d+,\s+v\d+,\s+v\d+", r"v_cvt_u32_f32_e32 v\d+, (?:[vs]\d+|0x[0-9a-f]{1,8})", From 766276f3d3d7827ed23bdcd98479539e145ca31d Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Mon, 23 Nov 2026 21:27:21 +0800 Subject: [PATCH 2/2] Recognize midpoints throughout the binary32 subnormal range --- tests/pixel_aot_check.py | 7 ++++++- tools/pixel_aot.py | 38 +++++++++++++++++++------------------- 2 files changed, 25 insertions(+), 20 deletions(-) diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index d4a6202c..87ae7cfc 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -10300,6 +10300,11 @@ def check_valu_div_fmas_draw(directory, compiler, renderer, backend): ("midpoint", (0x3f800001, 0x3fc00000, 0x8d800000), (0x3fc00001, 0x3f800000, 0x4fc00001, 0x3f800000), "pass"), # Cancellation: exact product plus addend is -2^-46 ("cancel", (0x3f800001, 0x3f7ffffe, 0xbf800000), (0xa8800000, 0x00000000, 0xb8800000, 0x00000000), "pass"), + # An exact product of 2^-150 minus 2^-196 falls short of increasing the odd subnormal. + ("subnormal-low-word", (0x1a000001, 0x19fffffe, 0x00400001), + (0x00400001, 0x00400001, 0x10000003, 0x10000003), "pass"), + ("subnormal-high-word", (0x1a000001, 0x19fffffe, 0x00040001), + (0x00040001, 0x00040001, 0x0e000030, 0x0e000030), "pass"), # Pre-scale underflow: 2^-126 * 2^-25 = 2^-151 before scale, 2^-119 after scale ("underflow", (0x00800000, 0x33000000, 0x00000000), (0x00000000, 0x00000000, 0x04000000, 0x04000000), "pass"), # Scale boundary: 2^-126 * 0.5 = 2^-127 intermediate subnormal, 2^-95 after scale @@ -10345,7 +10350,7 @@ def check_valu_div_fmas_draw(directory, compiler, renderer, backend): # Negative control 3: double rounding without 2Sum midpoint correction. mut_src3 = directory / "valu_div_fmas_mut_double_round.hlsl" mut_cso3 = directory / "valu_div_fmas_mut_double_round.cso" - mut_hlsl3 = hlsl_text.replace("if ((u0 & 0x1fffffffu) == 0x10000000u && err_sc != 0.0)", "if (false)") + mut_hlsl3 = hlsl_text.replace("if (midpoint && err_sc != 0.0)", "if (false)") assert mut_hlsl3 != hlsl_text mut_src3.write_text(mut_hlsl3, encoding="ascii") compile_shader(compiler, mut_src3, mut_cso3) diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index 2642b6cd..016b43e9 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -453,27 +453,27 @@ def comparison_resources(state): uint u0, u1; asuint(s_sc, u0, u1); uint exp = (u1 >> 20) & 0x7ffu; - if (exp >= 897u && exp <= 1150u) { - if ((u0 & 0x1fffffffu) == 0x10000000u && err_sc != 0.0) { - if ((s_sc > 0.0 && err_sc > 0.0) || (s_sc < 0.0 && err_sc < 0.0)) { - if (++u0 == 0u) ++u1; - } else { - if (u0-- == 0u) --u1; - } - s_sc = asdouble(u0, u1); + // Binary32 subnormals retain a fixed 2^-149 spacing. The guard may + // move into the high word or become the implicit bit at 2^-150. + bool midpoint = false; + if (exp >= 873u && exp <= 1150u) { + uint discarded = exp < 897u ? 926u - exp : 29u; + if (discarded <= 32u) { + uint guard = 1u << (discarded - 1u); + midpoint = (u0 & (guard | (guard - 1u))) == guard; + } else { + uint guard = 1u << (discarded - 33u); + uint significand_hi = (u1 & 0x000fffffu) | 0x00100000u; + midpoint = u0 == 0u && (significand_hi & (guard | (guard - 1u))) == guard; } - } else if (exp < 897u && exp >= 874u) { - uint shift = 897u - exp; - uint mask = (1u << (29u - shift)) - 1u; - uint guard = 1u << (28u - shift); - if ((u0 & mask) == guard && err_sc != 0.0) { - if ((s_sc > 0.0 && err_sc > 0.0) || (s_sc < 0.0 && err_sc < 0.0)) { - if (++u0 == 0u) ++u1; - } else { - if (u0-- == 0u) --u1; - } - s_sc = asdouble(u0, u1); + } + if (midpoint && err_sc != 0.0) { + if ((s_sc > 0.0 && err_sc > 0.0) || (s_sc < 0.0 && err_sc < 0.0)) { + if (++u0 == 0u) ++u1; + } else { + if (u0-- == 0u) --u1; } + s_sc = asdouble(u0, u1); } if (clamp_res) { s_sc = clamp(s_sc, 0.0, 1.0);