From 7bd5f01dd166dfcf80f4f96bb678cccc5918a7bc Mon Sep 17 00:00:00 2001 From: iurysf <98192149+iurysf@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:55:19 -0300 Subject: [PATCH] FUZZ-55: Route --oracle hw through hw_oracle, fix zero-sum sign, pin the reference Review follow-up on #4536 (CHANGES_REQUESTED by Flyander; coverage note by kapitche). - --oracle hw no longer always exits 77. It opens tools/hw_oracle (same pattern as tools/fmisc_diff.py), runs each program as a one-lane wave32 raw kernel in the game's inferred MODE, honours --hw-arch, and compares the four words with the reference. 77 is returned only when the oracle is unavailable. v_rcp/v_rsq/v_sqrt_f64 are counted skips there (native results are approximations, PROC-216); the translator-only known-divergence exclusions do not apply to hardware. - add_bits: an exact zero sum now follows IEEE 754-2019 6.3. +0 + +0 stays +0 in every mode; only opposite-signed zeros and x + (-x) give -0 when rounding toward negative. Before, every exact zero was -0 in that mode. - tests: direct table tests for compare (16 conditions x 28 operand pairs), class (10 classes plus boundaries), div_fixup, frexp and add_bits (NaN, inf, zero signs in all four modes), plus fake-oracle tests for hw routing, --hw-arch, exit 77, skips and shrinking. Mutating lt to <=, add_bits NaN to 0, or dropping the signed-zero rule now fails them. - docs/shader_validation.md describes the hw contract. No AMD hardware run has been done. KNOWN_DIVERGENCES keeps div-fixup-nan-s0 (it waits for TEST-983 to reach main). AI-assisted (OpenBot team). Co-authored-by: OpenBot <335604065+openbotgit[bot]@users.noreply.github.com> --- docs/shader_validation.md | 13 ++- tests/test_f64_diff.py | 235 +++++++++++++++++++++++++++++++++++++- tools/f64_diff.py | 102 +++++++++++++---- 3 files changed, 327 insertions(+), 23 deletions(-) diff --git a/docs/shader_validation.md b/docs/shader_validation.md index caa54dc4e..5eb987cb5 100644 --- a/docs/shader_validation.md +++ b/docs/shader_validation.md @@ -1238,7 +1238,17 @@ the minimized case is printed. `--oracle gpu` translates the same fragment shader and runs it through `runtime/build/vk_harness`, comparing the raw RGBA32F output words. It assembles the fragment module with `spirv-as` and the full-screen vertex shader with the Vulkan SDK's `glslc`; use `--exe PATH` to select another `vk_harness`. It exits 77 if the executable, SDK tools, Vulkan device or required `shaderFloat64` -feature is unavailable. `--oracle hw` requires the AMD `tools/hw_oracle` setup and likewise exits 77 when unavailable. +feature is unavailable. `--oracle hw` runs the same programs natively on an AMD GPU through `tools/hw_oracle` (one lane +of a wave32 compute kernel, as `tools/fmisc_diff.py` does) and compares the four words with the reference only, not with +the translator; `--hw-arch` picks the architecture to assemble for (default: detected). The campaign is one launch, and a +failing program is re-run alone while it is shrunk. The hardware runs every form, so the known-divergence exclusions +(translator limits) do not apply: output modifiers, clamp, negated/absolute operands and directed rounding are compared +too, and the kernels start in the game's inferred float MODE (IEEE off, DX10_CLAMP on). `v_rcp_f64`, `v_rsq_f64` and +`v_sqrt_f64` are counted skips there, because the native results are approximations (PROC-216) and the reference is exact; +an architecture that cannot set that MODE (gfx1170 and later) or a program the assembler rejects is a counted skip with the +runner's reason. It exits 77 only when the `tools/hw_oracle` tools or device are missing. The path is covered by +`tests/test_f64_diff.py` with a fake oracle (routing, `--hw-arch`, exit 77, skips, shrinking); **no AMD hardware run has +been done for it yet**. Exit codes are 0 for no unexpected mismatch, 1 for a mismatch (with instruction-removal shrinking), 2 for CLI/harness errors and 77 for unavailable oracles. Skips always include a reason. @@ -1247,6 +1257,7 @@ oracles. Skips always include a reason. python -I tools/f64_diff.py --programs 300 --seed 1 python -I tools/f64_diff.py --known --programs 300 --seed 1 python -I tools/f64_diff.py --oracle gpu --programs 300 --seed 1 +python -I tools/f64_diff.py --oracle hw --programs 300 --seed 1 python -I tools/f64_diff.py --self-test python -I tests/test_f64_diff.py ``` diff --git a/tests/test_f64_diff.py b/tests/test_f64_diff.py index f4dc3f5cd..4a02c17d7 100644 --- a/tests/test_f64_diff.py +++ b/tests/test_f64_diff.py @@ -52,7 +52,11 @@ class F64DiffTests(unittest.TestCase): self.assertFalse(fd.equivalent(expected, actual, ("int", "int"))) def test_exit_77_when_requested_oracle_is_unavailable(self): - self.assertEqual(self.command("--oracle", "hw").returncode, 77) + env = dict(os.environ, LEONIDA_AMD_CLANG=os.path.join(ROOT, "tools", "no-such-clang.exe")) + hw = subprocess.run([sys.executable, "-I", TOOL, "--oracle", "hw", "--programs", "3"], cwd=ROOT, + capture_output=True, text=True, timeout=120, env=env) + self.assertEqual(hw.returncode, 77, hw.stdout + hw.stderr) + self.assertIn("hardware oracle unavailable", hw.stderr) self.assertEqual(self.command("--oracle", "gpu", "--exe", "missing.exe").returncode, 77) self.assertEqual(self.command("--oracle", "gpu", "--exe", "missing.exe", "--ops", "not_f64").returncode, 2) @@ -142,6 +146,235 @@ class F64DiffTests(unittest.TestCase): finally: fd.translate = original + # ---- the reference functions, checked against hand-written tables (no shared code with the reference) ---- + + ONE, TWO, THREE = 0x3FF0000000000000, 0x4000000000000000, 0x4008000000000000 + NEG1, NEG2, NEG3 = 0xBFF0000000000000, 0xC000000000000000, 0xC008000000000000 + PZ, NZ = 0, 0x8000000000000000 + PINF, NINF = 0x7FF0000000000000, 0xFFF0000000000000 + QNAN, SNAN = 0x7FF8000000000000, 0x7FF0000000000001 + + def test_compare_table_all_16_conditions(self): + # Which of the four relations (lt, eq, gt, un) make each condition true: the ISA's definitions, written out. + true_for = { + "f": set(), "lt": {"lt"}, "eq": {"eq"}, "le": {"lt", "eq"}, "gt": {"gt"}, "lg": {"lt", "gt"}, + "ge": {"gt", "eq"}, "o": {"lt", "eq", "gt"}, "u": {"un"}, "nge": {"lt", "un"}, "nlg": {"eq", "un"}, + "ngt": {"lt", "eq", "un"}, "nle": {"gt", "un"}, "neq": {"lt", "gt", "un"}, "nlt": {"gt", "eq", "un"}, + "tru": {"lt", "eq", "gt", "un"}, + } + self.assertEqual(set(true_for), set(fd.CONDS)) + self.assertEqual(len(fd.CONDS), 16) + pairs = [(self.ONE, self.TWO, "lt"), (self.TWO, self.ONE, "gt"), (self.ONE, self.ONE, "eq"), + (self.NEG1, self.ONE, "lt"), (self.ONE, self.NEG1, "gt"), (self.NEG2, self.NEG2, "eq"), + (self.PZ, self.NZ, "eq"), (self.NZ, self.PZ, "eq"), (self.PZ, self.PZ, "eq"), (self.NZ, self.NZ, "eq"), + (0x8000000000000001, self.PZ, "lt"), (self.PZ, 1, "lt"), (1, 0x8000000000000001, "gt"), + (self.PINF, self.PINF, "eq"), (self.NINF, self.NINF, "eq"), (self.NINF, self.PINF, "lt"), + (self.PINF, self.NINF, "gt"), (self.PINF, self.ONE, "gt"), (self.NINF, self.ONE, "lt"), + (self.ONE, self.PINF, "lt"), (self.QNAN, self.ONE, "un"), (self.ONE, self.QNAN, "un"), + (self.QNAN, self.QNAN, "un"), (self.SNAN, self.ONE, "un"), (self.ONE, self.SNAN, "un"), + (self.QNAN, self.PINF, "un"), (self.NINF, self.QNAN, "un"), (self.QNAN, self.PZ, "un")] + for cond, relations in true_for.items(): + for a, b, relation in pairs: + with self.subTest(cond=cond, a=hex(a), b=hex(b)): + self.assertEqual(fd.compare(cond, a, b), int(relation in relations)) + + def test_class_table_all_ten_classes_and_boundaries(self): + table = [ + (0x7FF0000000000001, 0), (0xFFF0000000000001, 0), (0x7FF7FFFFFFFFFFFF, 0), # signalling NaN, any sign + (0x7FF8000000000000, 1), (0xFFF8000000000000, 1), (0xFFFFFFFFFFFFFFFF, 1), # quiet NaN, any payload + (self.NINF, 2), (self.NEG1, 3), (0xFFEFFFFFFFFFFFFF, 3), (0x8010000000000000, 3), + (0x800FFFFFFFFFFFFF, 4), (0x8000000000000001, 4), (self.NZ, 5), (self.PZ, 6), + (1, 7), (0x000FFFFFFFFFFFFF, 7), (0x0010000000000000, 8), (self.ONE, 8), + (0x7FEFFFFFFFFFFFFF, 8), (self.PINF, 9), + ] + for bits, want in table: + with self.subTest(bits=hex(bits)): + self.assertEqual(fd.class_index(bits), want) + self.assertEqual({want for _, want in table}, set(range(10))) + + def test_div_fixup_table(self): + one, two, three = self.ONE, self.TWO, self.THREE + e = lambda exp: exp << 52 # a biased exponent field with a zero fraction + qn2 = 0x7FF8000000000012 + table = [ + ("normal", three, one, one, three), + ("sign_out_negative_from_s1", three, self.NEG2, one, three | self.NZ), + ("sign_out_positive_both_negative", self.NEG3, self.NEG2, self.NEG1, three), + ("sign_out_clears_s0_sign", self.NEG3, one, one, three), + ("nan_s2_quiets_s2", one, one, self.SNAN, 0x7FF8000000000001), + ("nan_s2_beats_nan_s1", one, self.SNAN, qn2, qn2), + ("nan_s1_quiets_s1", one, self.SNAN, one, 0x7FF8000000000001), + ("nan_s2_beats_zero_over_zero", one, self.PZ, qn2, qn2), + ("zero_over_zero", one, self.PZ, self.NZ, 0xFFF8000000000000), + ("inf_over_inf", one, self.PINF, self.NINF, 0xFFF8000000000000), + ("x_over_inf_negative_zero", one, self.NINF, one, self.NZ), + ("x_over_inf_positive_zero", one, self.PINF, one, self.PZ), + ("zero_over_y", one, self.NEG2, self.NZ, self.PZ), + ("x_over_zero", one, self.NZ, one, self.NINF), + ("inf_over_y", one, self.NEG2, self.NINF, self.PINF), + ("nan_s0_to_signed_inf_isa_rule", self.QNAN, one, one, self.PINF), + ("nan_s0_to_signed_inf_negative", self.QNAN, self.NEG2, one, self.NINF), + ("underflow_edge_still_passes_s0", three, e(1075), e(1), three), + ("underflow_to_zero", three, e(1076), e(1), self.PZ), + ("underflow_beats_nan_s0", self.QNAN, e(1076), e(1), self.PZ), + ("overflow_edge_still_passes_s0", three, e(1), e(1024), three), + ("overflow_to_inf", three, e(1), e(1025), self.PINF), + ] + for name, s0, s1, s2, want in table: + with self.subTest(case=name): + self.assertEqual(fd.fixup(s0, s1, s2), want) + + def test_frexp_table(self): + half = 0x3FE0000000000000 + table = [ + (self.ONE, half, 1), (half, half, 0), (self.THREE, 0x3FE8000000000000, 2), (self.NEG2, self.NZ | half, 2), + (0xC020000000000000, self.NZ | half, 4), # -8 = -0.5 * 2**4 + (1, half, -1073), (3, 0x3FE8000000000000, -1072), # smallest subnormals + (0x000FFFFFFFFFFFFF, 0x3FEFFFFFFFFFFFFE, -1022), + (0x0010000000000000, half, -1021), (0x7FEFFFFFFFFFFFFF, 0x3FEFFFFFFFFFFFFF, 1024), + (self.PZ, self.PZ, 0), (self.NZ, self.NZ, 0), (self.PINF, self.PINF, 0), (self.NINF, self.NINF, 0), + (self.QNAN, self.QNAN, 0), (self.SNAN, self.SNAN, 0), + ] + for bits, mant, exp in table: + with self.subTest(bits=hex(bits)): + self.assertEqual(fd.frexp(bits), (mant, exp)) + + def test_add_bits_nan_inf_and_zero_table(self): + for a, b in ((self.QNAN, self.ONE), (self.ONE, self.QNAN), (self.SNAN, self.ONE), (self.QNAN, self.QNAN), + (self.PINF, self.NINF), (self.NINF, self.PINF), (self.QNAN, self.PINF)): + for mode in range(4): + with self.subTest(a=hex(a), b=hex(b), mode=mode): + self.assertTrue(fd.is_nan(fd.add_bits(a, b, mode))) + for a, b, want in ((self.PINF, self.ONE, self.PINF), (self.ONE, self.NINF, self.NINF), + (self.PINF, self.PINF, self.PINF), (self.NINF, self.NINF, self.NINF)): + for mode in range(4): + with self.subTest(a=hex(a), b=hex(b), mode=mode): + self.assertEqual(fd.add_bits(a, b, mode), want) + + def test_add_bits_exact_zero_sign_in_all_four_modes(self): + # IEEE 754-2019 6.3. Modes: 0 nearest even, 1 toward +inf, 2 toward -inf, 3 toward zero. + tiny = 1 # the smallest subnormal, so x + (-x) is an exact non-zero cancellation + cases = [ + ("+0 + +0", self.PZ, self.PZ, (self.PZ, self.PZ, self.PZ, self.PZ)), + ("-0 + -0", self.NZ, self.NZ, (self.NZ, self.NZ, self.NZ, self.NZ)), + ("+0 + -0", self.PZ, self.NZ, (self.PZ, self.PZ, self.NZ, self.PZ)), + ("-0 + +0", self.NZ, self.PZ, (self.PZ, self.PZ, self.NZ, self.PZ)), + ("1 + -1", self.ONE, self.NEG1, (self.PZ, self.PZ, self.NZ, self.PZ)), + ("-1 + 1", self.NEG1, self.ONE, (self.PZ, self.PZ, self.NZ, self.PZ)), + ("tiny + -tiny", tiny, tiny | self.NZ, (self.PZ, self.PZ, self.NZ, self.PZ)), + ] + for name, a, b, wants in cases: + for mode, want in enumerate(wants): + with self.subTest(case=name, mode=mode): + self.assertEqual(fd.add_bits(a, b, mode), want) + # A non-zero result keeps its own sign whatever the mode. + self.assertEqual(fd.add_bits(self.ONE, self.ONE, 2), self.TWO) + self.assertEqual(fd.add_bits(self.PZ, self.NEG1, 2), self.NEG1) + + # ---- --oracle hw: routed through tools/hw_oracle, compared with the reference (a fake stands in for the GPU) ---- + + class FakeHW: + """Answers each raw kernel with the reference's own result, as a hardware stand-in; flip corrupts v_trunc_f64.""" + device = "fake gfx1036" + + def __init__(self, flip=False, reason=None): + self.flip, self.reason, self.calls, self.closed = flip, reason, [], False + + def run(self, kernels): + self.calls.append(list(kernels)) + out = [] + for kernel in kernels: + if self.reason: + out.append(self.reason) + continue + try: + words = fd.ref_program(kernel.lines[:-3], True) # drop the store epilogue + except (fd.SkipCase, ArithmeticError, IndexError, KeyError, ValueError): + out.append("assembler rejected: fake") + continue + broken = self.flip and any(line.startswith("v_trunc_f64 ") for line in kernel.lines) # a planted hardware bug + out.append([words[0] ^ 1] + list(words[1:]) if broken else list(words)) + return out + + def close(self): + self.closed = True + + def run_main(self, fake, *args): + stdout, stderr = io.StringIO(), io.StringIO() + with mock.patch.object(fd, "open_hw_oracle", return_value=fake) as opener, \ + mock.patch.object(fd, "translate", side_effect=AssertionError("the translator must not run")), \ + contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): + code = fd.main(["--oracle", "hw", *args]) + return code, stdout.getvalue(), stderr.getvalue(), opener + + def test_hw_oracle_routes_programs_through_hw_oracle_and_uses_hw_arch(self): + fake = self.FakeHW() + code, out, _, opener = self.run_main(fake, "--hw-arch", "gfx1036", "--programs", "40", "--seed", "1") + self.assertEqual(code, 0, out) + opener.assert_called_once_with("gfx1036") + self.assertIn("hw: ", out) + self.assertIn(" 0 mismatch", out) + self.assertIn("fake gfx1036", out) + self.assertTrue(fake.closed) + self.assertEqual(len(fake.calls), 1) # one launch for the whole campaign + kernel = fake.calls[0][0] + self.assertEqual(kernel.lines[-1], "s_endpgm") + self.assertTrue(kernel.raw and kernel.threads == 1 and kernel.words == 4) + self.assertEqual(kernel.mode, fd.HW_MODE) + self.assertGreater(len(fake.calls[0]), 40) # sweep + programs + matches = int(out.split("hw: ")[1].split(" match")[0]) + self.assertGreater(matches, 60) + + def test_hw_oracle_with_known_runs_known_cases_against_the_reference(self): + fake = self.FakeHW() + code, out, _, _ = self.run_main(fake, "--known", "--programs", "20", "--seed", "2") + self.assertEqual(code, 0, out) + self.assertNotIn("KNOWN_DIVERGENCE", out) # translator-only exclusions do not apply to hardware + texts = [line for kernel in fake.calls[0] for line in kernel.lines] + self.assertTrue(any(" mul:2" in line for line in texts)) + self.assertTrue(any(" clamp" in line for line in texts)) + + def test_hw_oracle_mismatch_exits_1_and_shrinks_with_single_runs(self): + fake = self.FakeHW(flip=True) + code, out, _, _ = self.run_main(fake, "--ops", "v_trunc_f64", "--programs", "0") + self.assertEqual(code, 1, out) + self.assertIn("MISMATCH", out) + self.assertIn("minimal program:", out) + self.assertIn("v_trunc_f64", out) + self.assertGreater(len(fake.calls), 1) # the shrinker re-ran trial programs + self.assertTrue(all(len(batch) == 1 for batch in fake.calls[1:])) + self.assertTrue(fake.closed) + + def test_hw_oracle_skip_reason_from_runner_is_counted(self): + fake = self.FakeHW(reason="MODE dx10_clamp, ieee cannot be set on gfx1170") + code, out, _, _ = self.run_main(fake, "--ops", "v_trunc_f64", "--programs", "3") + self.assertEqual(code, 0, out) + self.assertIn("hardware: MODE dx10_clamp", out) + self.assertIn("0 match, 0 mismatch", out) + + def test_hw_oracle_unavailable_exits_77_without_running(self): + stderr = io.StringIO() + with mock.patch.object(fd, "open_hw_oracle", side_effect=fd.HWUnavailable("no AMD clang")), \ + contextlib.redirect_stderr(stderr): + code = fd.main(["--oracle", "hw", "--programs", "3"]) + self.assertEqual(code, 77) + self.assertIn("hardware oracle unavailable: no AMD clang", stderr.getvalue()) + + def test_hw_oracle_does_not_judge_approximate_transcendentals(self): + fake = self.FakeHW() + with tempfile.TemporaryDirectory() as tmp: + for op in ("v_rcp_f64", "v_rsq_f64", "v_sqrt_f64"): + status, reason, _, actual = fd.run_one([f"{op} v[8:9], 3.25"], "ps_f64_hw_approx", tmp, "hw", fake) + self.assertEqual(status, "skip") + self.assertIn("PROC-216", reason) + self.assertIsNone(actual) + self.assertEqual(fake.calls, []) + + def test_hw_oracle_open_failure_without_tools_is_hwunavailable(self): + env = dict(os.environ, LEONIDA_AMD_CLANG=os.path.join(ROOT, "tools", "no-such-clang.exe")) + with mock.patch.dict(os.environ, env), self.assertRaises(fd.HWUnavailable): + fd.open_hw_oracle("gfx1036") + def test_cli_exit_1_on_plantable_mismatch(self): original = fd.translate stdout = io.StringIO() diff --git a/tools/f64_diff.py b/tools/f64_diff.py index 8744a5c37..340f3d106 100644 --- a/tools/f64_diff.py +++ b/tools/f64_diff.py @@ -7,9 +7,10 @@ and executes their SPIR-V with the semantic one-lane interpreter. Only synthetic are created; no game files are read. The GPU path is deliberately optional. It translates the same fragment shader, runs it -through vk_harness, and reads back RGBA32F words. The hardware oracle is AMD-only and -returns 77 when the host has no configured AMD hw_oracle. ``--known`` runs known -divergence probes; a reproduced mismatch intentionally returns 1. +through vk_harness, and reads back RGBA32F words. ``--oracle hw`` runs the programs natively +on an AMD GPU through tools/hw_oracle (``--hw-arch`` selects the architecture) and compares +them with the reference; it returns 77 only when that oracle is unavailable. ``--known`` runs +known divergence probes; a reproduced mismatch intentionally returns 1. """ import argparse import gc @@ -72,6 +73,10 @@ class GPUUnavailable(Exception): pass +class HWUnavailable(Exception): + """No configured AMD hw_oracle on this host (tools/hw_oracle/); the CLI turns it into exit 77.""" + + def words_to_bits(lo, hi): return ((hi & M32) << 32) | (lo & M32) @@ -166,8 +171,13 @@ def add_bits(a, b, mode=0): if is_inf(a) or is_inf(b): af, bf = to_float(a), to_float(b) return from_float(af + bf) - negzero = (is_zero(a) and is_zero(b) and bool((a & b) >> 63)) or mode == 2 exact = to_fraction(a) + to_fraction(b) + # IEEE 754-2019 6.3: an exact zero sum of two zeros of the same sign keeps that sign in every mode; any other + # exact zero (opposite-signed zeros, or x + (-x)) is -0 only when rounding toward negative, +0 otherwise. + if is_zero(a) and is_zero(b) and (a ^ b) >> 63 == 0: + negzero = bool(a >> 63) + else: + negzero = mode == 2 return round_fraction(exact, mode, negzero) @@ -452,6 +462,31 @@ def run_gpu(lines, name, tmpdir, gpu): with open(raw, "rb") as f: return list(struct.unpack("<4I", f.read())) +# The float MODE the hardware kernels start with: the one docs/design.md infers for the game's shaders (the same as +# tools/fmisc_diff.py): IEEE off so output modifiers apply, DX10_CLAMP on. Directives an architecture cannot set make +# the program a counted skip (runner.Oracle.run returns the reason). +HW_MODE = {"ieee": 0, "dx10_clamp": 1, "denorm32": 0} + + +def hw_kernel(lines): + """A raw tools/hw_oracle kernel: the program on one lane, then v8..v11 stored at the output pointer.""" + from hw_oracle import asm + return asm.Kernel(list(lines) + ["v_mov_b32 v0, 0", "global_store_b128 v0, v[8:11], s[2:3]", "s_endpgm"], + wave=32, threads=1, words=4, raw=True, mode=HW_MODE) + + +def open_hw_oracle(arch=None): + """The AMD hardware oracle, or HWUnavailable when its tools or device are missing.""" + try: + from hw_oracle import runner + except ImportError as exc: + raise HWUnavailable(f"tools/hw_oracle cannot be imported: {exc}") from exc + try: + return runner.open_oracle(arch=arch) + except runner.Unavailable as exc: + raise HWUnavailable(str(exc)) from exc + + def rand_bits(rng): # Mostly finite normals, with signed zeros, infinities and NaNs for predicate/class coverage. if rng.random() < .2: @@ -578,7 +613,13 @@ def equivalent(a, b, kind="int"): return a == b -def run_one(lines, name, tmp, oracle="translator", gpu=None, include_known=False): +def run_one(lines, name, tmp, oracle="translator", gpu=None, include_known=False, hw_words=None): + """Compare one program with the reference. ``gpu`` is the prepared Vulkan context for --oracle gpu, or the open + hw_oracle for --oracle hw (whose result may be passed in as ``hw_words``: four words or a skip reason).""" + if oracle == "hw": + # The hardware runs every form natively, so the translator-only exclusions do not apply: compare it with the + # whole reference, the known cases included. + include_known = True if not include_known: for line in lines: if " mul:" in line or " div:" in line: @@ -593,6 +634,14 @@ def run_one(lines, name, tmp, oracle="translator", gpu=None, include_known=False return "skip", f"reference limitation: {type(exc).__name__}: {exc}", None, None if oracle == "gpu" and any(line.lstrip().startswith(("v_rsq_f64 ", "v_sqrt_f64 ")) for line in lines): return "skip", "GLSL.std.450 InverseSqrt/Sqrt double-precision result precision is implementation-defined", expected, None + if oracle == "hw": + if any(line.lstrip().startswith(("v_rcp_f64 ", "v_rsq_f64 ", "v_sqrt_f64 ")) for line in lines): + return "skip", ("native v_rcp_f64/v_rsq_f64/v_sqrt_f64 are approximations (about 26 bits, PROC-216) and " + "the reference is exact, so their result is not judged"), expected, None + actual = hw_words if hw_words is not None else gpu.run([hw_kernel(lines)])[0] + if isinstance(actual, str): return "skip", f"hardware: {actual}", expected, None + actual = [int(x) & M32 for x in actual] + return ("match", "", expected, actual) if equivalent(expected, actual, output_kind(lines)) else ("mismatch", "word comparison", expected, actual) try: actual = run_gpu(lines, name, tmp, gpu) if oracle == "gpu" else translate(lines, name, tmp) except (rdna2spirv.Unsupported, UnsupportedConstruct, SkipCase) as exc: return "skip", f"{type(exc).__name__}: {exc}", expected, None except (IndexError, KeyError, ValueError, OverflowError) as exc: return "skip", f"translator/interpreter limitation: {type(exc).__name__}: {exc}", expected, None @@ -626,7 +675,7 @@ def shrink(lines, expected, oracle="translator", gpu=None, gpu_ctx=None, tmpdir= def run_batch(ops, programs, seed, max_ops=1, sweep=True, allow_literal=True, known=False, all_failures=False, - oracle="translator", gpu=None): + oracle="translator", gpu=None, hw=None): counts = Counter(); skips = Counter(); failures = [] rng = random.Random(seed) sequence = [(op, True, None) for op in ops] if sweep else [] @@ -634,18 +683,24 @@ def run_batch(ops, programs, seed, max_ops=1, sweep=True, allow_literal=True, kn if known: sequence += [("v_div_fixup_f64" if label == "div-fixup-nan-s0" else "v_add_f64", True, label) for label in KNOWN_DIVERGENCES] + cases = [] + for idx, (op, is_sweep, known_case) in enumerate(sequence): + setup_lines, body_lines, _, _ = make_case(rng, op, allow_literal, known_case) + lines = setup_lines + body_lines + if not is_sweep and not known_case: + n_ops = rng.randint(1, max_ops) + for _ in range(n_ops - 1): + _, extra_body, _, _ = make_case(rng, rng.choice(ops), allow_literal) + lines.extend(extra_body) + cases.append((idx, lines, known_case)) + # One launch for the whole campaign; a failing program is re-run alone while it is shrunk. + hw_results = hw.run([hw_kernel(lines) for _, lines, _ in cases]) if oracle == "hw" else None with tempfile.TemporaryDirectory(prefix="f64-diff-") as tmp: - gpu_ctx = prepare_gpu(gpu, tmp) if oracle == "gpu" else None - for idx, (op, is_sweep, known_case) in enumerate(sequence): - setup_lines, body_lines, _, _ = make_case(rng, op, allow_literal, known_case) - lines = setup_lines + body_lines - if not is_sweep and not known_case: - n_ops = rng.randint(1, max_ops) - for _ in range(n_ops - 1): - _, extra_body, _, _ = make_case(rng, rng.choice(ops), allow_literal) - lines.extend(extra_body) + gpu_ctx = prepare_gpu(gpu, tmp) if oracle == "gpu" else hw if oracle == "hw" else None + for idx, lines, known_case in cases: status, reason, want, got = run_one(lines, f"ps_f64_{idx:05d}", tmp, oracle, gpu_ctx, - include_known=bool(known_case)) + include_known=bool(known_case), + hw_words=hw_results[idx] if hw_results is not None else None) if status == "skip": skips[reason] += 1 else: counts[status] += 1 if status == "mismatch": @@ -704,7 +759,7 @@ def main(argv=None): ap.add_argument("--oracle", choices=("translator", "gpu", "hw"), default="translator", help="translator (default), Vulkan GPU via vk_harness, or AMD hardware oracle") ap.add_argument("--exe", help="vk_harness executable for --oracle gpu") - ap.add_argument("--hw-arch", help="AMD hw_oracle architecture (if configured)") + ap.add_argument("--hw-arch", help="GPU architecture hw_oracle assembles for (default: detected)") args = ap.parse_args(argv) if args.programs < 0 or args.max_ops < 1: print("programs must be nonnegative and max-ops positive", file=sys.stderr); return 2 ops = [x.strip() for x in args.ops.split(",")] if args.ops else list(BASE) @@ -715,20 +770,25 @@ def main(argv=None): print("Excluded (not translated by main): v_mul_f64, v_min_f64, v_max_f64, v_fract_f64, v_cvt_f64_f32, v_ldexp_f64, v_mad_f64, v_cvt_i32_f64, v_cvt_u32_f64, v_div_scale_f64") return 0 if args.self_test: return 0 if self_test() else 1 - gpu = None + gpu = hw = None if args.oracle == "hw": - print("hardware oracle unavailable: this host has no configured AMD hw_oracle", file=sys.stderr); return 77 + try: hw = open_hw_oracle(args.hw_arch) + except HWUnavailable as exc: + print(f"hardware oracle unavailable: {exc}", file=sys.stderr); return 77 + print(f"hardware oracle: {getattr(hw, 'device', 'AMD GPU')}") if args.oracle == "gpu": ext = ".exe" if os.name == "nt" else "" gpu = args.exe or os.path.join(ROOT, "runtime", "build", "vk_harness" + ext) try: counts, skips, failures = run_batch(ops, args.programs, args.seed, args.max_ops, args.sweep, not args.no_literals, args.known, args.all_failures, - args.oracle, gpu) + args.oracle, gpu, hw) except GPUUnavailable as exc: print(f"GPU oracle unavailable: {exc}", file=sys.stderr); return 77 - except HarnessError as exc: + except (HarnessError, RuntimeError) as exc: print(f"harness error: {exc}", file=sys.stderr); return 2 + finally: + if hw is not None: hw.close() total = sum(counts.values()) + sum(skips.values()) print(f"{args.oracle}: {counts['match']} match, {counts['mismatch']} mismatch; {total} total, {dict(skips)} skips") if failures: