diff options
| author | ItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com> | 2026-11-22 13:15:16 -0500 |
|---|---|---|
| committer | ItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com> | 2026-11-22 13:15:16 -0500 |
| commit | eefaba67db3decdcc67908c2ea151f4857cb761d (patch) | |
| tree | 619c601166c042a4d8c85b2cb167c9a1e83a0920 | |
| parent | d2fb429f763fa932516952f1ddc6f6bfb692748c (diff) | |
| parent | 91fb9d601af072b653ac9edea0680aff766b44cf (diff) | |
Merge pull request #2431 from Vonsek
| -rw-r--r-- | docs/shader_validation.md | 27 | ||||
| -rw-r--r-- | tests/test_pk16_diff.py | 218 | ||||
| -rw-r--r-- | tools/pk16_diff.py | 572 |
3 files changed, 817 insertions, 0 deletions
diff --git a/docs/shader_validation.md b/docs/shader_validation.md index a93019e87..4eb7116f8 100644 --- a/docs/shader_validation.md +++ b/docs/shader_validation.md | |||
| @@ -803,6 +803,33 @@ on gfx1150 (they were measured on RDNA2 and, for the vector part, on this GPU be | |||
| 803 | `idxen offen` and offset-only soffset forms are new on gfx1150). The one difference is `v_pack_b32_f16` quieting | 803 | `idxen offen` and offset-only soffset forms are new on gfx1150). The one difference is `v_pack_b32_f16` quieting |
| 804 | signaling NaNs (only signaling NaN halves are not judged; a quiet NaN is compared). The default translator path of `mem` ran on the Radeon 880M (`VK_LOADER_DRIVERS_SELECT=*amd*`, `vk_compute_test` built with g++ as in the lab script): `--family mem --programs 200 --seed 1` gave 400 of 400 programs (native wave64 and wave32) matching the model, 0 not translated, 0 harness errors, so the translator agrees with the model on the OOB_SELECT, straddle, `s_load` and `s_buffer_load` rules there. On the RTX 5070 `vk_compute_test` loses the device (-4) for this and for the unchanged generator of `main`, so use the AMD device. | 804 | signaling NaNs (only signaling NaN halves are not judged; a quiet NaN is compared). The default translator path of `mem` ran on the Radeon 880M (`VK_LOADER_DRIVERS_SELECT=*amd*`, `vk_compute_test` built with g++ as in the lab script): `--family mem --programs 200 --seed 1` gave 400 of 400 programs (native wave64 and wave32) matching the model, 0 not translated, 0 harness errors, so the translator agrees with the model on the OOB_SELECT, straddle, `s_load` and `s_buffer_load` rules there. On the RTX 5070 `vk_compute_test` loses the device (-4) for this and for the unchanged generator of `main`, so use the AMD device. |
| 805 | 805 | ||
| 806 | ### Packed and 16-bit integer VALU (`tools/pk16_diff.py`) | ||
| 807 | |||
| 808 | `valu_fuzz.py --family f16` runs the 16-bit shifts, `v_add/sub_nc_u16`, `v_mul_lo_u16` and the 16-bit min/max on | ||
| 809 | the GPU with VGPR sources. `tools/pk16_diff.py` adds the packed integer ops (`v_pk_add/sub_u16/i16`, | ||
| 810 | `v_pk_mul_lo_u16`, `v_pk_min/max_u16/i16`, `v_pk_mad_u16/i16` and the packed shifts) with `op_sel`, `op_sel_hi` and | ||
| 811 | `clamp`, and the 16-bit VOP3 ops (`v_add/sub_nc_i16`, `v_min3/max3/med3_u16/i16`, `v_mad_u16/i16` next to the ones | ||
| 812 | above) with `op_sel` on every source and on the destination half and `clamp`. Sources are VGPRs, SGPRs, integer and | ||
| 813 | float inline constants and literals within the constant-bus limits. It runs one lane through | ||
| 814 | `tests/semantic/spirv_mini_interp.py` against its own ISA model, with the shrinking, skips and exit codes of | ||
| 815 | `salu_diff.py`. A constant whose high half a packed add/sub/mul/min/max/mad reads is left out unless `--known` (the | ||
| 816 | translator rejects it; #2224 changes that). | ||
| 817 | |||
| 818 | Measured on an RDNA2 iGPU (gfx1036) with `--oracle hw`: 2,300 programs, the `--known` forms included, match the | ||
| 819 | model. A 16-bit VOP3 op keeps the other half of its destination. A constant source is its 32-bit value split like a | ||
| 820 | register: `-16` is `0xfff0`/`0xffff`, `1.0` is `0x0000`/`0x3f80` (f32 bits, unlike the f16 ops), and a literal of a | ||
| 821 | 16-bit VOP3 op has 16 bits (`0xffff` with `op_sel` reads 0). The VOP2-named 16-bit ops (`v_mul_lo_u16`, | ||
| 822 | `v_min/max_*16`, the shifts) only have a VOP3 encoding on GFX10, and the generator writes them with `_e64`, because | ||
| 823 | without encoding bytes the translator reads a bare mnemonic as the VOP2 write that zeroes the high half. For the same | ||
| 824 | reason, rules that depend on the encoding bytes, such as a literal's 12-byte VOP3 encoding (SHADER-208), are out of | ||
| 825 | its reach. | ||
| 826 | |||
| 827 | ``` | ||
| 828 | python -I tools/pk16_diff.py --programs 3000 --seed 11 --max-ops 8 | ||
| 829 | python -I tools/pk16_diff.py --oracle hw --programs 500 --seed 1 | ||
| 830 | python -I tests/test_pk16_diff.py | ||
| 831 | ``` | ||
| 832 | |||
| 806 | ### Wave and cross-lane ops on the GPU (`tools/crosslane_fuzz.py`, FUZZ-7) | 833 | ### Wave and cross-lane ops on the GPU (`tools/crosslane_fuzz.py`, FUZZ-7) |
| 807 | 834 | ||
| 808 | Cross-lane ops read other lanes, so like FUZZ-6 this runs on the GPU and not in the one-lane interpreter. | 835 | Cross-lane ops read other lanes, so like FUZZ-6 this runs on the GPU and not in the one-lane interpreter. |
diff --git a/tests/test_pk16_diff.py b/tests/test_pk16_diff.py new file mode 100644 index 000000000..372f066fe --- /dev/null +++ b/tests/test_pk16_diff.py | |||
| @@ -0,0 +1,218 @@ | |||
| 1 | """tools/pk16_diff.py: the packed and 16-bit integer reference against hand-worked values, a short seeded fuzz run, | ||
| 2 | and canaries. Standard library only; no GPU.""" | ||
| 3 | import contextlib | ||
| 4 | import io | ||
| 5 | import os | ||
| 6 | from pathlib import Path | ||
| 7 | import re | ||
| 8 | import subprocess | ||
| 9 | import sys | ||
| 10 | import unittest | ||
| 11 | |||
| 12 | TOOL = Path(__file__).resolve().parents[1] / "tools" / "pk16_diff.py" | ||
| 13 | sys.path.insert(0, str(TOOL.parent)) | ||
| 14 | import pk16_diff as d # noqa: E402 | ||
| 15 | |||
| 16 | M = d.M32 | ||
| 17 | |||
| 18 | |||
| 19 | def prefix(v=None, s=None): | ||
| 20 | return ([f"v_mov_b32_e32 v{r}, 0x{(v or {}).get(r, 0):x}" for r in d.VREGS] | ||
| 21 | + [f"s_mov_b32 s{r}, 0x{(s or {}).get(r, 0):x}" for r in d.SREGS]) | ||
| 22 | |||
| 23 | |||
| 24 | def run(*body, v=None, s=None, regs=(1, 2, 3, 4)): | ||
| 25 | """The reference's four exported words; v / s map register -> seed value (others are 0).""" | ||
| 26 | return d.reference(prefix(v, s) + list(body) + d.observe(list(regs))) | ||
| 27 | |||
| 28 | |||
| 29 | class Reference(unittest.TestCase): | ||
| 30 | def test_packed_halves_follow_op_sel_and_op_sel_hi(self): | ||
| 31 | v = {2: 0x00050003, 3: 0x00070002} | ||
| 32 | self.assertEqual(run("v_pk_add_u16 v1, v2, v3", v=v)[0], 0x000C0005) | ||
| 33 | # low result from (hi v2, lo v3) = 5 + 2, high result from (lo v2, lo v3) = 3 + 2 | ||
| 34 | self.assertEqual(run("v_pk_add_u16 v1, v2, v3 op_sel:[1,0] op_sel_hi:[0,0]", v=v)[0], 0x00050007) | ||
| 35 | self.assertEqual(run("v_pk_mul_lo_u16 v1, v2, v3", v={2: 0x01000100, 3: 0x01000101})[0], 0x00000100) | ||
| 36 | self.assertEqual(run("v_pk_max_i16 v1, v2, v3", v={2: 0x7FFF8000, 3: 0x80000001})[0], 0x7FFF0001) | ||
| 37 | self.assertEqual(run("v_pk_min_u16 v1, v2, v3", v={2: 0x7FFF8000, 3: 0x80000001})[0], 0x7FFF0001) | ||
| 38 | |||
| 39 | def test_clamp_saturates_and_its_absence_wraps(self): | ||
| 40 | v = {2: 0x7FFFFFFF, 3: 0x00010001} | ||
| 41 | self.assertEqual(run("v_pk_add_i16 v1, v2, v3", v=v)[0], 0x80000000) | ||
| 42 | self.assertEqual(run("v_pk_add_i16 v1, v2, v3 clamp", v=v)[0], 0x7FFF0000) # 0x7fff+1 sat; -1+1 = 0 | ||
| 43 | self.assertEqual(run("v_pk_add_u16 v1, v2, v3 clamp", v=v)[0], 0x8000FFFF) # 0xffff+1 sat | ||
| 44 | self.assertEqual(run("v_pk_sub_u16 v1, v3, v2 clamp", v=v)[0], 0) | ||
| 45 | self.assertEqual(run("v_pk_mad_i16 v1, v2, v3, v3 clamp", v={2: 0x80008000, 3: 0xFFFFFFFF})[0], 0x7FFF7FFF) | ||
| 46 | self.assertEqual(run("v_mad_u16 v1, v2, v2, 1 clamp", v={2: 0x100})[0], 0xFFFF) | ||
| 47 | self.assertEqual(run("v_sub_nc_i16 v1, v2, v3 clamp", v={2: 0x8000, 3: 1})[0], 0x8000) | ||
| 48 | |||
| 49 | def test_packed_shifts_use_the_low_four_bits(self): | ||
| 50 | self.assertEqual(run("v_pk_lshlrev_b16 v1, v2, v3", v={2: 0x00110001, 3: 0x00030003})[0], 0x00060006) | ||
| 51 | self.assertEqual(run("v_pk_ashrrev_i16 v1, v2, v3", v={2: 0x000F0004, 3: 0x8000F000})[0], 0xFFFFFF00) | ||
| 52 | |||
| 53 | def test_16bit_ops_keep_the_other_half(self): | ||
| 54 | v = {1: 0xAAAABBBB, 2: 0x00050003, 3: 0x00070002} | ||
| 55 | self.assertEqual(run("v_add_nc_u16 v1, v2, v3", v=v)[0], 0xAAAA0005) | ||
| 56 | # op_sel:[1,1,1]: high halves in, result to the high half, low half kept | ||
| 57 | self.assertEqual(run("v_add_nc_u16 v1, v2, v3 op_sel:[1,1,1]", v=v)[0], 0x000CBBBB) | ||
| 58 | self.assertEqual(run("v_max_u16_e64 v1, v2, v3 op_sel:[0,1,0]", v=v)[0], 0xAAAA0007) | ||
| 59 | self.assertEqual(run("v_med3_i16 v1, v2, -1, v3 op_sel:[0,0,0,1]", v=v)[0], 0x0002BBBB) | ||
| 60 | self.assertEqual(run("v_lshrrev_b16_e64 v1, 17, v2", v=v)[0], 0xAAAA0001) | ||
| 61 | |||
| 62 | def test_constants_are_their_32_bit_value(self): | ||
| 63 | # measured on gfx1036: an inline constant is split like a register; a float constant is its f32 bits; a | ||
| 64 | # 16-bit op's literal has 16 bits | ||
| 65 | self.assertEqual(run("v_add_nc_u16 v1, 1.0, 0 op_sel:[1,0,0]")[0], 0x3F80) | ||
| 66 | self.assertEqual(run("v_add_nc_u16 v1, 1.0, 0")[0], 0) | ||
| 67 | self.assertEqual(run("v_add_nc_u16 v1, -16, 0 op_sel:[1,0,0]")[0], 0xFFFF) | ||
| 68 | self.assertEqual(run("v_max_u16_e64 v1, 0.15915494, 0")[0], 0xF983) | ||
| 69 | self.assertEqual(run("v_add_nc_u16 v1, 0xffff, 0 op_sel:[1,0,0]")[0], 0) | ||
| 70 | self.assertEqual(run("v_pk_add_u16 v1, 0x12345678, 0")[0], 0x12345678) | ||
| 71 | self.assertEqual(run("v_pk_add_u16 v1, 1.0, 0")[0], 0x3F800000) | ||
| 72 | |||
| 73 | |||
| 74 | class Generator(unittest.TestCase): | ||
| 75 | def lines(self, known=False, literals=True, n=3000, seed=1): | ||
| 76 | real = d.KNOWN, d.LITERALS | ||
| 77 | d.KNOWN, d.LITERALS = known, literals | ||
| 78 | try: | ||
| 79 | gen = d.Gen(d.random.Random(seed)) | ||
| 80 | return [line for _ in range(n) for line in gen.op(d.ALL_OPS)] | ||
| 81 | finally: | ||
| 82 | d.KNOWN, d.LITERALS = real | ||
| 83 | |||
| 84 | @staticmethod | ||
| 85 | def split(line): | ||
| 86 | op, _, rest = line.partition(" ") | ||
| 87 | args, mods = d.parse(rest) | ||
| 88 | return op, args[1:], mods | ||
| 89 | |||
| 90 | def test_every_op_is_generated_with_its_modifiers(self): | ||
| 91 | lines = self.lines() | ||
| 92 | seen = {re.sub(r"_e64$", "", line.split()[0]) for line in lines} | ||
| 93 | self.assertEqual(set(d.ALL_OPS) - seen, set()) | ||
| 94 | for word in (" op_sel:", " op_sel_hi:", " clamp"): | ||
| 95 | self.assertTrue(any(word in line for line in lines), word) | ||
| 96 | for line in lines: | ||
| 97 | op, srcs, mods = self.split(line) | ||
| 98 | base = op[:-4] if op.endswith("_e64") else op | ||
| 99 | self.assertTrue(op.endswith("_e64") == (base in d.E64), line) | ||
| 100 | table = d.OPS_PK if base in d.OPS_PK else d.OPS_16 | ||
| 101 | n, _, cl = table[base] | ||
| 102 | self.assertEqual(len(srcs), n, line) | ||
| 103 | if "clamp" in mods: | ||
| 104 | self.assertIsNotNone(cl, line) | ||
| 105 | self.assertEqual(len(mods.get("op_sel", [0] * (n if base in d.OPS_PK else n + 1))), | ||
| 106 | n if base in d.OPS_PK else n + 1, line) | ||
| 107 | |||
| 108 | def test_sources_respect_the_constant_bus(self): | ||
| 109 | for line in self.lines(): | ||
| 110 | _, srcs, _ = self.split(line) | ||
| 111 | lits = [x for x in srcs if x.startswith("0x")] | ||
| 112 | self.assertLessEqual(len(lits), 1, line) | ||
| 113 | self.assertLessEqual(len(set(x for x in srcs if x.startswith("s")) | set(lits)), 2, line) | ||
| 114 | if not line.startswith("v_pk_"): | ||
| 115 | self.assertTrue(all(int(x, 16) <= 0xFFFF for x in lits), line) | ||
| 116 | self.assertFalse(any("0x" in line for line in self.lines(literals=False))) | ||
| 117 | |||
| 118 | def test_known_divergences_are_left_out_by_default(self): | ||
| 119 | def const_hi(lines): | ||
| 120 | for line in lines: | ||
| 121 | op, srcs, mods = self.split(line) | ||
| 122 | if op not in d.OPS_PK or op in d.PK_SHIFTS: | ||
| 123 | continue | ||
| 124 | n = len(srcs) | ||
| 125 | sel, hi = mods.get("op_sel", [0] * n), mods.get("op_sel_hi", [1] * n) | ||
| 126 | if any(d.is_const(x) and (sel[i] or hi[i]) for i, x in enumerate(srcs)): | ||
| 127 | return True | ||
| 128 | return False | ||
| 129 | self.assertFalse(const_hi(self.lines())) | ||
| 130 | self.assertTrue(const_hi(self.lines(known=True))) | ||
| 131 | |||
| 132 | |||
| 133 | class Translated(unittest.TestCase): | ||
| 134 | def test_harness_canaries(self): | ||
| 135 | with contextlib.redirect_stdout(io.StringIO()): | ||
| 136 | self.assertTrue(d.self_test()) | ||
| 137 | |||
| 138 | def test_short_seeded_run_matches(self): | ||
| 139 | counts, failures = d.run_suite(80, 5, 5, d.ALL_OPS) | ||
| 140 | self.assertEqual(failures, [], failures[:1]) | ||
| 141 | self.assertEqual(counts["skip"], {}) | ||
| 142 | self.assertEqual(counts["pass"], 80) | ||
| 143 | |||
| 144 | def test_hand_cases_match_the_translator(self): | ||
| 145 | seeds = {1: 0xAAAABBBB, 2: 0x7FFF8000, 3: 0x80000001, 4: 0x00050003, 5: 0x00070002} | ||
| 146 | cases = ["v_pk_add_i16 v1, v2, v3 clamp", "v_pk_sub_u16 v1, v3, v2 op_sel:[1,0] op_sel_hi:[0,1] clamp", | ||
| 147 | "v_pk_mad_i16 v1, v2, v3, s4 clamp", "v_pk_lshlrev_b16 v1, 17, v4", | ||
| 148 | "v_pk_mad_u16 v1, v4, 3, v5 op_sel_hi:[1,0,1]", "v_add_nc_u16 v1, v4, v5 op_sel:[1,1,1]", | ||
| 149 | "v_mad_i16 v1, v2, v3, -1 op_sel:[1,0,0,1] clamp", "v_med3_u16 v1, v2, 0x1234, v4 op_sel:[0,0,1,0]", | ||
| 150 | "v_max_i16_e64 v1, v2, v3 op_sel:[1,1,0]", "v_add_nc_u16 v1, 1.0, s5 op_sel:[0,0,1]", | ||
| 151 | "v_ashrrev_i16_e64 v1, -16, v2", "v_sub_nc_i16 v1, v2, v3 clamp"] | ||
| 152 | for case in cases: | ||
| 153 | with self.subTest(case=case): | ||
| 154 | self.assertIsNone(d.check(prefix(seeds, {4: 0x00030004, 5: 0xFFFF0001}) + [case] | ||
| 155 | + d.observe([1, 2, 3, 4]))) | ||
| 156 | |||
| 157 | def test_a_wrong_translation_is_caught(self): | ||
| 158 | lines = prefix({2: 5}) + ["v_pk_add_u16 v1, v2, 1 op_sel_hi:[1,0]"] + d.observe([1, 2, 3, 4]) | ||
| 159 | self.assertIsNone(d.check(lines)) | ||
| 160 | want = d.reference(lines) | ||
| 161 | real = d.translated | ||
| 162 | try: | ||
| 163 | d.translated = lambda _lines: [want[0] ^ 0x10000] + want[1:] | ||
| 164 | self.assertIn("word 0 (v1)", d.check(lines)) | ||
| 165 | finally: | ||
| 166 | d.translated = real | ||
| 167 | |||
| 168 | def test_shrinking_keeps_the_instruction_that_matters(self): | ||
| 169 | lines = d.generate(d.random.Random(2), 5, ["v_pk_add_u16", "v_add_nc_u16", "v_med3_i16"]) | ||
| 170 | body = lines[d.N_SEED:-d.N_OBS] | ||
| 171 | target = body[len(body) // 2] | ||
| 172 | real = d.translated | ||
| 173 | try: | ||
| 174 | d.translated = lambda l: [w ^ (1 if target in l else 0) for w in d.reference(l)] | ||
| 175 | small = d.shrink(lines) | ||
| 176 | finally: | ||
| 177 | d.translated = real | ||
| 178 | kept = [line for line in small if not line.startswith(("v_mov_b32_e32", "s_mov_b32"))] | ||
| 179 | self.assertEqual(kept, [target]) | ||
| 180 | |||
| 181 | |||
| 182 | class Cli(unittest.TestCase): | ||
| 183 | def main(self, *argv): | ||
| 184 | out = io.StringIO() | ||
| 185 | with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()): | ||
| 186 | try: | ||
| 187 | rc = d.main(list(argv)) | ||
| 188 | except SystemExit as e: | ||
| 189 | rc = e.code | ||
| 190 | return rc, out.getvalue() | ||
| 191 | |||
| 192 | def test_exit_codes(self): | ||
| 193 | rc, out = self.main("--list-ops") | ||
| 194 | self.assertEqual(rc, 0) | ||
| 195 | self.assertIn("v_pk_mad_i16", out) | ||
| 196 | self.assertEqual(self.main("--ops", "v_nope")[0], 2) | ||
| 197 | self.assertEqual(self.main("--oracle", "gpu")[0], 2) | ||
| 198 | rc, out = self.main("--programs", "5", "--seed", "1") | ||
| 199 | self.assertEqual(rc, 0, out) | ||
| 200 | real = d.translated | ||
| 201 | try: | ||
| 202 | d.translated = lambda l: [w ^ 1 for w in d.reference(l)] | ||
| 203 | rc, out = self.main("--programs", "3", "--seed", "1", "--ops", "v_pk_max_u16") | ||
| 204 | finally: | ||
| 205 | d.translated = real | ||
| 206 | self.assertEqual(rc, 1) | ||
| 207 | self.assertIn("MISMATCH", out) | ||
| 208 | |||
| 209 | def test_hardware_oracle_without_the_tools_exits_77(self): | ||
| 210 | env = dict(os.environ, LEONIDA_AMD_CLANG=str(TOOL.parent / "no-such-clang.exe")) | ||
| 211 | r = subprocess.run([sys.executable, "-I", str(TOOL), "--oracle", "hw", "--programs", "3"], | ||
| 212 | capture_output=True, text=True, env=env) | ||
| 213 | self.assertEqual(r.returncode, 77, r.stdout + r.stderr) | ||
| 214 | self.assertIn("unavailable", r.stdout) | ||
| 215 | |||
| 216 | |||
| 217 | if __name__ == "__main__": | ||
| 218 | unittest.main() | ||
diff --git a/tools/pk16_diff.py b/tools/pk16_diff.py new file mode 100644 index 000000000..0dc48929d --- /dev/null +++ b/tools/pk16_diff.py | |||
| @@ -0,0 +1,572 @@ | |||
| 1 | r"""Differential fuzzing of packed and 16-bit integer VALU (v_pk_* integer ops, 16-bit VOP3 integer ops). Standard | ||
| 2 | library only. | ||
| 3 | |||
| 4 | Generates seeded straight-line programs of 16-bit integer vector instructions, one lane, runs them through | ||
| 5 | |||
| 6 | * the reference below, written from the RDNA2 ISA guide's pseudocode for each opcode, and | ||
| 7 | * tools/rdna2spirv.py, executing the SPIR-V with tests/semantic/spirv_mini_interp.py (lane 0 of a wave32), | ||
| 8 | |||
| 9 | and compares four exported words bit for bit (v8..v11). The reference does not share code with the translator, with | ||
| 10 | tools/cpu_ref.py or with the other fuzzers. tools/valu_fuzz.py --family f16 runs some of the same opcodes on the GPU | ||
| 11 | with VGPR sources; this one adds the packed add/sub/mul/min/max/mad, the signed add/sub, min3/max3/med3 and mad, | ||
| 12 | clamp, and SGPR, inline-constant and literal sources in every position the encoding allows. | ||
| 13 | |||
| 14 | What is modelled, per instruction: | ||
| 15 | * v_pk_* (VOP3P, OPS_PK): each result half is the op on the halves its sources select: op_sel bit i picks the | ||
| 16 | half of source i for the low result, op_sel_hi bit i for the high result (default op_sel:[0,..], | ||
| 17 | op_sel_hi:[1,..]). clamp saturates the exact result of add/sub/mad to [0, 0xffff] or [-32768, 32767]; | ||
| 18 | without it the result wraps to 16 bits. Shift amounts are their low 4 bits. | ||
| 19 | * 16-bit VOP3 ops (OPS_16): op_sel bits 0..n-1 pick source halves, bit n (the last) the destination half. The | ||
| 20 | result is written to that half and the other half of vD is kept. clamp as above (v_add_nc_*16, v_sub_nc_*16, | ||
| 21 | v_mad_*16). On GFX10 these are VOP3 only: the VOP2 forms of v_mul_lo_u16, v_min/max_u16/i16 and the 16-bit | ||
| 22 | shifts do not exist (the assembler refuses v_mul_lo_u16_e32). LLVM prints their VOP3 form without a suffix | ||
| 23 | and the translator tells it from a VOP2 write (which zeroes the high half) by the listing's encoding bytes. | ||
| 24 | A program here has no encodings, so these are written with _e64. | ||
| 25 | * sources: VGPRs v0..v7 and v12..v19, SGPRs s4..s19, integer inline constants -16..64, float inline constants | ||
| 26 | (0.5, 1.0, 2.0, 4.0, their negatives, 1/(2*pi)) and literals, at most one literal and two scalar values per | ||
| 27 | instruction (the GFX10 constant bus). A constant is its 32-bit value split into halves like a register: -16 is | ||
| 28 | 0xfff0 / 0xffff, 1.0 is 0x0000 / 0x3f80 (its f32 bits, not the f16 constant of the f16 ops), a literal of a | ||
| 29 | 16-bit VOP3 op has 16 bits (the assembler rejects a wider one), so its high half is 0. | ||
| 30 | Every rule was checked against an RDNA2 GPU (AMD Radeon iGPU, gfx1036, Windows driver 26.10.1) with --oracle hw. | ||
| 31 | |||
| 32 | Not generated: neg_lo/neg_hi on the integer packed ops (the translator rejects them, their meaning on integers is | ||
| 33 | unmeasured), clamp on min/max/mul_lo/shifts, DPP and SDWA forms (tools/sdwa_diff.py), v_mad_u32_u16 and the other | ||
| 34 | 16x16->32 ops (tools/vint_diff.py), v_dot* (#2229), f16 ops (tools/valu_fuzz.py --family f16). | ||
| 35 | |||
| 36 | Known divergences (KNOWN_DIVERGENCES): by default the generator leaves out the forms where the translator is known to | ||
| 37 | differ from the hardware, so that a run shows new problems only; --known puts them back (a hardware-only run always | ||
| 38 | has them): | ||
| 39 | * pk-const-hi: a constant (inline or literal) in a packed add/sub/mul_lo/min/max/mad source whose high half | ||
| 40 | op_sel or op_sel_hi reads. The translator raises Unsupported (counted as a skip); #2224 removes that. | ||
| 41 | |||
| 42 | With --oracle hw the same programs also run natively on an AMD GPU (tools/hw_oracle/), one lane of a wave32 compute | ||
| 43 | dispatch, and the four words are compared with the reference: that validates the reference itself. Without the | ||
| 44 | oracle tools the run exits 77. | ||
| 45 | |||
| 46 | Usage: | ||
| 47 | python -I tools/pk16_diff.py [--programs N] [--seed S] [--max-ops N] [--ops v_pk_mad_u16,v_med3_i16] | ||
| 48 | python -I tools/pk16_diff.py --no-literals # sources without literals | ||
| 49 | python -I tools/pk16_diff.py --known # also the forms in KNOWN_DIVERGENCES | ||
| 50 | python -I tools/pk16_diff.py --oracle hw # hardware vs reference only | ||
| 51 | python -I tools/pk16_diff.py --oracle translator,hw | ||
| 52 | python -I tools/pk16_diff.py --list-ops | ||
| 53 | python -I tools/pk16_diff.py --self-test | ||
| 54 | |||
| 55 | Exit 0 when every program matches, 1 on a mismatch (the shortest failing program is printed after removing | ||
| 56 | instructions that do not matter), 2 on a harness error, 77 when the requested hardware oracle is unavailable. | ||
| 57 | Skips are counted with their reasons. | ||
| 58 | """ | ||
| 59 | import argparse | ||
| 60 | import gc | ||
| 61 | import os | ||
| 62 | import random | ||
| 63 | import re | ||
| 64 | import struct | ||
| 65 | import sys | ||
| 66 | import tempfile | ||
| 67 | import warnings | ||
| 68 | |||
| 69 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 70 | sys.dont_write_bytecode = True | ||
| 71 | if HERE not in sys.path: | ||
| 72 | sys.path.insert(0, HERE) | ||
| 73 | SEM_DIR = os.path.join(os.path.dirname(HERE), "tests", "semantic") | ||
| 74 | if SEM_DIR not in sys.path: | ||
| 75 | sys.path.insert(0, SEM_DIR) | ||
| 76 | |||
| 77 | M16 = 0xFFFF | ||
| 78 | M32 = 0xFFFFFFFF | ||
| 79 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 80 | |||
| 81 | VREGS = tuple(range(0, 8)) + tuple(range(12, 20)) # data VGPRs; v8..v11 are the observation | ||
| 82 | SREGS = tuple(range(4, 20)) # data SGPRs | ||
| 83 | N_SEED = len(VREGS) + len(SREGS) | ||
| 84 | N_OBS = 4 | ||
| 85 | INLINE_F = {"0.5": 0x3F000000, "-0.5": 0xBF000000, "1.0": 0x3F800000, "-1.0": 0xBF800000, "2.0": 0x40000000, | ||
| 86 | "-2.0": 0xC0000000, "4.0": 0x40800000, "-4.0": 0xC0800000, "0.15915494": 0x3E22F983} | ||
| 87 | HALVES = (0, 1, 2, 15, 16, 17, 0x7FFF, 0x8000, 0x8001, 0xFFFF, 0xFFFE, 0x00FF, 0x0100, 0x5555, 0xAAAA, 0x1234, | ||
| 88 | 0xFF00, 0x4000, 0xC000, 0x00F0) | ||
| 89 | |||
| 90 | |||
| 91 | class Skip(Exception): | ||
| 92 | pass | ||
| 93 | |||
| 94 | |||
| 95 | class RefError(Exception): | ||
| 96 | pass | ||
| 97 | |||
| 98 | |||
| 99 | def sx16(x): | ||
| 100 | x &= M16 | ||
| 101 | return x - 0x10000 if x & 0x8000 else x | ||
| 102 | |||
| 103 | |||
| 104 | def satu(v): | ||
| 105 | return max(0, min(M16, v)) | ||
| 106 | |||
| 107 | |||
| 108 | def sati(v): | ||
| 109 | return max(-32768, min(32767, v)) | ||
| 110 | |||
| 111 | |||
| 112 | def med3(a, b, c): | ||
| 113 | return sorted((a, b, c))[1] | ||
| 114 | |||
| 115 | |||
| 116 | # name -> (nsrc, fn on 16-bit source halves -> exact integer, clamp fn or None). The result keeps its low 16 bits. | ||
| 117 | OPS_PK = { | ||
| 118 | "v_pk_add_u16": (2, lambda a, b: a + b, satu), | ||
| 119 | "v_pk_add_i16": (2, lambda a, b: sx16(a) + sx16(b), sati), | ||
| 120 | "v_pk_sub_u16": (2, lambda a, b: a - b, satu), | ||
| 121 | "v_pk_sub_i16": (2, lambda a, b: sx16(a) - sx16(b), sati), | ||
| 122 | "v_pk_mul_lo_u16": (2, lambda a, b: a * b, None), | ||
| 123 | "v_pk_min_u16": (2, min, None), | ||
| 124 | "v_pk_max_u16": (2, max, None), | ||
| 125 | "v_pk_min_i16": (2, lambda a, b: min(sx16(a), sx16(b)), None), | ||
| 126 | "v_pk_max_i16": (2, lambda a, b: max(sx16(a), sx16(b)), None), | ||
| 127 | "v_pk_lshlrev_b16": (2, lambda a, b: b << (a & 15), None), | ||
| 128 | "v_pk_lshrrev_b16": (2, lambda a, b: b >> (a & 15), None), | ||
| 129 | "v_pk_ashrrev_i16": (2, lambda a, b: sx16(b) >> (a & 15), None), | ||
| 130 | "v_pk_mad_u16": (3, lambda a, b, c: a * b + c, satu), | ||
| 131 | "v_pk_mad_i16": (3, lambda a, b, c: sx16(a) * sx16(b) + sx16(c), sati), | ||
| 132 | } | ||
| 133 | PK_SHIFTS = ("v_pk_lshlrev_b16", "v_pk_lshrrev_b16", "v_pk_ashrrev_i16") | ||
| 134 | OPS_16 = { | ||
| 135 | "v_add_nc_u16": (2, lambda a, b: a + b, satu), | ||
| 136 | "v_sub_nc_u16": (2, lambda a, b: a - b, satu), | ||
| 137 | "v_add_nc_i16": (2, lambda a, b: sx16(a) + sx16(b), sati), | ||
| 138 | "v_sub_nc_i16": (2, lambda a, b: sx16(a) - sx16(b), sati), | ||
| 139 | "v_mul_lo_u16": (2, lambda a, b: a * b, None), | ||
| 140 | "v_min_u16": (2, min, None), | ||
| 141 | "v_max_u16": (2, max, None), | ||
| 142 | "v_min_i16": (2, lambda a, b: min(sx16(a), sx16(b)), None), | ||
| 143 | "v_max_i16": (2, lambda a, b: max(sx16(a), sx16(b)), None), | ||
| 144 | "v_lshlrev_b16": (2, lambda a, b: b << (a & 15), None), | ||
| 145 | "v_lshrrev_b16": (2, lambda a, b: b >> (a & 15), None), | ||
| 146 | "v_ashrrev_i16": (2, lambda a, b: sx16(b) >> (a & 15), None), | ||
| 147 | "v_min3_u16": (3, min, None), | ||
| 148 | "v_max3_u16": (3, max, None), | ||
| 149 | "v_med3_u16": (3, med3, None), | ||
| 150 | "v_min3_i16": (3, lambda a, b, c: min(sx16(a), sx16(b), sx16(c)), None), | ||
| 151 | "v_max3_i16": (3, lambda a, b, c: max(sx16(a), sx16(b), sx16(c)), None), | ||
| 152 | "v_med3_i16": (3, lambda a, b, c: med3(sx16(a), sx16(b), sx16(c)), None), | ||
| 153 | "v_mad_u16": (3, lambda a, b, c: a * b + c, satu), | ||
| 154 | "v_mad_i16": (3, lambda a, b, c: sx16(a) * sx16(b) + sx16(c), sati), | ||
| 155 | } | ||
| 156 | # GFX10 has only the VOP3 encoding of these (VOP2 names on earlier chips). LLVM prints them without a suffix and the | ||
| 157 | # translator then tells VOP3 from VOP2 by the listing's encoding bytes; a program here has none, so it says _e64. | ||
| 158 | E64 = ("v_mul_lo_u16", "v_min_u16", "v_max_u16", "v_min_i16", "v_max_i16", "v_lshlrev_b16", "v_lshrrev_b16", | ||
| 159 | "v_ashrrev_i16") | ||
| 160 | ALL_OPS = sorted(OPS_PK) + sorted(OPS_16) | ||
| 161 | |||
| 162 | KNOWN = False # also generate the forms in KNOWN_DIVERGENCES (--known; always on for a hardware-only run) | ||
| 163 | LITERALS = True | ||
| 164 | KNOWN_DIVERGENCES = { | ||
| 165 | "pk-const-hi": "a constant in a packed add/sub/mul_lo/min/max/mad source whose high half op_sel or op_sel_hi " | ||
| 166 | "reads: the translator raises Unsupported, #2224 reads the constant's 32-bit value", | ||
| 167 | } | ||
| 168 | |||
| 169 | |||
| 170 | # ---- program generation ------------------------------------------------------------------------------------- | ||
| 171 | |||
| 172 | def rand_value(rng): | ||
| 173 | r = rng.random() | ||
| 174 | if r < 0.5: | ||
| 175 | return rng.choice(HALVES) | (rng.choice(HALVES) << 16) | ||
| 176 | if r < 0.6: | ||
| 177 | return rng.randrange(0, 64) | ||
| 178 | return rng.getrandbits(32) | ||
| 179 | |||
| 180 | |||
| 181 | def is_const(tok): | ||
| 182 | return not re.fullmatch(r"[vs]\d+", tok) | ||
| 183 | |||
| 184 | |||
| 185 | class Gen: | ||
| 186 | def __init__(self, rng): | ||
| 187 | self.r = rng | ||
| 188 | |||
| 189 | def vreg(self): | ||
| 190 | return f"v{self.r.choice(VREGS)}" | ||
| 191 | |||
| 192 | def const(self, lit_ok, lit16): | ||
| 193 | r = self.r | ||
| 194 | k = r.random() | ||
| 195 | if k < 0.25: | ||
| 196 | return r.choice(tuple(INLINE_F)) | ||
| 197 | if k < 0.6 or not lit_ok: | ||
| 198 | return str(r.randint(-16, 64)) | ||
| 199 | v = rand_value(r) & (M16 if lit16 else M32) | ||
| 200 | if v <= 64: | ||
| 201 | v = 0x1234 if lit16 else 0x12345678 | ||
| 202 | return f"0x{v:x}" | ||
| 203 | |||
| 204 | def srcs(self, n, lit16, const_ok): | ||
| 205 | """n sources: at most one literal and two scalar values (the literal counted among them). const_ok[i]: a | ||
| 206 | constant may go in source i.""" | ||
| 207 | r = self.r | ||
| 208 | out, bus, lit = [], set(), False | ||
| 209 | for i in range(n): | ||
| 210 | k = r.random() | ||
| 211 | if k < 0.5: | ||
| 212 | out.append(self.vreg()) | ||
| 213 | elif k < 0.75 or not const_ok[i]: | ||
| 214 | s = f"s{r.choice(SREGS)}" | ||
| 215 | if s not in bus and len(bus) >= 2: | ||
| 216 | out.append(self.vreg()) | ||
| 217 | continue | ||
| 218 | bus.add(s) | ||
| 219 | out.append(s) | ||
| 220 | else: | ||
| 221 | c = self.const(LITERALS and not lit and len(bus) < 2, lit16) | ||
| 222 | if c.startswith("0x"): | ||
| 223 | lit = True | ||
| 224 | bus.add("lit") | ||
| 225 | out.append(c) | ||
| 226 | return out | ||
| 227 | |||
| 228 | def op(self, ops): | ||
| 229 | r = self.r | ||
| 230 | name = r.choice(ops) | ||
| 231 | d = r.choice(VREGS) | ||
| 232 | if name in OPS_PK: | ||
| 233 | n, _, cl = OPS_PK[name] | ||
| 234 | sel = [int(r.random() < 0.3) for _ in range(n)] | ||
| 235 | hi = [int(r.random() < 0.7) for _ in range(n)] | ||
| 236 | free = KNOWN or name in PK_SHIFTS | ||
| 237 | srcs = self.srcs(n, False, [free or not (sel[i] or hi[i]) for i in range(n)]) | ||
| 238 | line = f"{name} v{d}, {', '.join(srcs)}" | ||
| 239 | if any(sel): | ||
| 240 | line += f" op_sel:[{','.join(map(str, sel))}]" | ||
| 241 | if not all(hi): | ||
| 242 | line += f" op_sel_hi:[{','.join(map(str, hi))}]" | ||
| 243 | if cl and r.random() < 0.3: | ||
| 244 | line += " clamp" | ||
| 245 | return [line] | ||
| 246 | n, _, cl = OPS_16[name] | ||
| 247 | line = f"{name}{'_e64' if name in E64 else ''} v{d}, {', '.join(self.srcs(n, True, [True] * n))}" | ||
| 248 | sel = [int(r.random() < 0.3) for _ in range(n + 1)] | ||
| 249 | if any(sel): | ||
| 250 | line += f" op_sel:[{','.join(map(str, sel))}]" | ||
| 251 | if cl and r.random() < 0.3: | ||
| 252 | line += " clamp" | ||
| 253 | return [line] | ||
| 254 | |||
| 255 | |||
| 256 | def seeds(rng): | ||
| 257 | return ([f"v_mov_b32_e32 v{v}, 0x{rand_value(rng):x}" for v in VREGS] | ||
| 258 | + [f"s_mov_b32 s{s}, 0x{rand_value(rng):x}" for s in SREGS]) | ||
| 259 | |||
| 260 | |||
| 261 | def observe(regs): | ||
| 262 | return [f"v_mov_b32_e32 v{8 + i}, v{r}" for i, r in enumerate(regs)] | ||
| 263 | |||
| 264 | |||
| 265 | def generate(rng, n_ops, ops): | ||
| 266 | gen = Gen(rng) | ||
| 267 | body = [] | ||
| 268 | for _ in range(n_ops): | ||
| 269 | body += gen.op(ops) | ||
| 270 | written = [] | ||
| 271 | for line in reversed(body): | ||
| 272 | dst = int(line.split()[1].rstrip(",")[1:]) | ||
| 273 | if dst not in written: | ||
| 274 | written.append(dst) | ||
| 275 | regs = written[:4] | ||
| 276 | regs += [rng.choice(VREGS) for _ in range(4 - len(regs))] | ||
| 277 | return seeds(rng) + body + observe(regs) | ||
| 278 | |||
| 279 | |||
| 280 | # ---- the reference interpreter -------------------------------------------------------------------------------- | ||
| 281 | |||
| 282 | _MOD = re.compile(r"\s+(op_sel|op_sel_hi):\[([01,]+)\]|\s+(clamp)\b") | ||
| 283 | |||
| 284 | |||
| 285 | def parse(rest): | ||
| 286 | """Operands and modifiers of one instruction.""" | ||
| 287 | mods = {} | ||
| 288 | for m in _MOD.finditer(rest): | ||
| 289 | if m.group(3): | ||
| 290 | mods["clamp"] = True | ||
| 291 | else: | ||
| 292 | mods[m.group(1)] = [int(x) for x in m.group(2).split(",")] | ||
| 293 | rest = _MOD.sub("", rest) | ||
| 294 | return [a.strip() for a in rest.split(",")], mods | ||
| 295 | |||
| 296 | |||
| 297 | def value(tok, st): | ||
| 298 | if re.fullmatch(r"v\d+", tok): | ||
| 299 | return st["v"].get(int(tok[1:]), 0) | ||
| 300 | if re.fullmatch(r"s\d+", tok): | ||
| 301 | if tok not in st["s"]: | ||
| 302 | raise RefError(f"{tok} read before it is written") | ||
| 303 | return st["s"][tok] | ||
| 304 | if tok in INLINE_F: | ||
| 305 | return INLINE_F[tok] | ||
| 306 | return int(tok, 0) & M32 | ||
| 307 | |||
| 308 | |||
| 309 | def half(v, hi): | ||
| 310 | return (v >> 16) & M16 if hi else v & M16 | ||
| 311 | |||
| 312 | |||
| 313 | def reference(lines): | ||
| 314 | """Run the program; returns the four exported words.""" | ||
| 315 | st = {"v": {}, "s": {}} | ||
| 316 | for line in lines: | ||
| 317 | op, _, rest = line.partition(" ") | ||
| 318 | args, mods = parse(rest) | ||
| 319 | if op == "s_mov_b32": | ||
| 320 | st["s"][args[0]] = value(args[1], st) | ||
| 321 | continue | ||
| 322 | d = int(args[0][1:]) | ||
| 323 | vals = [value(a, st) for a in args[1:]] | ||
| 324 | if op == "v_mov_b32_e32": | ||
| 325 | st["v"][d] = vals[0] | ||
| 326 | continue | ||
| 327 | if op in OPS_PK: | ||
| 328 | n, fn, cl = OPS_PK[op] | ||
| 329 | out = 0 | ||
| 330 | for k, sel in enumerate((mods.get("op_sel", [0] * n), mods.get("op_sel_hi", [1] * n))): | ||
| 331 | r = fn(*[half(v, sel[i]) for i, v in enumerate(vals)]) | ||
| 332 | if mods.get("clamp") and cl: | ||
| 333 | r = cl(r) | ||
| 334 | out |= (r & M16) << (16 * k) | ||
| 335 | st["v"][d] = out | ||
| 336 | continue | ||
| 337 | op = op[:-4] if op.endswith("_e64") and op[:-4] in E64 else op | ||
| 338 | if op not in OPS_16: | ||
| 339 | raise RefError(f"{op} is not modelled") | ||
| 340 | n, fn, cl = OPS_16[op] | ||
| 341 | sel = mods.get("op_sel", [0] * (n + 1)) | ||
| 342 | r = fn(*[half(v, sel[i]) for i, v in enumerate(vals)]) | ||
| 343 | if mods.get("clamp") and cl: | ||
| 344 | r = cl(r) | ||
| 345 | old = st["v"].get(d, 0) | ||
| 346 | st["v"][d] = ((old & M16) | ((r & M16) << 16)) if sel[n] else ((old & 0xFFFF0000) | (r & M16)) | ||
| 347 | return [st["v"].get(8 + i, 0) for i in range(4)] | ||
| 348 | |||
| 349 | |||
| 350 | # ---- the translator side ----------------------------------------------------------------------------------- | ||
| 351 | |||
| 352 | def translated(lines, name="ps_pk16"): | ||
| 353 | """Translate and execute; returns the four exported words, or raises Skip.""" | ||
| 354 | import rdna2spirv | ||
| 355 | from spirv_mini_interp import run_fragment | ||
| 356 | with tempfile.TemporaryDirectory(prefix="pk16-diff-") as tmp: | ||
| 357 | dis = os.path.join(tmp, "disasm") | ||
| 358 | os.mkdir(dis) | ||
| 359 | path = os.path.join(dis, name + ".s") | ||
| 360 | with open(path, "w", encoding="utf-8", newline="\n") as f: | ||
| 361 | f.write(f"; {name} pk16_diff case\n") | ||
| 362 | for line in lines: | ||
| 363 | f.write("\t" + line + "\n") | ||
| 364 | f.write("\texp mrt0 v8, v9, v10, v11 done vm\n\ts_endpgm\n") | ||
| 365 | with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: | ||
| 366 | f.write(STUB_DXBC) | ||
| 367 | try: | ||
| 368 | with warnings.catch_warnings(): | ||
| 369 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 370 | spvasm = rdna2spirv.translate(path) | ||
| 371 | gc.collect() | ||
| 372 | except rdna2spirv.Unsupported as e: | ||
| 373 | raise Skip(f"translator unsupported: {e}") from None | ||
| 374 | try: | ||
| 375 | out = run_fragment(spvasm) | ||
| 376 | except Exception as e: # noqa: BLE001 - an interpreter gap is a counted skip, never a pass | ||
| 377 | raise Skip(f"mini_interp: {type(e).__name__}: {str(e)[:80]}") from None | ||
| 378 | return [w & M32 for w in out["%out_mrt0"]] | ||
| 379 | |||
| 380 | |||
| 381 | def hw_kernel(lines): | ||
| 382 | """A raw kernel for tools/hw_oracle: the program on one lane, then v8..v11 stored at the output pointer.""" | ||
| 383 | from hw_oracle import asm | ||
| 384 | return asm.Kernel(list(lines) + ["v_mov_b32 v0, 0", "global_store_b128 v0, v[8:11], s[2:3]", "s_endpgm"], | ||
| 385 | wave=32, threads=1, words=4, raw=True) | ||
| 386 | |||
| 387 | |||
| 388 | # ---- comparison, shrinking, the run -------------------------------------------------------------------------- | ||
| 389 | |||
| 390 | def _diff(lines, want, got, label): | ||
| 391 | bad = [k for k in range(4) if want[k] != got[k]] | ||
| 392 | if not bad: | ||
| 393 | return None | ||
| 394 | i = bad[0] | ||
| 395 | return f"word {i} ({lines[-N_OBS + i].split(', ')[1]}): reference 0x{want[i]:08x}, {label} 0x{got[i]:08x}" | ||
| 396 | |||
| 397 | |||
| 398 | def check(lines, backends=("translator",), hw=None): | ||
| 399 | """None on a match, else a description. Raises Skip (every backend skipped) / RefError. | ||
| 400 | hw is the hardware result for this program (four words or a str reason), or a callable lines -> that.""" | ||
| 401 | want = reference(lines) | ||
| 402 | problems, skips = [], [] | ||
| 403 | if "translator" in backends: | ||
| 404 | try: | ||
| 405 | problems.append(_diff(lines, want, translated(lines), "translated")) | ||
| 406 | except Skip as e: | ||
| 407 | skips.append(e) | ||
| 408 | if "hw" in backends: | ||
| 409 | got = hw(lines) if callable(hw) else hw | ||
| 410 | if isinstance(got, str): | ||
| 411 | skips.append(Skip(f"hardware: {got}")) | ||
| 412 | else: | ||
| 413 | problems.append(_diff(lines, want, got, "hardware")) | ||
| 414 | if skips and len(skips) == len(backends): | ||
| 415 | raise skips[0] | ||
| 416 | return "; ".join(p for p in problems if p) or None | ||
| 417 | |||
| 418 | |||
| 419 | def shrink(lines, check_fn=check): | ||
| 420 | """Observe one register if that still fails, drop instructions while the program still mismatches, then the | ||
| 421 | seeds of registers nothing reads.""" | ||
| 422 | def fails(trial): | ||
| 423 | try: | ||
| 424 | return bool(check_fn(trial)) | ||
| 425 | except (Skip, RefError): | ||
| 426 | return False | ||
| 427 | seed, body, obs = lines[:N_SEED], lines[N_SEED:-N_OBS], lines[-N_OBS:] | ||
| 428 | for line in obs: | ||
| 429 | one = [line.replace(line.split()[1], f"v{8 + i},") for i in range(4)] | ||
| 430 | if fails(seed + body + one): | ||
| 431 | obs = one | ||
| 432 | break | ||
| 433 | changed = True | ||
| 434 | while changed: | ||
| 435 | changed = False | ||
| 436 | for i in range(len(body) - 1, -1, -1): | ||
| 437 | trial = body[:i] + body[i + 1:] | ||
| 438 | if fails(seed + trial + obs): | ||
| 439 | body, changed = trial, True | ||
| 440 | used = set() | ||
| 441 | for line in body: | ||
| 442 | used |= set(re.findall(r"\b[vs]\d+\b", line)) # a 16-bit write keeps the other half of vD: it reads vD | ||
| 443 | for line in obs: | ||
| 444 | used |= set(re.findall(r"\b[vs]\d+\b", line.partition(" ")[2])) | ||
| 445 | seed = [line for line in seed if line.split()[1].rstrip(",") in used] | ||
| 446 | return seed + body + obs | ||
| 447 | |||
| 448 | |||
| 449 | def run_suite(programs, seed, max_ops, ops, backends=("translator",), oracle=None): | ||
| 450 | counts = {"pass": 0, "mismatch": 0, "skip": {}} | ||
| 451 | failures = [] | ||
| 452 | rng = random.Random(seed) | ||
| 453 | progs = [generate(rng, rng.randrange(1, max_ops + 1), ops) for _ in range(programs)] | ||
| 454 | hw = oracle.run([hw_kernel(p) for p in progs]) if "hw" in backends else [None] * programs | ||
| 455 | for i, lines in enumerate(progs): | ||
| 456 | try: | ||
| 457 | problem = check(lines, backends, hw[i]) | ||
| 458 | except Skip as e: | ||
| 459 | counts["skip"][str(e)] = counts["skip"].get(str(e), 0) + 1 | ||
| 460 | continue | ||
| 461 | if problem is None: | ||
| 462 | counts["pass"] += 1 | ||
| 463 | continue | ||
| 464 | counts["mismatch"] += 1 | ||
| 465 | failures.append((i, problem, lines)) | ||
| 466 | return counts, failures | ||
| 467 | |||
| 468 | |||
| 469 | def self_test(): | ||
| 470 | """Harness canaries: a hand program matches, the reference gives hand-worked values, a bad form is a skip.""" | ||
| 471 | base = [f"v_mov_b32_e32 v{v}, 0x{0x00010001 * v:x}" for v in VREGS] + [f"s_mov_b32 s{s}, {s}" for s in SREGS] | ||
| 472 | body = ["v_pk_add_u16 v1, v2, s4 op_sel:[1,0] op_sel_hi:[0,0]", # lo: 2 + 4, hi: 2 + 4 | ||
| 473 | "v_pk_mad_i16 v3, v3, -1, v5 op_sel_hi:[1,0,1] clamp", # -1 in both halves: 5 - 3 | ||
| 474 | "v_mad_u16 v4, v6, 0x8000, v7 op_sel:[0,0,0,1] clamp", # 6 * 0x8000 + 7 saturates; high half | ||
| 475 | "v_max3_i16 v2, v2, -16, s5 op_sel:[0,0,0,0]"] | ||
| 476 | lines = base + body + observe([1, 3, 4, 2]) | ||
| 477 | ok = check(lines) is None | ||
| 478 | worked = reference(lines) == [0x00060006, 0x00020002, 0xFFFF0004, 0x00020005] | ||
| 479 | try: | ||
| 480 | translated(base + ["v_pk_add_u16_sdwa_dpp v1, v2, v3"] + observe([1, 2, 3, 4])) | ||
| 481 | skipped = False | ||
| 482 | except Skip: | ||
| 483 | skipped = True | ||
| 484 | print(f"self-test: match {ok}, hand values {worked}, unsupported form skipped {skipped}") | ||
| 485 | return ok and worked and skipped | ||
| 486 | |||
| 487 | |||
| 488 | def main(argv=None): | ||
| 489 | ap = argparse.ArgumentParser(description="Packed and 16-bit integer VALU differential fuzzing.") | ||
| 490 | ap.add_argument("--programs", type=int, default=300) | ||
| 491 | ap.add_argument("--seed", type=int, default=1) | ||
| 492 | ap.add_argument("--max-ops", type=int, default=6) | ||
| 493 | ap.add_argument("--ops", default=None, help="comma-separated opcodes (--list-ops)") | ||
| 494 | ap.add_argument("--no-literals", action="store_true", help="no literal sources") | ||
| 495 | ap.add_argument("--list-ops", action="store_true") | ||
| 496 | ap.add_argument("--self-test", action="store_true") | ||
| 497 | ap.add_argument("--all-failures", action="store_true", help="print every failing program, not just the first") | ||
| 498 | ap.add_argument("--known", action="store_true", | ||
| 499 | help="also generate the forms where the translator is known to differ (KNOWN_DIVERGENCES; " | ||
| 500 | "always on with --oracle hw alone)") | ||
| 501 | ap.add_argument("--oracle", default="translator", | ||
| 502 | help="comma-separated comparison targets: translator (default), hw (natively on an AMD GPU; see " | ||
| 503 | "tools/hw_oracle/). 'hw' alone compares the hardware with the reference only") | ||
| 504 | ap.add_argument("--hw-arch", default=None, help="GPU architecture to assemble for (default: detected)") | ||
| 505 | a = ap.parse_args(argv) | ||
| 506 | if a.programs < 1 or a.max_ops < 1: | ||
| 507 | ap.error("--programs and --max-ops must be at least 1") | ||
| 508 | backends = tuple(dict.fromkeys(t.strip() for t in a.oracle.split(","))) | ||
| 509 | if not backends or any(t not in ("translator", "hw") for t in backends): | ||
| 510 | ap.error("--oracle takes translator, hw or translator,hw") | ||
| 511 | global KNOWN, LITERALS | ||
| 512 | KNOWN = a.known or backends == ("hw",) | ||
| 513 | LITERALS = not a.no_literals | ||
| 514 | if a.list_ops: | ||
| 515 | for name in ALL_OPS: | ||
| 516 | if name in OPS_PK: | ||
| 517 | n, _, cl = OPS_PK[name] | ||
| 518 | print(f"{name:18} VOP3P, {n} sources, op_sel/op_sel_hi{', clamp' if cl else ''}") | ||
| 519 | else: | ||
| 520 | n, _, cl = OPS_16[name] | ||
| 521 | print(f"{name:18} VOP3, {n} sources, op_sel (sources and destination half){', clamp' if cl else ''}") | ||
| 522 | return 0 | ||
| 523 | if a.self_test: | ||
| 524 | return 0 if self_test() else 1 | ||
| 525 | if a.ops is not None: | ||
| 526 | tokens = [t.strip() for t in a.ops.split(",")] | ||
| 527 | if not any(tokens) or any(not t for t in tokens): | ||
| 528 | ap.error("--ops must be a comma-separated list of opcodes") | ||
| 529 | ops = sorted(set(tokens)) | ||
| 530 | else: | ||
| 531 | ops = list(ALL_OPS) | ||
| 532 | unknown = [o for o in ops if o not in ALL_OPS] | ||
| 533 | if unknown: | ||
| 534 | ap.error("unknown ops: " + ", ".join(unknown)) | ||
| 535 | oracle = None | ||
| 536 | if "hw" in backends: | ||
| 537 | from hw_oracle import runner | ||
| 538 | try: | ||
| 539 | oracle = runner.open_oracle(arch=a.hw_arch) | ||
| 540 | except runner.Unavailable as e: | ||
| 541 | print(f"hardware oracle unavailable: {e}") | ||
| 542 | return 77 | ||
| 543 | print(f"hardware oracle: {oracle.device}") | ||
| 544 | try: | ||
| 545 | counts, failures = run_suite(a.programs, a.seed, a.max_ops, ops, backends, oracle) | ||
| 546 | skips = sum(counts["skip"].values()) | ||
| 547 | print(f"{a.programs} programs (seed {a.seed}, {'+'.join(backends)}{', known' if KNOWN else ''}): " | ||
| 548 | f"{counts['pass']} pass, {counts['mismatch']} mismatch, {skips} skipped") | ||
| 549 | for reason, n in sorted(counts["skip"].items(), key=lambda kv: -kv[1]): | ||
| 550 | print(f" skip x{n}: {reason}") | ||
| 551 | |||
| 552 | def check_fn(lines): | ||
| 553 | return check(lines, backends, (lambda l: oracle.run([hw_kernel(l)])[0]) if oracle else None) | ||
| 554 | for i, problem, lines in failures[: None if a.all_failures else 1]: | ||
| 555 | small = shrink(lines, check_fn) | ||
| 556 | print(f"MISMATCH program {i}: {check_fn(small) or problem}") | ||
| 557 | print("\n".join("\t" + line for line in small)) | ||
| 558 | except (RefError, RuntimeError) as e: | ||
| 559 | print(f"harness error: {e}") | ||
| 560 | return 2 | ||
| 561 | finally: | ||
| 562 | if oracle: | ||
| 563 | oracle.close() | ||
| 564 | return 1 if failures else 0 | ||
| 565 | |||
| 566 | |||
| 567 | if __name__ == "__main__": | ||
| 568 | try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode | ||
| 569 | sys.stdout.reconfigure(errors="replace") | ||
| 570 | except (AttributeError, ValueError, OSError): | ||
| 571 | pass | ||
| 572 | sys.exit(main()) | ||