r"""Every f16 input through the f16 transcendentals on an AMD GPU (FUZZ-29). Standard library only. v_exp_f16, v_log_f16, v_rcp_f16, v_rsq_f16, v_sqrt_f16, v_sin_f16 and v_cos_f16 run natively through the hardware oracle (tools/hw_oracle/) on all 65,536 f16 bit patterns, in wave32 and wave64 and under several float MODEs, and each result is compared with the rule the translator implements (tools/rdna2spirv.py: widen to f32, the GLSL.std.450 function, round to nearest even back to f16, f16 denormals kept): * v_exp_f16 = Exp2, v_log_f16 = Log2, v_rcp_f16 = 1 / x, v_rsq_f16 = InverseSqrt, v_sqrt_f16 = Sqrt. The reference is the exact value, correctly rounded to f16 (decimal arithmetic, 60 digits), which is the best a Vulkan driver can return for the translated SPIR-V. * v_sin_f16 / v_cos_f16 take turns: the reference is sin / cos of 2 pi x, reduced in turns, correctly rounded. A second table compares the hardware with Sin / Cos of the f32 product 6.2831855 * x, which is what the translator computed before reducing in turns (#594). * Where the rule's SPIR-V is undefined (Log2 / Sqrt / InverseSqrt of a negative, Log2 / InverseSqrt of 0, a division by 0), the hardware result is tabulated instead of judged. Nothing is assumed about how close the hardware is: the tables count bit-exact results, 1 ulp, more than 1 ulp, denormal operands read as zero, denormal results flushed, and NaN, and list the hardware word for each special input. Each MODE is read back inside a kernel first, so a launcher that ignored the descriptor fails instead of producing plausible tables. Usage: python -I tools/f16_trans_sweep.py [--ops v_exp_f16,v_log_f16] [--modes keep16,flush16] [--json out.json] python -I tools/f16_trans_sweep.py --self-test Exit 0 when the sweep ran (differences from the rule are findings, not failures), 1 when wave32 and wave64 disagree or --json cannot be written, 2 on a harness error (a MODE that did not apply, a kernel without its words), 77 when the hardware oracle is unavailable. On Linux the oracle needs LEONIDA_HW_DRM_NODE (docs/shader_validation.md). Nothing here reads game files. """ import argparse import functools import json import os import stat import struct import sys import tempfile from decimal import ROUND_HALF_EVEN, Decimal, localcontext HERE = os.path.dirname(os.path.abspath(__file__)) sys.dont_write_bytecode = True if HERE not in sys.path: sys.path.insert(0, HERE) from file_mode import published_mode # noqa: E402 import replace_retry # noqa: E402 OPS = ("v_exp_f16", "v_log_f16", "v_rcp_f16", "v_rsq_f16", "v_sqrt_f16", "v_sin_f16", "v_cos_f16") # f32 denormals flushed and IEEE off is the state docs/design.md infers for the game's shaders; the f16 denormal # field is the open question, so both settings are run, then IEEE on, then f16 rounding toward zero. MODES = { "keep16": {"ieee": 0, "dx10_clamp": 1, "denorm32": 0, "denorm16_64": 3}, "flush16": {"ieee": 0, "dx10_clamp": 1, "denorm32": 0, "denorm16_64": 0}, "ieee_keep16": {"ieee": 1, "dx10_clamp": 1, "denorm32": 0, "denorm16_64": 3}, "ieee_flush16": {"ieee": 1, "dx10_clamp": 1, "denorm32": 0, "denorm16_64": 0}, "keep16_rtz": {"ieee": 0, "dx10_clamp": 1, "denorm32": 0, "denorm16_64": 3, "round16_64": 3}, } THREADS = 1024 PER_THREAD = 8 # inputs per thread, packed two to a dword PER_KERNEL = THREADS * PER_THREAD # 8192 inputs, 4096 words per kernel: 8 kernels cover every input QNAN = 0x7E00 TWO_PI_F32 = struct.unpack("= Decimal(2) ** (e + 1) and e < 15: e += 1 ulp = Decimal(2) ** (e - 10) with localcontext() as c: c.prec = 80 n = int((a / ulp).to_integral_value(rounding="ROUND_DOWN" if rtz else ROUND_HALF_EVEN)) val = n * ulp if val > 65504: return sign | (0x7BFF if rtz else 0x7C00) return sign | struct.unpack("= 1: f -= 1 q = f * 4 if q == q.to_integral_value(): return [Decimal(0), Decimal(1), Decimal(0), Decimal(-1)][int(q)] if f > Decimal("0.5"): f -= 1 # (-0.5, 0.5] return _sin(2 * _pi() * f) def exact(op, h): """The exact real result of the op on f16 h as a Decimal, or a str for a result that is not a finite real: 'nan', '+inf', '-inf', '+0', '-0', or 'undef' where the translated SPIR-V is undefined.""" if is_nan(h): return "nan" s = neg(h) if is_inf(h): return {"v_exp_f16": "+0" if s else "+inf", "v_log_f16": "undef" if s else "+inf", "v_rcp_f16": "-0" if s else "+0", "v_rsq_f16": "undef" if s else "+0", "v_sqrt_f16": "undef" if s else "+inf", "v_sin_f16": "undef", "v_cos_f16": "undef"}[op] if is_zero(h): return {"v_exp_f16": Decimal(1), "v_log_f16": "undef", "v_rcp_f16": "undef", "v_rsq_f16": "undef", "v_sqrt_f16": "-0" if s else "+0", "v_sin_f16": "-0" if s else "+0", "v_cos_f16": Decimal(1)}[op] x = to_dec(h) if s and op in ("v_log_f16", "v_rsq_f16", "v_sqrt_f16"): return "undef" with localcontext() as c: c.prec = 60 if op == "v_exp_f16": return Decimal(2) ** x if x != x.to_integral_value() else (Decimal(2) ** int(x) if abs(x) < 64 else (Decimal(0) if x < 0 else Decimal(10) ** 30)) if op == "v_log_f16": return x.ln() / Decimal(2).ln() if op == "v_rcp_f16": return 1 / x if op == "v_rsq_f16": return 1 / x.sqrt() if op == "v_sqrt_f16": return x.sqrt() return sin_turns(x, op == "v_cos_f16") def product_turns(op, h): """sin / cos of the f32 product 6.2831855 * x for finite h (the translator before #594 was fixed).""" with localcontext() as c: c.prec = 60 t = Decimal(struct.unpack("> 16] return out def classify(op, hw, ref): """Counts for one op and mode. A denormal operand whose word equals the hardware's own word for a zero of the same sign counts as read as zero (the rule is undefined at 0 for log, rcp and rsq, so the rule can't say).""" zero_hw = {False: hw[0x0000], True: hw[0x8000]} c = {"inputs": 0, "exact": 0, "ulp1": 0, "ulp_more": 0, "max_ulp": 0, "nan_ok": 0, "zero_sign": 0, "denorm_in_as_zero": 0, "denorm_out_flushed": 0, "undefined": 0, "nan_payload_kept": 0, "snan_kept": 0, "snan_quieted": 0, "snan_other": 0, "other": 0} worst = [] for h in range(65536): r, g = ref[h], hw[h] c["inputs"] += 1 if r is None: c["undefined"] += 1 continue if is_nan(r): if is_nan(g): c["nan_ok"] += 1 if is_nan(h) and (g & 0x1FF) == (h & 0x1FF): c["nan_payload_kept"] += 1 if is_nan(h) and not h & 0x200: c["snan_kept" if g == h else "snan_quieted" if g == h | 0x200 else "snan_other"] += 1 else: c["other"] += 1 worst.append((h, g, r)) continue if g == r: c["exact"] += 1 elif is_denorm(h) and g == zero_hw[neg(h)]: c["denorm_in_as_zero"] += 1 elif is_denorm(r) and is_zero(g) and (g & 0x8000) == (r & 0x8000): c["denorm_out_flushed"] += 1 elif is_zero(g) and is_zero(r): c["zero_sign"] += 1 elif is_nan(g): c["other"] += 1 worst.append((h, g, r)) else: d = ulps(g, r) c["max_ulp"] = max(c["max_ulp"], d) if d == 1: c["ulp1"] += 1 else: c["ulp_more"] += 1 worst.append((h, g, r)) worst.sort(key=lambda t: -ulps(t[1], t[2]) if not (is_nan(t[1]) or is_nan(t[2])) else -1 << 20) return c, worst[:8] def product_reference(op, rtz=False): return [None if is_nan(h) or is_inf(h) else to_bits(product_turns(op, h), rtz) for h in range(65536)] def range_stats(hw, turns): """sin / cos only: ulps against sin / cos of the f32 product, by |x| band.""" bands = {"|x|<=1": (0, 1), "1<|x|<=256": (1, 256), "|x|>256": (256, 1e9)} out = {} for name, (lo, hi) in bands.items(): n = ex = u1 = more = 0 worst = 0 for h in range(65536): if is_nan(h) or is_inf(h): continue a = abs(float(to_dec(h))) if not (lo < a <= hi or (lo == 0 and a == 0)): continue r = turns[h] g = hw[h] n += 1 if is_nan(g): more += 1 continue d = 0 if (g == r or (is_zero(g) and is_zero(r))) else ulps(g, r) worst = max(worst, d) ex += d == 0 u1 += d == 1 more += d > 1 out[name] = {"inputs": n, "exact": ex, "ulp1": u1, "ulp_more": more, "max_ulp": worst} return out def fmt(h): if h is None: return "undef" v = struct.unpack(" {v}" for h, v in report["ops"][op][modes[0]]["specials"].items())) except RuntimeError as e: print(f"harness error: {e}") return 2 finally: oracle.close() if a.json is not None: err = write_json_report(a.json, report) if err: print(f"error: {err}", file=sys.stderr) return 1 return rc if __name__ == "__main__": try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode sys.stdout.reconfigure(errors="replace") except (AttributeError, ValueError, OSError): pass sys.exit(main())