diff --git a/docs/experiments/native-sin-cos-f16.md b/docs/experiments/native-sin-cos-f16.md new file mode 100644 index 0000000000..ff73c3c9fa --- /dev/null +++ b/docs/experiments/native-sin-cos-f16.md @@ -0,0 +1,47 @@ +# Binary16 VOP1/VOP3/SDWA `v_sin_f16` and `v_cos_f16` in direct Compute DXIL + +Issue #3298 (Refs #2935) lowers `v_sin_f16` (`0x60` / `0x1e0`) and `v_cos_f16` +(`0x61` / `0x1e1`) in the direct Compute DXIL translator via +`binary16_unary()` (`src/gfx1013_compute_native.cpp`) and `DirectCompute::trig_turns()` +/ `float_alu()` (`src/gfx1013_direct_compute.inl`). + +## Lowering & Semantics + +- Both instructions share `trig_turns()` with `v_sin_f32` and `v_cos_f32`. It reduces the widened binary32 angle + in revolutions with round-to-nearest-even (`part = a - Round_ne(a)`, DXIL op 26, so `|part| <= 0.5`), keeps a + signed zero angle, multiplies by `2 * pi` and selects an exact `+0.0` at `|part| == 0.5` for sin and + `|part| == 0.25` for cos, before `packed_half_rne()`. An angle of +0.75 turns reduces to -0.25. +- Special values on the modified binary16 source: + - `±Inf` and `NaN` (`|source| >= 0x7c00`) give the quiet NaN `0x7e00`, whatever NaN the host Sin/Cos returns. + - `v_sin_f16(-0.0)` (`0x8000`) gives `-0.0` (`0x8000`) even on a host whose Sin loses the sign of zero; `v_cos_f16(±0.0)` + returns `+1.0` (`0x3c00`). +- Preserves destination high bits `D[31:16]` on VOP1/VOP3 and supports SDWA + subword selection/padding/preservation, `abs`/`neg`, SGPR/VGPR/literal, and + inline float/integer constants under the default binary16 RNE + keep-denormals + `MODE` contract. +- Refuses `clamp`, `omod`, high-half VOP3 `op_sel`, DPP16/DPP8 encodings, + non-default binary16 `MODE`, and SDWA high-half selection on inline constants. + +## Verification + +- [native_sin_cos_f16_check.py](../../tests/native_sin_cos_f16_check.py) checks 37 cases (`VOP1`, `VOP3`, `SDWA`, + `abs`/`neg` including sin on negative halves, inline/literal/SGPR/overlap, `±0`, `±0.25`, `±0.5`, `±0.75`, + `-1.75`, `2048.0`, `65504.0`, `±Inf`, `qNaN`, `sNaN`, subnormals, general angles) and 8 refusals in `ir`, + `controls` and `hardware` (`tests/cmake/native_sin_cos_f16.cmake`). +- `ir` evaluates the IR on a model host and compares every bit, NaN payloads too. The model keeps NaN payloads + (also through `legacyF16ToF32`), answers an invalid operation with the negative quiet NaN `0xffc00000` (as x86 + SSE does) and has Sin return `+0` for a zero angle. D3D fixes none of these, so the NaN select and the `-0.0` + select of `v_sin_f16` are each needed on that host: removing either, or changing the NaN test from `uge` to + `ugt`, fails `ir`. The `a == 0` select inside `trig_turns()` belongs to the shared `v_sin_f32` path; for binary16 + the `-0.0` select covers the same case. +- `hardware` compares NaN, `±0` and `±1` results exactly. Other results accept `2^-20` absolute plus two binary16 + ulp of the expected value. + +## Accuracy + +No documented error bound for DXIL `Sin` and `Cos` was found. The parts of the Direct3D 11.3 functional +specification read for this note (section 3.1, floating-point rules) list none, and the instruction reference rows +were not reachable. The `hardware` tolerance is therefore an assumption, not a host contract: a binary32 error of +at most `2^-20` absolute for an argument in [-pi, pi]. Near a zero crossing only that absolute part applies, so the +check cannot tell a tiny result such as `sin_subnormal` (about 3.7e-7) from zero. The RDNA2 accuracy of +`V_SIN_F16`/`V_COS_F16` was not compared. The readback is not measured on this machine (capability skip 77). diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index e222c69c44..65ff47aece 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -31,7 +31,7 @@ static bool binary16_alu(std::string_view name) { static bool binary16_unary(std::string_view name) { return name == "v_rcp_f16" || name == "v_sqrt_f16" || name == "v_exp_f16" || - name == "v_rsq_f16" || name == "v_log_f16"; + name == "v_rsq_f16" || name == "v_log_f16" || name == "v_sin_f16" || name == "v_cos_f16"; } [[noreturn]] void refuse(unsigned pc, const string &reason) { diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index c8432b6a87..5c95a73e10 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -947,6 +947,20 @@ struct DirectCompute { string select_float(const string &condition, const string &yes, const string &no) { return ir.value("select i1 " + condition + ", float " + yes + ", float " + no); } + // Reduce an angle in turns to [-0.5, 0.5] with round-to-nearest-even (DXIL + // Round_ne, op 26) before converting to radians, preserving signed zero and + // the exact zeros at half a turn for sin and a quarter turn for cos. + string trig_turns(bool cosine, const string &a) { + auto unary_f32 = [&](unsigned op, const string &v) { + return ir.invoke("float", "unary.f32", op, {{"float", v}}, "nounwind readnone"); + }; + auto part = ir.value("fsub float " + a + ", " + unary_f32(26, a)); + part = select_float(ir.value("fcmp oeq float " + a + ", 0.0"), a, part); + auto radians = ir.value("fmul float " + part + ", 0x401921FB60000000"); + auto mag_part = unary_f32(6, part); + auto exact = ir.value("fcmp oeq float " + mag_part + (cosine ? ", 0.25" : ", 0.5")); + return select_float(exact, "0.0", unary_f32(cosine ? 12 : 13, radians)); + } // Invert the cube projection. Each pair of faces has a common major // axis, with the negative face second. The two minor axes span [-1,1]. std::array cube_axes(const string &face, const string &u, const string &v, bool tangent) { @@ -2566,9 +2580,12 @@ struct DirectCompute { const auto source = half_bits(0); auto a = widen(source); const bool rsq = n == "v_rsq_f16", exp = n == "v_exp_f16", log = n == "v_log_f16"; + const bool trig = n == "v_sin_f16" || n == "v_cos_f16"; string widened; if (n == "v_rcp_f16") { widened = ir.value("fdiv float 1.000000e+00, " + a); + } else if (trig) { + widened = trig_turns(n == "v_cos_f16", a); } else if (binary16_unary(n)) { const unsigned opcode = rsq ? 25 : exp ? 21 : log ? 23 : 24; widened = ir.invoke("float", "unary.f32", opcode, {{"float", a}}, "nounwind readnone"); @@ -2611,6 +2628,12 @@ struct DirectCompute { rounded = select(cmp("eq", source, "31744"), "31744", rounded); rounded = select(cmp("ugt", source, "31744"), "32256", rounded); rounded = select(cmp("eq", magnitude, "0"), "64512", rounded); + } else if (trig) { + const auto magnitude = ir.binary("and", source, "32767"); + // Map +/-Inf and NaN to canonical quiet NaN; preserve -0.0 on v_sin_f16. + rounded = select(cmp("uge", magnitude, "31744"), "32256", rounded); + if (n == "v_sin_f16") + rounded = select(cmp("eq", source, "32768"), "32768", rounded); } // D[31:16] keeps its value: LLVM GCNSubtarget::zeroesHigh16BitsOfDest says // "On gfx10, all 16-bit instructions preserve the high bits", as v_cvt_f16_f32 above already does. @@ -2959,14 +2982,7 @@ struct DirectCompute { ir.value("fcmp oeq float " + b + ", 0.0")); result = select_float(zero, "0.0", ir.value("fmul float " + a + ", " + b)); } else if (n == "v_sin_f32" || n == "v_cos_f32") { - // Victory trig_turns: reduce in turns before converting to - // radians, preserving signed zero and exact quarter-turn zeros. - auto part = ir.value("fsub float " + a + ", " + unary(26, a)); - part = select_float(ir.value("fcmp oeq float " + a + ", 0.0"), a, part); - const bool cosine = n == "v_cos_f32"; - auto radians = ir.value("fmul float " + part + ", 0x401921FB60000000"); - auto exact = ir.value("fcmp oeq float " + unary(6, part) + (cosine ? ", 0.25" : ", 0.5")); - result = select_float(exact, "0.0", unary(cosine ? 12 : 13, radians)); + result = trig_turns(n == "v_cos_f32", a); } else if (cube) result = cube_alu(n, a, fp(1), fp(2)); else if (n == "v_add_f32" || n == "v_sub_f32" || n == "v_subrev_f32" || n == "v_mul_f32") { diff --git a/tests/cmake/native_sin_cos_f16.cmake b/tests/cmake/native_sin_cos_f16.cmake new file mode 100644 index 0000000000..8ff0d13c69 --- /dev/null +++ b/tests/cmake/native_sin_cos_f16.cmake @@ -0,0 +1,17 @@ +if(TARGET native_compute_ir_dump AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_sin_cos_f16_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_sin_cos_f16_check.py" ir + "$") + set_tests_properties(native_sin_cos_f16_ir PROPERTIES TIMEOUT 60) +endif() +if(TARGET compile_dxil AND TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_sin_cos_f16_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_sin_cos_f16_check.py" controls + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_sin_cos_f16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_sin_cos_f16_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_sin_cos_f16_check.py" hardware + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_sin_cos_f16_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) +endif() diff --git a/tests/native_f16_alu_check.py b/tests/native_f16_alu_check.py index 97e7f360c6..83e9c89834 100644 --- a/tests/native_f16_alu_check.py +++ b/tests/native_f16_alu_check.py @@ -419,7 +419,6 @@ 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((vop1(0x60, 3, 257) + [0xbf810000], 'direct DXIL lowering for v_sin_f16')) for name, op in UNARY_CODE.items(): programs.append((vop1(op, 3, 250) + [0, 0xbf810000], 'unsupported v_%s_f16 DPP form' % name)) programs.append((vop3(op, 3, 257, 0, clamp=1, unary=True) + [0xbf810000], diff --git a/tests/native_sin_cos_f16_check.py b/tests/native_sin_cos_f16_check.py new file mode 100644 index 0000000000..e82c2e3cba --- /dev/null +++ b/tests/native_sin_cos_f16_check.py @@ -0,0 +1,370 @@ +"""Binary16 VOP1/VOP3/SDWA v_sin_f16 and v_cos_f16 in direct Compute DXIL (#3298, Refs #2935).""" +from dataclasses import dataclass +import math +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +import f16_packed_model as M +import native_f16_alu_check as F +from native_compute_clear_check import write_request +from native_sdwa_f16_check import ABS, NEG, PAD, PRESERVE, SCALAR, WORD_0, WORD_1, DWORD, OLD, sdwa + + +TRIG_OPS = {'sin': 0x60, 'cos': 0x61} +TWO_PI_F32 = struct.unpack('>d', bytes.fromhex('401921FB60000000'))[0] + + +def _f32_literal(token): + if token.startswith('0x'): + raw = token[2:].zfill(16) + return struct.unpack('d', bytes.fromhex(raw))[0]))[0] + return struct.unpack('= 0x7C00: + return 0x7E00 + if op == 'sin' and bits == 0x8000: + return 0x8000 + a = struct.unpack('= 193 else (self.inline_code - 128) & 0xFFFF + if self.encoding == 'sdwa': + sel = self.sdwa_src0 & 7 + picked = (self.src_val >> 16) if sel == WORD_1 else (self.src_val & 0xFFFF) + return F.modified(picked, bool(self.sdwa_src0 & ABS), bool(self.sdwa_src0 & NEG), 0) + return F.modified(self.src_val & 0xFFFF, self.abs_mask, self.neg, 0) + + def want(self): + return expected_trig_f16(self.op, self.source_half()) + + def emit(self): + opcode = TRIG_OPS[self.op] + if self.encoding == 'sdwa': + return (F.mov(1, self.src_val) + F.mov(3, OLD) + + sdwa(opcode, self.sdwa_dst, self.sdwa_unused, self.sdwa_src0, unary=True)) + if self.encoding == 'overlap': + return F.mov(3, F.HI_A | self.src_val) + F.vop1(opcode, 3, 259) + if self.encoding == 'literal': + return F.mov(3, F.HI_A) + F.vop1(opcode, 3, 255) + [self.src_val] + if self.encoding == 'sgpr': + return F.smov(8, F.HI_B | self.src_val) + F.mov(3, F.HI_A) + F.vop1(opcode, 3, 8) + if self.encoding in ('inline', 'inline_int'): + return F.mov(3, F.HI_A) + F.vop1(opcode, 3, self.inline_code) + if self.encoding == 'vop3': + return F.mov(1, F.HI_B | self.src_val) + F.mov(3, F.HI_A) + F.vop3( + opcode, 3, 257, 0, self.abs_mask, self.neg, unary=True) + return F.mov(1, F.HI_B | self.src_val) + F.mov(3, F.HI_A) + F.vop1(opcode, 3, 257) + + def matches(self, got, *, hardware=False): + want_h = self.want() + if self.encoding == 'sdwa': + shift = 16 if self.sdwa_dst == WORD_1 else 0 + mask = 0xFFFF << shift + other = OLD & ~mask if self.sdwa_unused == PRESERVE else 0 + if (got & ~mask) != other: + return False + got_h = (got & mask) >> shift + else: + if (got >> 16) != (F.HI_A >> 16): + return False + got_h = got & 0xFFFF + if not hardware: + # The IR is evaluated by interpret_trig's model host, so every bit is compared, NaN payloads too. + return got_h == want_h + if M.is_nan(want_h) or want_h in (0x0000, 0x8000, 0x3C00, 0xBC00): + return F.same_binary16(got_h, want_h) + # No documented error bound for DXIL Sin/Cos was found (see docs/experiments/native-sin-cos-f16.md). The + # readback assumes a host error of at most 2^-20 absolute on the binary32 result, plus the binary16 rounding + # of two ulp of the expected value. Near a zero crossing only the absolute part applies. + ulp = M.h2f((want_h & 0x7C00) or 0x0001) * (2.0 ** -10 if want_h & 0x7C00 else 1.0) + return abs(M.h2f(got_h) - M.h2f(want_h)) <= 2.0 ** -20 + 2 * ulp + + +def all_cases(): + cases = [ + # Exact specials & quarter/half turns across both VOP1 and VOP3. + Case('sin_pos_zero', 'sin', 'vop1', 0x0000), + Case('sin_neg_zero', 'sin', 'vop1', 0x8000), + Case('cos_pos_zero', 'cos', 'vop1', 0x0000), + Case('cos_neg_zero', 'cos', 'vop1', 0x8000), + Case('sin_qtr_pos', 'sin', 'vop1', 0x3400), # +0.25 -> +1.0 + Case('sin_qtr_neg', 'sin', 'vop1', 0xB400), # -0.25 -> -1.0 + Case('cos_qtr_pos', 'cos', 'vop1', 0x3400), # +0.25 -> +0.0 + Case('cos_qtr_neg', 'cos', 'vop1', 0xB400), # -0.25 -> +0.0 + Case('sin_half_pos', 'sin', 'vop1', 0x3800), # +0.5 -> +0.0 + Case('sin_half_neg', 'sin', 'vop1', 0xB800), # -0.5 -> +0.0 + Case('cos_half_pos', 'cos', 'vop1', 0x3800), # +0.5 -> -1.0 + Case('cos_half_neg', 'cos', 'vop1', 0xB800), # -0.5 -> -1.0 + Case('sin_3qtr_pos', 'sin', 'vop3', 0x3A00), # +0.75 -> -1.0 + Case('cos_3qtr_pos', 'cos', 'vop3', 0x3A00), # +0.75 reduces to -0.25 turns -> +0.0 + Case('cos_3qtr_neg', 'cos', 'vop3', 0xBA00), # -0.75 -> +0.0 + Case('cos_1_75_neg', 'cos', 'vop1', 0xBF00), # -1.75 -> +0.0 + Case('sin_int_2048', 'sin', 'vop1', 0x6800), # 2048.0 -> +0.0 + Case('cos_max_norm', 'cos', 'vop1', 0x7BFF), # 65504.0 -> +1.0 + Case('sin_pos_inf', 'sin', 'vop1', 0x7C00), # +Inf -> NaN + Case('cos_neg_inf', 'cos', 'vop3', 0xFC00), # -Inf -> NaN + Case('sin_qnan', 'sin', 'vop1', 0x7E01), # NaN -> NaN + Case('cos_snan', 'cos', 'vop3', 0x7D02), # sNaN -> NaN + # General angles, modifiers (abs/neg), source kinds, overlap, and SDWA. + Case('sin_0125', 'sin', 'vop1', 0x3000), # 0.125 + Case('cos_0125_neg', 'cos', 'vop3', 0x3000, neg=1), + Case('sin_0125_neg', 'sin', 'vop3', 0x3000, neg=1), # -0.125 -> -0.7071 (sin is odd) + Case('sin_0375_abs', 'sin', 'vop3', 0xB600, abs_mask=1), + Case('cos_00625', 'cos', 'vop1', 0x2C00), # 0.0625 + Case('sin_subnormal', 'sin', 'vop1', 0x0001), + Case('cos_inline_f16', 'cos', 'inline', inline_code=240), # 0.5 -> -1.0 + Case('sin_inline_int', 'sin', 'inline_int', inline_code=193), # -1 -> +0.0 + Case('cos_literal', 'cos', 'literal', 0x12343800), # low half 0.5 -> -1.0 + Case('sin_sgpr', 'sin', 'sgpr', 0x3400), + Case('cos_overlap', 'cos', 'overlap', 0x3800), + Case('sin_sdwa_w1_pres', 'sin', 'sdwa', 0x34003800, sdwa_dst=WORD_1, sdwa_unused=PRESERVE, sdwa_src0=WORD_1), + Case('cos_sdwa_w0_pad', 'cos', 'sdwa', 0x34003800, sdwa_dst=WORD_0, sdwa_unused=PAD, sdwa_src0=DWORD | ABS), + # sin is odd, so dropping ABS or NEG on a negative selected half flips the sign of the result. + Case('sin_sdwa_w1_abs', 'sin', 'sdwa', 0xB0003800, sdwa_dst=WORD_0, sdwa_unused=PRESERVE, sdwa_src0=WORD_1 | ABS), + Case('sin_sdwa_w0_neg', 'sin', 'sdwa', 0x3800B000, sdwa_dst=WORD_1, sdwa_unused=PAD, sdwa_src0=WORD_0 | NEG), + ] + assert len(cases) < F.STRIDE + return cases + + +def program(cases): + code = F.preamble() + for slot, c in enumerate(cases): + code += c.emit() + F.store(slot * 4, 3) + return code + [0xBF810000] + + +def refusal_programs(): + return [ + (F.vop3(TRIG_OPS['sin'], 3, 257, 0, clamp=1, unary=True) + [0xBF810000], 'unsupported v_sin_f16 clamp or omod'), + (F.vop3(TRIG_OPS['cos'], 3, 257, 0, omod=1, unary=True) + [0xBF810000], 'unsupported v_cos_f16 clamp or omod'), + (F.vop3(TRIG_OPS['sin'], 3, 257, 0, opsel=1, unary=True) + [0xBF810000], 'unsupported v_sin_f16 high-half op_sel'), + (F.vop1(TRIG_OPS['cos'], 3, 250) + [0x010101B1, 0xBF810000], 'unsupported v_cos_f16 DPP form'), + (F.vop1(TRIG_OPS['sin'], 3, 233) + [0x01010101, 0xBF810000], 'unsupported v_sin_f16 DPP form'), + ([0xBFA40004] + F.vop1(TRIG_OPS['sin'], 3, 257) + [0xBF810000], 'unsupported binary16 rounding or denormal mode'), + ([0xBFA50000] + F.vop1(TRIG_OPS['cos'], 3, 257) + [0xBF810000], 'unsupported binary16 rounding or denormal mode'), + (sdwa(TRIG_OPS['sin'], WORD_0, PRESERVE, WORD_1 | SCALAR, reg0=242, unary=True) + [0xBF810000], + 'unsupported SDWA binary16 inline constant selection'), + ] + + +def _float_val(token, values): + if token.startswith('%'): + kind, bits = values[token] + assert kind == 'float', (token, kind) + return struct.unpack(' 0x7F800000 + + +def _host_fbin(op, left, right): + """A model host for the float binaries that keeps NaN payloads and answers Inf - Inf with HOST_DEFAULT_NAN. + + D3D does not fix NaN bit patterns, so a model host that propagates payloads and has a negative default NaN + makes every special-result select of the lowering observable: without them the stored half differs. + """ + for bits in (left, right): + if _is_nan32(bits): + return bits | 0x00400000 + value = {'fsub': F._f32(left) - F._f32(right), 'fmul': F._f32(left) * F._f32(right)}[op] + return HOST_DEFAULT_NAN if math.isnan(value) else _f32_bits(struct.unpack(' b) + else: + raise AssertionError(line) + values[m.group(1)] = ('i1', int(res)) + elif (m := re.fullmatch(r'(%\w+) = select i1 (\S+), float (\S+), float (\S+)', line)): + val = _float_val(m.group(3) if F._i1(m.group(2), values) else m.group(4), values) + values[m.group(1)] = ('float', _f32_bits(val)) + elif (m := re.fullmatch(r'(%\w+) = call float @dx\.op\.legacyF16ToF32\(i32 131, i32 (\S+)\)', line)): + half = F._i32(m.group(2), values) & 0xFFFF + if (half & 0x7C00) == 0x7C00 and half & 0x3FF: + # Widen a NaN with its payload, as IEEE conversions do; struct's binary16 path drops it. + values[m.group(1)] = ('float', (half & 0x8000) << 16 | 0x7F800000 | (half & 0x3FF) << 13) + else: + values[m.group(1)] = ('float', F._widen(half)) + elif (m := re.fullmatch(r'(%\w+) = (fsub|fmul) float (\S+), (\S+)', line)): + left, right = (_f32_bits(_float_val(t, values)) if not t.startswith('%') else values[t][1] + for t in (m.group(3), m.group(4))) + values[m.group(1)] = ('float', _host_fbin(m.group(2), left, right)) + elif (m := re.fullmatch(r'(%\w+) = call float @dx\.op\.unary\.f32\(i32 (\d+), float (\S+)\)', line)): + op_id, token = int(m.group(2)), m.group(3) + xbits = values[token][1] if token.startswith('%') else _f32_bits(_float_val(token, values)) + x = F._f32(xbits) + if op_id == 6: + ybits = xbits & 0x7FFFFFFF + elif _is_nan32(xbits): + ybits = xbits | 0x00400000 + elif op_id in (12, 13): + y = (math.cos(x) if op_id == 12 else math.sin(x) + 0.0) if math.isfinite(x) else math.nan + ybits = HOST_DEFAULT_NAN if math.isnan(y) else _f32_bits(struct.unpack('