diff --git a/docs/testing.md b/docs/testing.md index ffe729d24f..7f0d070bcf 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -731,6 +731,22 @@ exits 77, so CI skips it. `image_fuzz.py --oracle hw` loads a linear texture thr its CPU model; add `--negative-control` to check that wrong models are caught. A gfx1150 (RDNA3.5) is not RDNA2: a match supports the model and does not prove RDNA2. Run these one at a time: a second job on the same GPU can hang it. +## Model oracle on any Vulkan GPU (no AMD hardware) + +`pk16_diff.py`, `vint_diff.py` and `sdwa_diff.py` judge their translated programs on a Vulkan GPU only against the words +a native AMD GPU produced (`--oracle hw,vk`). `tools/vk_model_fuzz.py` runs the same programs, for the same seed, on +whatever Vulkan GPU you have and judges them against the fuzzer's reference model instead: + +```sh +python -I tools/vk_model_fuzz.py pk16_diff --programs 1500 --seed 11 --build runtime/build +``` + +`--build` is the folder with `vk_compute_test`; `llvm-mc` with the AMDGPU target is needed as for `valu_fuzz.py`. It exits +0 when every judged program matched, 1 on a mismatch (the first few programs are printed), 2 when `vk_compute_test` is +missing and 77 when nothing could be judged. A program the model declines counts as a skip. A mismatch here is the GPU +disagreeing with the model, which is a driver difference, a translator bug or a model bug: re-read the program with +the fuzzer itself (`pk16_diff.py --seed S --programs N`) before reporting it. + ## Choosing the GPU With more than one GPU, pick one through the Vulkan loader, for example diff --git a/tests/test_vk_model_fuzz.py b/tests/test_vk_model_fuzz.py new file mode 100644 index 0000000000..717e7b3bb6 --- /dev/null +++ b/tests/test_vk_model_fuzz.py @@ -0,0 +1,169 @@ +"""Unit tests for tools/vk_model_fuzz.py: the Vulkan run of a diff fuzzer judged against its own reference model. + +The GPU is stood in for by a ``judge`` function, so the test needs no Vulkan device, llvm-mc or game files. + + python -I tests/test_vk_model_fuzz.py +""" +import contextlib +import io +import os +import random +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TOOLS_DIR = os.path.join(ROOT, "tools") +if TOOLS_DIR not in sys.path: + sys.path.insert(0, TOOLS_DIR) + +import pk16_diff # noqa: E402 +import vk_model_fuzz as vmf # noqa: E402 + + +def agreeing_judge(seen): + """A GPU that returns exactly the reference words: every program matches.""" + def judge(progs, want, verdict, **kwargs): + seen.update(progs=progs, want=want, kwargs=kwargs) + counts, bad = {}, [] + for i, (lines, words) in enumerate(zip(progs, want)): + if isinstance(words, str): + counts["skip: " + words] = counts.get("skip: " + words, 0) + 1 + continue + klass, detail = verdict(lines, words, list(words)) + counts[klass] = counts.get(klass, 0) + 1 + if klass == "mismatch": + bad.append((i, detail, lines)) + return counts, bad + return judge + + +def one_wrong_word_judge(progs, want, verdict, **kwargs): + """A GPU that flips one bit of the first judged program's first word.""" + counts, bad = {}, [] + flipped = False + for i, (lines, words) in enumerate(zip(progs, want)): + if isinstance(words, str): + counts["skip: " + words] = counts.get("skip: " + words, 0) + 1 + continue + got = list(words) + if not flipped: + got[0] ^= 1 + flipped = True + klass, detail = verdict(lines, words, got) + counts[klass] = counts.get(klass, 0) + 1 + if klass == "mismatch": + bad.append((i, detail, lines)) + return counts, bad + + +class RunTest(unittest.TestCase): + def test_programs_are_the_ones_the_fuzzer_generates_for_the_seed(self): + seen = {} + vmf.run("pk16_diff", 25, 7, 4, 32, None, None, judge=agreeing_judge(seen)) + rng = random.Random(7) + expected = [pk16_diff.generate(rng, rng.randrange(1, 5), list(pk16_diff.ALL_OPS)) for _ in range(25)] + self.assertEqual(seen["progs"], expected) + + def test_the_model_words_are_what_the_gpu_is_judged_against(self): + seen = {} + counts, bad = vmf.run("pk16_diff", 40, 3, 6, 32, None, None, judge=agreeing_judge(seen)) + self.assertEqual(bad, []) + self.assertEqual(sum(counts.values()), 40) + for lines, words in zip(seen["progs"], seen["want"]): + self.assertEqual(words, [w & 0xFFFFFFFF for w in pk16_diff.reference(lines)]) + + def test_sdwa_programs_are_not_assumed_uniform_across_lanes(self): + seen = {} + vmf.run("sdwa_diff", 10, 2, 3, 32, None, None, judge=agreeing_judge(seen)) + self.assertFalse(seen["kwargs"]["uniform"]) + seen.clear() + vmf.run("vint_diff", 10, 2, 3, 32, None, None, judge=agreeing_judge(seen)) + self.assertTrue(seen["kwargs"]["uniform"]) + + def test_a_program_the_model_declines_is_a_skip_with_a_reason(self): + with mock.patch.object(pk16_diff, "reference", side_effect=pk16_diff.Skip("not modelled")): + self.assertEqual(vmf.reference_words(pk16_diff, ["v_nop"]), "not modelled") + with mock.patch.object(pk16_diff, "reference", side_effect=pk16_diff.RefError("bad program")): + self.assertEqual(vmf.reference_words(pk16_diff, ["v_nop"]), "bad program") + + + def test_declined_programs_never_reach_the_gpu_and_mismatch_indexes_stay_original(self): + real = pk16_diff.reference + calls = [] + + def declining(lines): + calls.append(lines) + if len(calls) % 2 == 0: + raise pk16_diff.Skip("every other program") + return real(lines) + + seen = {} + with mock.patch.object(pk16_diff, "reference", side_effect=declining): + counts, bad = vmf.run("pk16_diff", 10, 5, 4, 32, None, None, judge=agreeing_judge(seen)) + self.assertEqual(len(seen["progs"]), 5) + self.assertEqual(counts.get("skip: model declines: every other program"), 5) + self.assertEqual(counts.get("match"), 5) + self.assertEqual(bad, []) + + calls.clear() + with mock.patch.object(pk16_diff, "reference", side_effect=declining): + counts, bad = vmf.run("pk16_diff", 10, 5, 4, 32, None, None, judge=one_wrong_word_judge) + self.assertEqual(len(bad), 1) + rng = random.Random(5) + progs = [pk16_diff.generate(rng, rng.randrange(1, 5), list(pk16_diff.ALL_OPS)) for _ in range(10)] + self.assertEqual(bad[0][2], progs[bad[0][0]]) + self.assertEqual(bad[0][0] % 2, 0) # the model declined the odd-numbered calls, so judged ones are even + + +class MainTest(unittest.TestCase): + def call(self, *argv, judge=None): + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + if judge is None: + code = vmf.main(list(argv)) + else: + real = vmf.run + + def with_judge(*a, **k): + return real(*a, judge=judge, **k) + with mock.patch.object(vmf, "run", side_effect=with_judge): + code = vmf.main(list(argv)) + return code, out.getvalue(), err.getvalue() + + def test_all_programs_matching_exits_zero(self): + code, out, _ = self.call("pk16_diff", "--programs", "20", "--seed", "4", judge=agreeing_judge({})) + self.assertEqual(code, 0) + self.assertIn("pk16_diff seed 4, 20 programs, wave 32:", out) + self.assertNotIn("MISMATCH", out) + + def test_a_wrong_word_exits_one_and_prints_the_program(self): + code, out, _ = self.call("vint_diff", "--programs", "20", "--seed", "4", judge=one_wrong_word_judge) + self.assertEqual(code, 1) + self.assertIn("MISMATCH program", out) + self.assertIn("\n ", out) + + def test_nothing_judged_exits_77(self): + with mock.patch.object(vmf, "run", return_value=({"skip: hardware: x": 3}, [])): + code, out, _ = self.call("pk16_diff", "--programs", "3") + self.assertEqual(code, 77) + + def test_a_folder_without_vk_compute_test_is_one_error_line_and_exit_two(self): + with tempfile.TemporaryDirectory() as folder: + code, out, err = self.call("pk16_diff", "--programs", "2", "--build", folder) + self.assertEqual(code, 2) + self.assertTrue(err.startswith("ERROR: "), err) + self.assertEqual(len(err.strip().splitlines()), 1, err) + self.assertNotIn("Traceback", err) + + def test_bad_arguments_are_a_usage_error(self): + for argv in (["pk16_diff", "--programs", "0"], ["pk16_diff", "--ops", "a,,b"], ["nope"]): + with self.subTest(argv=argv), contextlib.redirect_stderr(io.StringIO()): + with self.assertRaises(SystemExit) as caught: + vmf.main(argv) + self.assertEqual(caught.exception.code, 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/vk_model_fuzz.py b/tools/vk_model_fuzz.py new file mode 100644 index 0000000000..7d73111c73 --- /dev/null +++ b/tools/vk_model_fuzz.py @@ -0,0 +1,121 @@ +r"""Judge a diff fuzzer's translated programs on the local Vulkan GPU against its reference model. Standard library only. + +pk16_diff.py, vint_diff.py and sdwa_diff.py run their generated programs three ways: the reference model (written from +the RDNA2 ISA pseudocode), the translator on a CPU interpreter, and, with --oracle hw,vk, the translated SPIR-V on a +Vulkan GPU judged against the words a native AMD GPU produced. The last needs an AMD GPU. This tool is the same Vulkan +run without one: the programs the fuzzer would generate for the same seed go through the translator and +vk_compute_test, and each result is compared with the fuzzer's reference model. It answers "does this GPU and driver +agree with the model on these programs" for any Vulkan device, NVIDIA and Intel included. + + python -I tools/vk_model_fuzz.py pk16_diff --programs 1500 --seed 11 --build runtime/build + +--build is the folder with vk_compute_test (a Visual Studio configuration subfolder is found). llvm-mc with the AMDGPU +target is needed as for valu_fuzz.py (LLVM_MC, docs/testing.md). The programs for a seed are the ones +``pk16_diff.py --seed S --programs N`` generates, so a mismatch can be re-read with that tool. + +A program the reference model declines (the fuzzer's Skip or RefError) is counted as a skip, not judged. Exit code 0: +every judged program matched, 1: a mismatch, 2: bad arguments or no vk_compute_test, 77: nothing could be judged. +""" +import argparse +import importlib +import os +import random +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +FUZZERS = ("pk16_diff", "vint_diff", "sdwa_diff") +# The ``uniform`` argument each fuzzer's own run_suite passes to vk_fuzz_run.judge (sdwa_diff programs differ by lane). +UNIFORM = {"pk16_diff": True, "vint_diff": True, "sdwa_diff": False} + + +def default_ops(module): + """The fuzzer's own default op list: ALL_OPS, or every op of its OPS table (sdwa_diff).""" + if hasattr(module, "ALL_OPS"): + return list(module.ALL_OPS) + return sorted(module.OPS) + + +def reference_words(module, lines): + """The reference model's four words for one program, or a str saying why the model declines it.""" + try: + return [int(word) & 0xFFFFFFFF for word in module.reference(lines)] + except (module.Skip, module.RefError) as exc: + return str(exc) or type(exc).__name__ + + +def run(name, programs, seed, max_ops, wave, build, work, ops=None, judge=None): + """(counts, mismatches) for ``programs`` programs of fuzzer ``name``. + + counts maps a verdict class to how many programs got it; mismatches is [(index, detail, lines)]. ``judge`` is + vk_fuzz_run.judge unless a test passes its own.""" + import vk_fuzz_run + module = importlib.import_module(name) + if judge is None: + judge = vk_fuzz_run.judge + verdict = getattr(module, "vk_verdict", vk_fuzz_run.exact_verdict) + rng = random.Random(seed) + chosen = ops or default_ops(module) + progs = [module.generate(rng, rng.randrange(1, max_ops + 1), chosen) for _ in range(programs)] + want = [reference_words(module, lines) for lines in progs] + # The model's declined programs are not sent to the GPU; vk_fuzz_run.judge would label them as hardware skips. + judged = [i for i, words in enumerate(want) if not isinstance(words, str)] + counts = {} + for words in want: + if isinstance(words, str): + counts["skip: model declines: " + words] = counts.get("skip: model declines: " + words, 0) + 1 + bad = [] + if judged: + got_counts, got_bad = judge([progs[i] for i in judged], [want[i] for i in judged], verdict, wave=wave, + build=build, work_parent=work, opaque=True, uniform=UNIFORM[name]) + for klass, n in got_counts.items(): + counts[klass] = counts.get(klass, 0) + n + bad = [(judged[i], detail, lines) for i, detail, lines in got_bad] + return counts, bad + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("fuzzer", choices=FUZZERS) + ap.add_argument("--programs", type=int, default=300) + ap.add_argument("--seed", type=int, default=1) + ap.add_argument("--max-ops", type=int, default=6) + ap.add_argument("--ops", help="comma-separated opcodes (default: the fuzzer's own list)") + ap.add_argument("--wave", type=int, choices=(32, 64), default=32) + ap.add_argument("--build", help="the folder with vk_compute_test (default: runtime/build)") + ap.add_argument("--work", help="a folder for the temporary files") + ap.add_argument("--max-report", type=int, default=5, help="mismatching programs to print (default 5)") + args = ap.parse_args(argv) + if args.programs < 1 or args.max_ops < 1 or args.max_report < 0: + ap.error("--programs and --max-ops must be at least 1, --max-report at least 0") + ops = None + if args.ops is not None: + ops = [token.strip() for token in args.ops.split(",")] + if not all(ops): + ap.error("--ops must be a comma-separated list of opcodes") + try: + counts, bad = run(args.fuzzer, args.programs, args.seed, args.max_ops, args.wave, args.build, args.work, ops) + except FileNotFoundError as exc: + print(f"ERROR: {exc}", file=sys.stderr) + return 2 + summary = ", ".join(f"{klass} {n}" for klass, n in sorted(counts.items(), key=lambda kv: kv[0].startswith("skip"))) + print(f"{args.fuzzer} seed {args.seed}, {args.programs} programs, wave {args.wave}: {summary or 'nothing ran'}") + for index, detail, lines in bad[:args.max_report]: + print(f"MISMATCH program {index}: {detail}") + print("\n".join(" " + line for line in lines)) + if len(bad) > args.max_report: + print(f"... {len(bad) - args.max_report} more mismatching programs") + if bad: + return 1 + judged = sum(n for klass, n in counts.items() if not klass.startswith("skip")) + return 0 if judged else 77 + + +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: + pass + sys.exit(main())