diff --git a/docs/experiments/f16-alu-direct.md b/docs/experiments/f16-alu-direct.md index fdb5709542..0307e7dcf6 100644 --- a/docs/experiments/f16-alu-direct.md +++ b/docs/experiments/f16-alu-direct.md @@ -26,7 +26,7 @@ Each of these is a named diagnostic: `s_round_mode` and `s_denorm_mode` that leave the f16 fields at that contract, and that leave the f32 fields unchanged, are accepted. A write that changes an f32 rounding or denormal field keeps the previous control-instruction refusal. A guest branch together with a MODE write makes the contract unprovable and is refused with the rounding diagnostic. -fma, fmac, fmamk, fmaak, min, max, ldexp, the min3/max3/med3 forms, div_fixup, VOP1 and the `v_pk` forms stay on the generic direct-lowering diagnostic. The fixture checks `v_fmac_f16` and `v_min_f16`. +For the plain scalar-half forms, fma, fmac, fmamk, fmaak, min, max, ldexp, the min3/max3/med3 forms, div_fixup and VOP1 stay on the generic direct-lowering diagnostic. The fixture checks `v_fmac_f16` and `v_min_f16`. VOP3P arithmetic has a [separate experiment](native-packed-f16.md). ## Linux diff --git a/docs/experiments/native-packed-f16.md b/docs/experiments/native-packed-f16.md new file mode 100644 index 0000000000..69d9a6611b --- /dev/null +++ b/docs/experiments/native-packed-f16.md @@ -0,0 +1,60 @@ +# Packed binary16 arithmetic in direct Pixel and Compute DXIL + +The direct compiler lowers the VOP3P `v_pk_add_f16`, `v_pk_mul_f16`, and +`v_pk_fma_f16` instructions. Each result half has independent source-half +selectors and input negation. The packed word uses the normal EXEC-masked +destination write. The lowering accepts numeric registers, literal words, and +inline zero. + +ADD and MUL widen the inputs, use binary32 arithmetic, then round to binary16 +with the existing integer nearest-even conversion. FMA forms the exact 22-bit +product and aligns the addend in integer arithmetic. Alignment keeps a sticky +bit for distant operands, where cancellation cannot reach the discarded bits. +The intermediate keeps 24 significant bits, with its last bit set to one when +discarded bits are nonzero. This round-to-odd step preserves which side of a +binary16 midpoint the exact sum fell on. The final nearest-even conversion +therefore agrees with a single binary16 rounding. + +The supported MODE preserves subnormals, rounds to nearest even, and leaves +`FP16_OVFL` clear. Clamp, unsupported source encodings, and undetermined or +unsupported MODE keep explicit refusals. NaN results use the canonical +`0x7e00` half from the project's arithmetic reference. NaN payload behavior +has not been measured on an RDNA2 device. + +## Reproduction + +Run from an x64 Visual Studio Developer PowerShell with DXC and Python configured. + +```powershell +$env:XBOX2WINDOWS_ADAPTER = 'RTX 4070' +cmake --preset dev +cmake --build --preset dev --target compile_dxil native_store_replay offscreen_check +ctest --preset dev --no-tests=error -j 1 -R '^native_packed_f16_' -V +``` + +The [source-built fixture](../../tests/native_packed_f16_check.py) compares +both halves against the [exact rational model](../../tests/f16_packed_model.py). +Compute checks full and sparse EXEC readbacks, including inactive lanes and +buffer guards. Pixel checks the same FMA cases and alternates ADD and MUL in +the other two output channels. Two FMA cases distinguish one binary16 rounding +from a nearest-even binary32 intermediate. The first stores `0x3e053e01`, +where the double-rounded version would store `0x3e043e02`. The second stores +`0x6201be01` instead of `0x6202be02`. Compute replay requires wave32. + +On Windows 11 with SDK 10.0.26100 and DXC 1.9.2602.17, the RTX 4070 +(driver `32.0.16.2124`) matched all 2,064 Compute readback words in each of +the full and sparse dispatches. Pixel matched all ten cases on both the RTX +4070 and WARP (`10.0.26100.10068`). The local WARP adapter exposes four +lanes, so the wave32 Compute replay used the RTX 4070. + +## References + +- [AMD RDNA 2 ISA, section 12.10](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) + and [LLVM 21.1.0 GFX1030 assembly syntax](https://releases.llvm.org/21.1.0/docs/AMDGPU/AMDGPUAsmGFX1030.html#vop3p) + document the operand fields. The LLVM release is `3623fe661ae35c6c80ac221f14d85be76aa870f1`, Apache-2.0 WITH LLVM-exception. +- [Boldo and Melquiond, *Emulation of a FMA and Correctly Rounded Sums*](https://guillaume.melquiond.fr/doc/08-tc.pdf) + explains rounding to odd and the subsequent nearest-even conversion. +- [shadPS4 #4354](https://github.com/shadps4-emu/shadPS4/pull/4354) demonstrates + the corresponding translation scope. Observed 2026-11-27 at + `34b35b526e3bfbb8a6f22c11035cb051174ac6f1`, GPL-2.0. The code and + fixtures in this repository were developed independently. diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index fb6e462aea..4f0016f4b8 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -1062,8 +1062,128 @@ struct DirectCompute { h = select(nan, ir.binary("or", ir.binary("lshr", frac, "13"), "32256"), h); return ir.binary("or", h, sign); } + static bool packed_f16_arithmetic(Name n) { + return n == "v_pk_add_f16" || n == "v_pk_mul_f16" || n == "v_pk_fma_f16"; + } + string fused_half_rne(const string &a, const string &b, const string &c) { + auto both = [&](const string &x, const string &y) { return ir.value("and i1 " + x + ", " + y); }; + auto either = [&](const string &x, const string &y) { return ir.value("or i1 " + x + ", " + y); }; + auto clz = [&](const string &value) { + // FirstbitHi counts from the most significant bit. OR-ing in bit + // zero leaves every nonzero count unchanged and bounds zero's shift. + return ir.invoke("i32", "unaryBits.i32", 33, + {{"i32", ir.binary("or", value, "1")}}, "nounwind readnone"); + }; + struct Half { string magnitude, sign, significand, exponent; }; + auto decode = [&](const string &word) { + auto magnitude = ir.binary("and", word, "32767"); + auto field = ir.binary("lshr", magnitude, "10"); + auto normal = cmp("ne", field, "0"); + auto hidden = select(normal, "1024", "0"); + return Half{magnitude, ir.binary("and", word, "32768"), + ir.binary("or", ir.binary("and", word, "1023"), hidden), + ir.binary("sub", select(normal, field, "1"), "25")}; + }; + auto x = decode(a), y = decode(b), z = decode(c); + auto product_sign = ir.binary("xor", x.sign, y.sign); + auto product = ir.binary("mul", x.significand, y.significand); + auto product_exp = ir.binary("add", x.exponent, y.exponent); + + // Normalize both exact terms at bit 30, leaving space for a carry. + // The product has at most 22 bits and the addend at most 11. Close + // exponents therefore align exactly, including after cancellation. + auto normalize = [&](const string &mantissa, const string &exponent) { + auto leading = clz(mantissa); + return std::pair{ + ir.binary("shl", mantissa, ir.binary("sub", leading, "1")), + select(cmp("eq", mantissa, "0"), "-128", + ir.binary("add", exponent, ir.binary("sub", "31", leading)))}; + }; + auto [product_mantissa, product_top] = normalize(product, product_exp); + auto [addend_mantissa, addend_top] = normalize(z.significand, z.exponent); + auto product_larger = either(cmp("sgt", product_top, addend_top), + both(cmp("eq", product_top, addend_top), cmp("uge", product_mantissa, addend_mantissa))); + auto big = select(product_larger, product_mantissa, addend_mantissa); + auto smaller_mantissa = select(product_larger, addend_mantissa, product_mantissa); + auto big_exp = select(product_larger, product_top, addend_top); + auto small_exp = select(product_larger, addend_top, product_top); + auto sign = select(product_larger, product_sign, z.sign); + auto distance = ir.binary("sub", big_exp, small_exp); + auto shift = select(cmp("ult", distance, "31"), distance, "31"); + auto aligned = ir.binary("lshr", smaller_mantissa, shift); + // A wide alignment has no significant cancellation. Retain a sticky + // bit for discarded data so a nearby midpoint still rounds correctly. + auto sticky = cmp("ne", ir.binary("shl", aligned, shift), smaller_mantissa); + aligned = ir.binary("or", aligned, ir.value("zext i1 " + sticky + " to i32")); + auto same_sign = cmp("eq", product_sign, z.sign); + auto magnitude = select(same_sign, ir.binary("add", big, aligned), ir.binary("sub", big, aligned)); + auto leading = clz(magnitude); + auto normalized = ir.binary("shl", magnitude, leading); + auto exponent = ir.binary("sub", ir.binary("add", big_exp, "128"), leading); + + // Encode the exact sum rounded to odd at binary32 precision. If any + // bits were lost, set the last retained bit. The final binary16 + // nearest-even conversion then sees the correct side of every tie. + auto odd = cmp("ne", ir.binary("and", normalized, "255"), "0"); + auto significand = ir.binary("or", ir.binary("lshr", normalized, "8"), + ir.value("zext i1 " + odd + " to i32")); + auto binary32 = ir.binary("or", ir.binary("shl", sign, "16"), + ir.binary("or", ir.binary("shl", exponent, "23"), ir.binary("and", significand, "8388607"))); + auto zero = select(both(cmp("eq", product, "0"), cmp("eq", z.magnitude, "0")), + ir.binary("and", product_sign, z.sign), "0"); + auto finite = select(cmp("eq", magnitude, "0"), zero, packed_half_rne(binary32)); + + auto x_inf = cmp("eq", x.magnitude, "31744"), y_inf = cmp("eq", y.magnitude, "31744"); + auto product_inf = either(x_inf, y_inf), c_inf = cmp("eq", z.magnitude, "31744"); + auto invalid_product = either(both(x_inf, cmp("eq", y.magnitude, "0")), + both(y_inf, cmp("eq", x.magnitude, "0"))); + auto invalid_sum = both(both(product_inf, c_inf), cmp("ne", product_sign, z.sign)); + auto nan = either(either(cmp("ugt", x.magnitude, "31744"), cmp("ugt", y.magnitude, "31744")), + either(cmp("ugt", z.magnitude, "31744"), either(invalid_product, invalid_sum))); + return select(nan, "32256", + select(product_inf, ir.binary("or", product_sign, "31744"), select(c_inf, c, finite))); + } + void packed_f16_alu(const Inst &i) { + const bool fused = i.name == "v_pk_fma_f16"; + if (i.enc != Encoding::Mix || i.clamp || (!fused && (i.src[2] || (i.a & 0x2400) || (i.neg & 4)))) + refuse(i.pc, "unsupported packed binary16 arithmetic encoding"); + if (!half_mode_known || ((mode_bits ^ 0xf0u) & 0x8000ccu)) + refuse(i.pc, "unsupported binary16 rounding or denormal mode"); + std::array words; + for (unsigned j = 0; j < (fused ? 3u : 2u); ++j) { + unsigned r = i.src[j]; + if (r > 105 && r < 256 && r != 128 && r != 255) + refuse(i.pc, "unsupported packed binary16 arithmetic source"); + words[j] = operand32(i, r); + } + auto lane = [&](unsigned selectors, unsigned negate) { + auto operand = [&](unsigned j) { + auto bits = (selectors & (1u << j)) ? ir.binary("lshr", words[j], "16") + : ir.binary("and", words[j], "65535"); + return (negate & (1u << j)) ? ir.binary("xor", bits, "32768") : bits; + }; + auto a = operand(0), b = operand(1); + if (fused) + return fused_half_rne(a, b, operand(2)); + auto widen = [&](const string &bits) { + return ir.invoke("float", "legacyF16ToF32", 131, {{"i32", bits}}, "nounwind readnone"); + }; + const auto op = i.name == "v_pk_mul_f16" ? "fmul" : "fadd"; + auto result = ir.value(string(op) + " float " + widen(a) + ", " + widen(b)); + auto bits = packed_half_rne(ir.value("bitcast float " + result + " to i32")); + return select(cmp("ugt", ir.binary("and", bits, "32767"), "31744"), "32256", bits); + }; + // In VOP3P, NEG_HI occupies the ABS field. OP_SEL_HI[2] lives in word 0. + auto low = lane((i.a >> 11) & 7, i.neg); + auto high = lane(((i.b >> 27) & 3) | ((i.a >> 12) & 4), i.abs); + vector_write(i.dst, ir.binary("or", low, ir.binary("shl", high, "16"))); + } bool float_alu(const Inst &i, const string *permuted = nullptr) { auto n = i.name; + if (packed_f16_arithmetic(n)) { + packed_f16_alu(i); + return true; + } if ((i.subword || (!i.wide && !i.dpp_control && !permuted)) && (n == "v_cvt_f16_f32" || n == "v_cvt_f32_f16")) { if (i.scale || i.clamp || i.src_sext[0]) @@ -3003,6 +3123,8 @@ struct DirectCompute { if (op.name == "s_round_mode" || op.name == "s_denorm_mode" || op.name == "s_setreg_b32" || op.name == "s_setreg_imm32_b32") mode_write = true; + if (packed_f16_arithmetic(op.name)) + half_binary = true; if (op.branch() && op.op != 2) conditional = true; } diff --git a/tests/cmake/native_packed_f16.cmake b/tests/cmake/native_packed_f16.cmake new file mode 100644 index 0000000000..c2a6ce8939 --- /dev/null +++ b/tests/cmake/native_packed_f16.cmake @@ -0,0 +1,16 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND + EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_packed_f16_check.py") + add_test(NAME native_packed_f16_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_f16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_packed_f16_compute_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" compute "$" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_f16_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_packed_f16_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" pixel "$" "${DXC_BIN_DIR}" "$" ${adapter}) + set_tests_properties(native_packed_f16_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/native_packed_f16_check.py b/tests/native_packed_f16_check.py new file mode 100644 index 0000000000..aea34cac6a --- /dev/null +++ b/tests/native_packed_f16_check.py @@ -0,0 +1,213 @@ +"""Run direct packed binary16 arithmetic against an exact-rational reference.""" +from dataclasses import dataclass +from fractions import Fraction +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from f16_packed_model import h2f, half_op, round_exact +from native_direct_container_check import patched_pixel +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_scalar_lds_check import sop1 +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl + +OPS = {'add': 0x0f, 'mul': 0x10, 'fma': 0x0e} +GUARD = 0x69696969 +INACTIVE = 0x13579bdf +PROLOGUE = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + + +@dataclass(frozen=True) +class Case: + a: int + b: int + c: int + low: int = 0 + high: int = 7 + neg_lo: int = 0 + neg_hi: int = 0 + + @property + def inputs(self): + return self.a, self.b, self.c + + +CASES = ( + # Both products are binary16 midpoints. A minimum subnormal addend + # changes the exact rounded result but vanishes on a binary32 tie. + Case(0x3c033c01, 0x3e003e00, 0x00018001), + Case(0x6001bc01, 0x3e003e00, 0x80010001), + Case(0x04000001, 0x38003800, 0x03ff0000), + Case(0x7bfffbff, 0x40004000, 0x80000000), + Case(0xbc003c00, 0x3c003c00, 0x3c00bc00), + Case(0x80008000, 0xbc003c00, 0x80008000), + Case(0x7c00fc00, 0x00003c00, 0x3c007c00), + Case(0x7d017e01, 0x3c003c00, 0x3c003c00), + Case(0x42003c00, 0xc4004000, 0x4400c000, low=5, high=2, neg_lo=1, neg_hi=6), + Case(0x00018001, 0x35553c00, 0x7bff83ff, low=3, high=4, neg_lo=2, neg_hi=1), +) + + +def packed_instruction(name, dst, case, bad=0): + active = 7 if name == 'fma' else 3 + # Set the conventional high selector for the unused third source. + high = case.high if name == 'fma' else case.high | 4 + word0 = (0xcc000000 | OPS[name] << 16 | dst | (case.low & active) << 11 | + (high & 4) << 12 | (case.neg_hi & active) << 8 | bad) + last = 259 if name == 'fma' else 0 + word1 = 257 | 258 << 9 | last << 18 | (high & 3) << 27 | (case.neg_lo & active) << 29 + return [word0, word1] + + +def moves(case): + return [word for index, value in enumerate(case.inputs, 1) for word in (0x7e0002ff | index << 17, value)] + + +def compute_program(cases, *, sparse=False, bad=0, mode=()): + code = PROLOGUE + list(mode) + for slot, case in enumerate(cases): + code += moves(case) + for j, op in enumerate(OPS): + if sparse: + code += [0x7E0802FF, INACTIVE, sop1(3, 126, 255), 0x55555555] + code += packed_instruction(op, 4, case, bad) + if sparse: + code.append(sop1(3, 126, 193)) + code += [0xE0701000 | (slot * len(OPS) + j) * 4, 0x80080408] + return code + [0xBF810000] + + +def root_signature(sdk, work): + hlsl = work / 'root.hlsl' + hlsl.write_text('#define RS "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'RS', '-Fo', root, hlsl], check=True) + return root.read_bytes() + + +def compile_shader(cli, sdk, work, profile, source): + output = source.with_suffix('.cso') + run = subprocess.run([cli, sdk, work / 'cache', profile, source, output], + capture_output=True, text=True, timeout=30) + return output, run + + +def controls(cli, sdk, work): + root = root_signature(sdk, work) + source = request(work, root, compute_program(CASES[:1])) + output, run = compile_shader(cli, sdk, work, 'gfx1013-direct-cs@0', source) + assert run.returncode == 0 and output.is_file(), run.stdout + run.stderr + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], check=True, + capture_output=True, text=True).stdout + assert 'fadd float' in dump and 'fmul float' in dump and '@dx.op.unaryBits.i32(i32 33,' in dump, dump + for options, message in ( + ({'bad': 0x8000}, 'packed binary16 arithmetic encoding'), + ({'bad': 0x2000}, 'packed binary16 arithmetic encoding'), + ({'mode': (0xBFA50003,)}, 'binary16 rounding or denormal mode'), + ({'mode': (0xBFA40004,)}, 'binary16 rounding or denormal mode'), + ): + source = request(work, root, compute_program(CASES[:1], **options)) + _, run = compile_shader(cli, sdk, work, 'gfx1013-direct-cs@0', source) + assert run.returncode and message in run.stderr, (options, run.stderr) + print('ADD/MUL and integer FMA compiled; unsupported modifiers and modes were refused') + + +def operands(case, high): + selected = case.high if high else case.low + neg = case.neg_hi if high else case.neg_lo + return tuple(((word >> (16 * ((selected >> i) & 1))) & 0xffff) ^ (((neg >> i) & 1) << 15) + for i, word in enumerate(case.inputs)) + + +def expected(case, op): + low, high = (half_op(op, *operands(case, h)) for h in (False, True)) + return low | high << 16 + + +def double_rounded(case): + def lane(high): + a, b, c = map(h2f, operands(case, high)) + rounded_f32, = struct.unpack('> 16, other & 0xffff, other >> 16)) + run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', reference], + capture_output=True, text=True, timeout=30) + if run.returncode == 77: + raise SystemExit(77) + assert run.returncode == 0, (index, run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'{len(CASES)} Pixel readbacks matched, including both exact FMA tie cases') + + +if __name__ == '__main__': + mode, tool, sdk, *args = sys.argv[1:] + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + if mode == 'controls': + controls(tool, sdk, work) + elif mode == 'compute': + draw_compute(tool, sdk, work) + elif mode == 'pixel': + draw_pixel(tool, sdk, *args, work) + else: + raise ValueError(mode)