From eb3524f6bac892d558fc0096dc721736bc4e11d7 Mon Sep 17 00:00:00 2001 From: legacy-code-archaeologist <359844974+legacy-code-archaeologist@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:48:49 +0100 Subject: [PATCH] shader: lower v_fma_f16, v_fmac_f16, v_fmamk_f16 and v_fmaak_f16 in direct compute Lower v_fma_f16 (VOP3), v_fmac_f16 (VOP2/VOP3A), v_fmamk_f16 (VOP2) and v_fmaak_f16 (VOP2) in DirectCompute::float_alu() using the shared single-rounded binary16 FMA helper fused_half_rne() (#3151) while preserving D[31:16]. Supports VOP3 abs/neg/clamp, enforces the default binary16 MODE contract via half_binary, refuses DPP/SDWA/omod/high-half op_sel/third-source modifiers on v_fmac_f16, updates the unlowered placeholder in tests/native_f16_alu_check.py from v_fmac_f16 to v_pk_fmac_f16, and adds @dx.op.unaryBits.i32(i32 33, ...) evaluation to native_f16_alu_check.py's IR interpreter. Fixes #3186 Refs #2935 AI-assisted. --- docs/experiments/native-direct-fma-f16.md | 39 +++ src/gfx1013_direct_compute.inl | 58 ++++- tests/cmake/native_fma_f16.cmake | 19 ++ tests/native_f16_alu_check.py | 6 +- tests/native_fma_f16_check.py | 298 ++++++++++++++++++++++ 5 files changed, 418 insertions(+), 2 deletions(-) create mode 100644 docs/experiments/native-direct-fma-f16.md create mode 100644 tests/cmake/native_fma_f16.cmake create mode 100644 tests/native_fma_f16_check.py diff --git a/docs/experiments/native-direct-fma-f16.md b/docs/experiments/native-direct-fma-f16.md new file mode 100644 index 0000000000..1a6078e817 --- /dev/null +++ b/docs/experiments/native-direct-fma-f16.md @@ -0,0 +1,39 @@ +# Scalar binary16 FMA in the direct C++ compute path (#3186) + +`src/gfx1013_direct_compute.inl` now lowers `v_fma_f16` (VOP3), `v_fmac_f16` (VOP2/VOP3A), `v_fmamk_f16` (VOP2), and +`v_fmaak_f16` (VOP2) in the direct C++ compute path (`DirectCompute::float_alu()`): + +- **Exact single-rounded FMA (`fused_half_rne()`):** Reuses the shared 32-bit integer `fused_half_rne(a, b, c)` helper + (introduced in #3151 for `v_pk_fma_f16`) so `a * b + c` computes an exact product, aligns the addend with a sticky + bit, and rounds once to nearest-even binary16 rather than double-rounding through binary32. +- **High-half preservation:** Every operation reads `16`-bit sources (preserving `S0..S2[15:0]` / `K[15:0]` / `D[15:0]`), + writes the result into `D[15:0]`, and keeps `D[31:16]` unchanged. +- **Modifiers & MODE contract:** Supports VOP3 `abs`, `neg`, and `clamp` (`[0.0, 1.0]` saturation); refuses DPP, SDWA, + `omod`, high-half `op_sel`, third-source modifiers/`src2` on `v_fmac_f16_e64`, and non-default FP16 MODE writes + (`half_binary` in `DirectCompute::lower()`). +- **Test adjustment:** Updated the unlowered-instruction refusal placeholder in + [`tests/native_f16_alu_check.py`](../../tests/native_f16_alu_check.py) from `v_fmac_f16` to `v_pk_fmac_f16`, and added + `@dx.op.unaryBits.i32(i32 33, ...)` (`FirstbitHi`) evaluation to its IR interpreter so `native_fma_f16_ir` evaluates + `fused_half_rne()` directly. + +## Fixture + +[`tests/native_fma_f16_check.py`](../../tests/native_fma_f16_check.py) via +[`tests/cmake/native_fma_f16.cmake`](../../tests/cmake/native_fma_f16.cmake) (`native_fma_f16_ir`, +`native_fma_f16_controls`, `native_fma_f16_hardware`): + +- **IR (`native_fma_f16_ir`):** Evaluates lane 0 across 41 cases (all 4 `#2073` single-rounding vs double-rounding tie + witnesses across all 4 instructions, SGPR/literal/inline-float/inline-int sources, `dst = src0` overlap, VOP3 + `abs`/`neg`/`clamp`, signed zeros, exact cancellation, subnormals, `diff_e >= 30` sticky-bit midpoint, underflow + ties, overflow, `Inf`/`NaN`) against an exact `fractions.Fraction` reference, plus 12 refusals. +- **Controls (`native_fma_f16_controls`):** Compiles the full 41-case shader to DXIL via `compile_dxil` and verifies all + 12 refusals. +- **Hardware (`native_fma_f16_hardware`):** Replays all 41 cases via `native_store_replay --direct`. + +Measured on 27.11.2026, `main` `c45bf9ab` plus this change, Windows 10.0.26100 (`dev` preset): `native_fma_f16_ir` +(41 cases + 12 refusals), `native_fma_f16_controls`, `native_f16_alu_ir`, `native_packed_f16_controls`, +`native_packed_f16_pixel_warp`, `native_packed_f16_pixel_hardware`, all 57 `^native_.*_(controls|ir)$` tests, and +`tests/docs_links_check.py` passed; `native_fma_f16_hardware` skipped (`77`, +`Intel(R) HD Graphics 530` `31.0.101.2111`: requires shader model 6.6 with wave32, so GPU compute readback is +not measured). Five broken-lowering sensitivity checks (`zero_high_half`, `drop_sticky`, `swap_fmamk_fmaak`, +`drop_clamp`, `drop_inf_cancel_nan`) each failed `native_fma_f16_ir` (exit `1`). diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index fa752100e8..0d927b9e9f 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -1531,6 +1531,58 @@ struct DirectCompute { ir.binary("and", rounded, "65535"))); return true; } + if (n == "v_fma_f16" || n == "v_fmac_f16" || n == "v_fmamk_f16" || n == "v_fmaak_f16") { + if (graphics_input) + return false; + if (i.dpp_control || permuted) + refuse(i.pc, "unsupported " + string(n) + " DPP form"); + if (i.subword) + refuse(i.pc, "unsupported " + string(n) + " SDWA form"); + if (i.scale) + refuse(i.pc, "unsupported " + string(n) + " omod"); + if (i.wide && (i.a & 0x7800)) + refuse(i.pc, "unsupported " + string(n) + " high-half op_sel"); + if (n == "v_fmac_f16" && i.wide && (((i.abs | i.neg) & 4) || i.src[2])) + refuse(i.pc, "unsupported v_fmac_f16 third-source modifier"); + if (!half_mode_known || ((mode_bits ^ 0xf0u) & 0x8000ccu)) + refuse(i.pc, "unsupported binary16 rounding or denormal mode"); + auto half_bits = [&](unsigned j) { + const unsigned r = i.src[j]; + string bits; + if (r >= 240 && r <= 248) { + constexpr unsigned halves[]{0x3800, 0xb800, 0x3c00, 0xbc00, 0x4000, + 0xc000, 0x4400, 0xc400, 0x3118}; + bits = to_string(halves[r - 240]); + } else if (r == 255) + bits = to_string(i.literal & 65535u); + else if (r >= 128 && r <= 192) + bits = to_string((r - 128) & 65535u); + else if (r >= 193 && r <= 208) + bits = to_string((192u - r) & 65535u); + else + bits = ir.binary("and", operand32(i, r), "65535"); + if (i.abs & (1u << j)) + bits = ir.binary("and", bits, "32767"); + if (i.neg & (1u << j)) + bits = ir.binary("xor", bits, "32768"); + return bits; + }; + auto a = half_bits(0); + auto b = n == "v_fmamk_f16" ? to_string(i.literal & 65535u) : half_bits(1); + auto c = n == "v_fma_f16" ? half_bits(2) + : n == "v_fmac_f16" ? ir.binary("and", read(i.dst), "65535") + : n == "v_fmamk_f16" ? half_bits(1) + : to_string(i.literal & 65535u); + auto result = fused_half_rne(a, b, c); + if (i.clamp) { + auto nan = cmp("ugt", ir.binary("and", result, "32767"), "31744"); + auto low = ir.value("or i1 " + nan + ", " + cmp("ne", ir.binary("and", result, "32768"), "0")); + result = select(low, "0", select(cmp("ugt", result, "15359"), "15360", result)); + } + auto kept = ir.binary("and", read(i.dst), "4294901760"); + vector_write(i.dst, ir.binary("or", kept, ir.binary("and", result, "65535"))); + return true; + } const auto rule = alu_rules.find(n); const bool byte_to_float = n.size() == 16 && n.substr(0, 15) == "v_cvt_f32_ubyte" && n.back() >= '0' && n.back() <= '3'; @@ -3362,7 +3414,11 @@ struct DirectCompute { op.name == "v_cvt_f16_u16" || op.name == "v_cvt_f16_i16" || op.name == "v_cvt_u16_f16" || - op.name == "v_cvt_i16_f16") + op.name == "v_cvt_i16_f16" || + op.name == "v_fma_f16" || + op.name == "v_fmac_f16" || + op.name == "v_fmamk_f16" || + op.name == "v_fmaak_f16") half_binary = true; if (op.name == "s_round_mode" || op.name == "s_denorm_mode" || op.name == "s_setreg_b32" || op.name == "s_setreg_imm32_b32") diff --git a/tests/cmake/native_fma_f16.cmake b/tests/cmake/native_fma_f16.cmake new file mode 100644 index 0000000000..12e85d19ec --- /dev/null +++ b/tests/cmake/native_fma_f16.cmake @@ -0,0 +1,19 @@ +# v_fma_f16, v_fmac_f16, v_fmamk_f16 and v_fmaak_f16 in the direct C++ compute path. +# Named to sort after native_f16_alu.cmake so native_compute_ir_dump is already defined. +if(TARGET native_compute_ir_dump AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_fma_f16_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_fma_f16_check.py" ir + "$") + set_tests_properties(native_fma_f16_ir PROPERTIES TIMEOUT 60) +endif() +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_fma_f16_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_fma_f16_check.py" controls + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_fma_f16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_fma_f16_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_fma_f16_check.py" hardware + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_fma_f16_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/native_f16_alu_check.py b/tests/native_f16_alu_check.py index 49d6c3a080..f80c1dac56 100644 --- a/tests/native_f16_alu_check.py +++ b/tests/native_f16_alu_check.py @@ -274,7 +274,7 @@ def refusal_programs(): programs.append(([0xb98005c1] + add + [0xbf810000], 'unsupported binary16 rounding or denormal mode')) programs.append(([0xbfa40001] + add + [0xbf810000], 'unsupported compute control instruction s_round_mode')) programs.append(([0xbfa5000c] + add + [0xbf810000], 'unsupported compute control instruction s_denorm_mode')) - programs.append((vop2(0x36, 3, 257, 2) + [0xbf810000], 'direct DXIL lowering for v_fmac_f16')) + programs.append((vop2(0x3c, 3, 257, 2) + [0xbf810000], 'direct DXIL lowering for v_pk_fmac_f16')) programs.append((vop2(0x3a, 3, 257, 2) + [0xbf810000], 'direct DXIL lowering for v_min_f16')) return programs @@ -458,6 +458,10 @@ def bits_of(token): elif 'legacyF16ToF32' in rhs: argument = re.search(r'i32 (\S+)\)$', rhs) values[name] = ('float', _widen(_i32(argument.group(1), values))) + elif 'unaryBits.i32(i32 33,' in rhs: + argument = re.search(r'i32 33,\s*i32 ([^,\s\)]+)\)', rhs) + x = _i32(argument.group(1), values) & 0xffffffff + values[name] = ('i32', (32 - x.bit_length()) if x else 0xffffffff) elif 'createHandleFromBinding' in rhs or 'annotateHandle' in rhs: values[name] = ('handle', 0) else: diff --git a/tests/native_fma_f16_check.py b/tests/native_fma_f16_check.py new file mode 100644 index 0000000000..afb4d8e704 --- /dev/null +++ b/tests/native_fma_f16_check.py @@ -0,0 +1,298 @@ +"""Direct compute binary16 FMA (v_fma_f16, v_fmac_f16, v_fmamk_f16, v_fmaak_f16).""" +from fractions import Fraction +import math +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request +import native_f16_alu_check as F +from native_scalar_lds_check import scalar, sop1 + + +HI_DST = 0xABCD0000 +HI_A = 0xBEEF0000 +HI_B = 0x789A0000 +HI_C = 0x13570000 + +OP_FMAC, OP_FMAMK, OP_FMAAK = 0x36, 0x37, 0x38 +OP_FMA_VOP3 = 0x34B +OP_FMAC_VOP3 = 0x136 + + +def vop3_tern(op, vdst, s0, s1, s2, *, abs_mask=0, neg=0, clamp=0, omod=0, op_sel=0): + w0 = (0xD4000000 | ((op & 0x3FF) << 16) | ((clamp & 1) << 15) | + ((op_sel & 0xF) << 11) | ((abs_mask & 7) << 8) | (vdst & 0xFF)) + w1 = ((neg & 7) << 29) | ((omod & 3) << 27) | ((s2 & 0x1FF) << 18) | ((s1 & 0x1FF) << 9) | (s0 & 0x1FF) + return [w0, w1] + + +def half_to_fraction(bits): + bits &= 0xFFFF + sign = -1 if (bits & 0x8000) else 1 + exp = (bits >> 10) & 0x1F + mant = bits & 0x3FF + if exp == 0x1F: + return None + if exp == 0: + return Fraction(sign * mant, 1 << 24) + return Fraction(sign * (1024 + mant), 1 << (25 - exp)) if exp < 25 else Fraction(sign * (1024 + mant) * (1 << (exp - 25)), 1) + + +def round_fraction_f16(q, neg_zero=False): + if q == 0: + return 0x8000 if neg_zero else 0x0000 + sign = 0x8000 if q < 0 else 0x0000 + aq = abs(q) + # Overflow boundary: 65520 = 65504 + 16 -> +inf + if aq >= Fraction(65520, 1): + return sign | 0x7C00 + # Find largest e >= -24 such that 2^e <= aq, or subnormal grid 2^-24. + if aq < Fraction(1, 1 << 14): + scaled = aq * (1 << 24) + n = scaled.numerator // scaled.denominator + rem = scaled - n + if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and (n & 1)): + n += 1 + return sign | n + # Normal range: 2^e <= aq < 2^(e+1) + num, den = aq.numerator, aq.denominator + e = num.bit_length() - den.bit_length() + if aq < (Fraction(1 << e, 1) if e >= 0 else Fraction(1, 1 << (-e))): + e -= 1 + elif aq >= (Fraction(1 << (e + 1), 1) if e + 1 >= 0 else Fraction(1, 1 << (-(e + 1)))): + e += 1 + shift = e - 10 + step = Fraction(1 << shift, 1) if shift >= 0 else Fraction(1, 1 << (-shift)) + scaled = aq / step + n = scaled.numerator // scaled.denominator + rem = scaled - n + if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and (n & 1)): + n += 1 + if n == 2048: + n = 1024 + e += 1 + if e > 15: + return sign | 0x7C00 + return sign | ((e + 15) << 10) | (n & 0x3FF) + + +def ref_fma16(a_bits, b_bits, c_bits, *, abs_mask=0, neg=0, clamp=False): + a = F.modified(a_bits, abs_mask, neg, 0) + b = F.modified(b_bits, abs_mask, neg, 1) + c = F.modified(c_bits, abs_mask, neg, 2) + + def cls(h): + e, f = (h >> 10) & 0x1F, h & 0x3FF + return e == 0x1F and f != 0, e == 0x1F and f == 0, (h & 0x7FFF) == 0, (h >> 15) & 1 + + an, ai, az, sa = cls(a) + bn, bi, bz, sb = cls(b) + cn, ci, cz, sc = cls(c) + sp = sa ^ sb + if an or bn or cn or (ai and bz) or (bi and az) or ((ai or bi) and ci and sp != sc): + out = 0x7E00 + elif ai or bi: + out = (sp << 15) | 0x7C00 + elif ci: + out = (sc << 15) | 0x7C00 + else: + exact = half_to_fraction(a) * half_to_fraction(b) + half_to_fraction(c) + out = round_fraction_f16(exact, neg_zero=(az or bz) and cz and sp == 1 and sc == 1) + if clamp: + if (out & 0x7FFF) > 0x7C00 or (out & 0x8000): + out = 0 + elif out > 0x3BFF: + out = 0x3C00 + return out + + +# #2073 double-rounding tie witnesses: f32 a*b+c rounded to f16 disagrees with exact single-rounded FMA. +TIE_WITNESSES_2073 = ( + (0x4A54, 0x1EF4, 0x4E2D, 0x4E33), + (0x51EA, 0xBF3E, 0x1D5F, 0xD55B), + (0x2BD5, 0xBE83, 0x4528, 0x450F), + (0x3915, 0x387A, 0x4B71, 0x4B9F), +) + + +def cases(): + items = [] + + def add(name, code, want, dst=3): + items.append((name, code, want, dst)) + + # 1. All four #2073 single-rounding witnesses across v_fma_f16, v_fmac_f16, v_fmamk_f16, v_fmaak_f16. + for a, b, c, want in TIE_WITNESSES_2073: + assert ref_fma16(a, b, c) == want + assert F.packed_half_rne( + struct.unpack('=30 midpoint', 0x4200, 0x5156, 0x0001, 0, 0, False), # 128.0625 + 2^-24 -> 0x5801 (drop sticky -> 0x5800) + ('subnormal tie to even', 0x0001, 0x3800, 0x0000, 0, 0, False), # 2^-24 * 0.5 = 2^-25 -> 0 + ('subnormal above half', 0x0003, 0x3800, 0x0000, 0, 0, False), # 3 * 2^-25 -> 0x0001 + ('overflow +inf', 0x7BFF, 0x4000, 0x3C00, 0, 0, False), + ('overflow -inf', 0xFBFF, 0x4000, 0x3C00, 0, 0, False), + ('clamp negative', 0xC000, 0x4000, 0x3C00, 0, 0, True), + ('clamp >1.0', 0x4000, 0x4000, 0x3C00, 0, 0, True), + ('clamp 0.5', 0x3800, 0x3C00, 0x0000, 0, 0, True), + ('clamp +inf', 0x7C00, 0x3C00, 0x0000, 0, 0, True), + ('clamp qNaN', 0x7E00, 0x3C00, 0x0000, 0, 0, True), + ('0 * inf -> qNaN', 0x0000, 0x7C00, 0x3C00, 0, 0, False), + ('+inf + -inf -> qNaN', 0x7C00, 0x3C00, 0xFC00, 0, 0, False), + ('+inf + 1 -> +inf', 0x7C00, 0x3C00, 0x3C00, 0, 0, False), + ('-inf + 1 -> -inf', 0xFC00, 0x3C00, 0x3C00, 0, 0, False), + ('abs/neg all 3', 0xC000, 0xC200, 0x3C00, 5, 6, False), + ] + for label, a, b, c, absm, negm, cl in edges: + add(label, + F.mov(1, HI_A | a) + F.mov(2, HI_B | b) + F.mov(4, HI_C | c) + F.mov(3, HI_DST | 0x4444) + + vop3_tern(OP_FMA_VOP3, 3, 257, 258, 260, abs_mask=absm, neg=negm, clamp=int(cl)), + ref_fma16(a, b, c, abs_mask=absm, neg=negm, clamp=cl)) + + assert len(items) < F.STRIDE + return items + + +def emit_program(items): + code = [sop1(3, 20, 4), sop1(3, 21, 128), 0xF408080A, 0xFA000020, + scalar(0x1E, 7, 5, 128 + F.SHIFT), F.vmove(8, 7), sop1(3, 126, 129), + 0xBFA40000, 0xBFA5000F, 0xBA800881, 0] + want = [] + for index, (_, snippet, expected, dst) in enumerate(items): + code += snippet + F.store(4 * index, dst) + want.append(HI_DST | expected) + code.append(0xBF810000) + return code, want + + +def same_word(got, want): + if (got >> 16) != (HI_DST >> 16): + return False + return F.same_binary16(got & 0xFFFF, want & 0xFFFF) + + +def refusal_programs(): + fma = vop3_tern(OP_FMA_VOP3, 3, 257, 258, 260) + fmac = F.vop2(OP_FMAC, 3, 257, 2) + return [ + (F.vop2(OP_FMAC, 3, 250, 2) + [0xFF00B101, 0xBF810000], 'unsupported DPP arithmetic'), + (F.vop2(OP_FMAC, 3, 249, 2) + [0x06060601, 0xBF810000], 'unimplemented direct SDWA operand profile'), + (vop3_tern(OP_FMA_VOP3, 3, 257, 258, 260, omod=1) + [0xBF810000], 'unsupported v_fma_f16 omod'), + (vop3_tern(OP_FMAC_VOP3, 3, 257, 258, 0, omod=1) + [0xBF810000], 'unsupported v_fmac_f16 omod'), + (vop3_tern(OP_FMA_VOP3, 3, 257, 258, 260, op_sel=1) + [0xBF810000], 'unsupported v_fma_f16 high-half op_sel'), + (vop3_tern(OP_FMAC_VOP3, 3, 257, 258, 0, op_sel=8) + [0xBF810000], 'unsupported v_fmac_f16 high-half op_sel'), + (vop3_tern(OP_FMAC_VOP3, 3, 257, 258, 0, neg=4) + [0xBF810000], 'unsupported v_fmac_f16 third-source modifier'), + (vop3_tern(OP_FMAC_VOP3, 3, 257, 258, 260) + [0xBF810000], 'unsupported v_fmac_f16 third-source modifier'), + ([0xBFA4000C] + fma + [0xBF810000], 'unsupported binary16 rounding or denormal mode'), + ([0xBFA50000] + fmac + [0xBF810000], 'unsupported binary16 rounding or denormal mode'), + ([0xBA8005C1, 1] + fma + [0xBF810000], 'unsupported binary16 rounding or denormal mode'), + ([0xB98005C1] + fmac + [0xBF810000], 'unsupported binary16 rounding or denormal mode'), + ] + + +def ir(dumper): + items = cases() + code, want = emit_program(items) + refusals = refusal_programs() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = F.dump(dumper, work, code, 'fma-f16') + assert run.returncode == 0, run.stderr + stores = sorted(F.interpret(run.stdout)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] + bad = [(i, items[i][0], hex(got), hex(exp)) + for i, ((_, got), exp) in enumerate(zip(stores, want)) if not same_word(got, exp)] + assert not bad, bad[:8] + for idx, (refused, why) in enumerate(refusals): + r = F.dump(dumper, work, refused, f'refused-{idx}') + assert r.returncode != 0 and why in r.stderr, (why, r.returncode, r.stderr) + print(f'native_fma_f16 IR: {len(want)} single-rounded conversions match Fraction reference; {len(refusals)} refusals matched') + return 0 + + +def controls(cli, sdk, work, root): + items = cases() + code, want = emit_program(items) + marker = request(work, root, code) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert 'legacyF32ToF16' not in dump, dump + + refusals = refusal_programs() + for n, (prog_words, why) in enumerate(refusals): + m = request(work, root, prog_words) + o = m.with_suffix(f'.refused{n}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode != 0 and why in r.stderr, (why, r.stdout, r.stderr) + assert not o.exists(), o + + print(f'native_fma_f16 controls: compiled {len(want)} FMA cases cleanly to DXIL; verified {len(refusals)} refusals') + return 0 + + +def hardware(replay, sdk, work, root): + items = cases() + code, want = emit_program(items) + marker = request(work, root, code) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + words_out = list(struct.unpack(f'<{F.WORDS}I', output.read_bytes())) + for group in range(F.GROUPS): + head = F.BASE + group * F.STRIDE + got = words_out[head:head + len(want)] + bad = [(i, items[i][0], hex(a), hex(b)) for i, (a, b) in enumerate(zip(got, want)) if not same_word(a, b)] + assert not bad, (group, bad[:8]) + words_out[F.BASE:F.BASE + len(want)] = [0] * len(want) + words_out[F.BASE + F.STRIDE:F.BASE + F.STRIDE + len(want)] = [0] * len(want) + assert all(w == F.SENTINEL for w in words_out if w != 0), 'guard overwritten' + print(f'native_fma_f16 hardware: {len(want)} FMA cases matched across {F.GROUPS} groups') + return 0 + + +def main(mode, tool, sdk=None): + if mode == 'ir': + return ir(tool) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:]))