diff options
| author | iurysf <98192149+iurysf@users.noreply.github.com> | 2026-11-22 22:20:42 -0300 |
|---|---|---|
| committer | iurysf <98192149+iurysf@users.noreply.github.com> | 2026-11-22 22:57:33 -0300 |
| commit | 50b889e3c19360e96eaa1c14a0e216f4fb8c0cfa (patch) | |
| tree | 333257820e377660a000ad271a7b22182a8e8976 /tools/f64_diff.py | |
| parent | 03b09a086592a197db64d91655c6e65c30764d96 (diff) | |
FUZZ-55: Harden binary64 differential probes
AI-assisted (OpenBot team).
Explicitly count FTZ and implementation-defined GPU precision skips, execute known divergence probes, correct compare modeling, and reuse prepared GPU context when shrinking. CPU campaigns and RTX 4070 Vulkan shaderFloat64 campaigns finished with zero unexpected mismatches.
Co-authored-by: OpenBot <335604065+openbotgit[bot]@users.noreply.github.com>
Diffstat (limited to 'tools/f64_diff.py')
| -rw-r--r-- | tools/f64_diff.py | 746 |
1 files changed, 746 insertions, 0 deletions
diff --git a/tools/f64_diff.py b/tools/f64_diff.py new file mode 100644 index 000000000..8744a5c37 --- /dev/null +++ b/tools/f64_diff.py | |||
| @@ -0,0 +1,746 @@ | |||
| 1 | """Differential checks for the 47 binary64 VALU instruction forms translated by main. | ||
| 2 | |||
| 3 | The reference below decodes IEEE-754 words itself. Finite arithmetic is performed with | ||
| 4 | Fractions and rounded to binary64; it shares no implementation with the translator, its | ||
| 5 | CPU interpreter, cpu_ref, or another fuzzer. The second path translates generated listings | ||
| 6 | and executes their SPIR-V with the semantic one-lane interpreter. Only synthetic programs | ||
| 7 | are created; no game files are read. | ||
| 8 | |||
| 9 | The GPU path is deliberately optional. It translates the same fragment shader, runs it | ||
| 10 | through vk_harness, and reads back RGBA32F words. The hardware oracle is AMD-only and | ||
| 11 | returns 77 when the host has no configured AMD hw_oracle. ``--known`` runs known | ||
| 12 | divergence probes; a reproduced mismatch intentionally returns 1. | ||
| 13 | """ | ||
| 14 | import argparse | ||
| 15 | import gc | ||
| 16 | import math | ||
| 17 | import os | ||
| 18 | import random | ||
| 19 | import re | ||
| 20 | import shutil | ||
| 21 | import struct | ||
| 22 | import subprocess | ||
| 23 | import sys | ||
| 24 | import tempfile | ||
| 25 | import warnings | ||
| 26 | from collections import Counter | ||
| 27 | from fractions import Fraction | ||
| 28 | |||
| 29 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 30 | ROOT = os.path.dirname(HERE) | ||
| 31 | SEM = os.path.join(ROOT, "tests", "semantic") | ||
| 32 | for path in (HERE, SEM, os.path.join(ROOT, "tests")): | ||
| 33 | if path not in sys.path: | ||
| 34 | sys.path.insert(0, path) | ||
| 35 | sys.dont_write_bytecode = True | ||
| 36 | |||
| 37 | import rdna2spirv # noqa: E402 | ||
| 38 | from spirv_mini_interp import UnsupportedConstruct, run_fragment # noqa: E402 | ||
| 39 | import spirv_interp # noqa: E402 | ||
| 40 | |||
| 41 | M32 = 0xFFFFFFFF | ||
| 42 | M64 = 0xFFFFFFFFFFFFFFFF | ||
| 43 | EXP = 0x7FF0000000000000 | ||
| 44 | FRAC = 0x000FFFFFFFFFFFFF | ||
| 45 | QNAN = 0x7FF8000000000000 | ||
| 46 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 47 | CONDS = ("f", "lt", "eq", "le", "gt", "lg", "ge", "o", "u", "nge", "nlg", "ngt", "nle", "neq", "nlt", "tru") | ||
| 48 | ROUND = ("v_trunc_f64", "v_ceil_f64", "v_rndne_f64", "v_floor_f64") | ||
| 49 | BASE = (*ROUND, "v_add_f64", "v_cvt_f32_f64", "v_rcp_f64", "v_rsq_f64", "v_sqrt_f64", | ||
| 50 | "v_div_fixup_f64", "v_div_fmas_f64", "v_frexp_mant_f64", "v_frexp_exp_i32_f64", | ||
| 51 | *(f"v_cmp_{c}_f64" for c in CONDS), *(f"v_cmpx_{c}_f64" for c in CONDS), | ||
| 52 | "v_cmp_class_f64", "v_cmpx_class_f64") | ||
| 53 | OP_FORMS = {op: "round" if op in ROUND else "unary" if op in ("v_cvt_f32_f64", "v_rcp_f64", "v_rsq_f64", "v_sqrt_f64", "v_frexp_mant_f64", "v_frexp_exp_i32_f64") else "binary" if op == "v_add_f64" else "ternary" if op in ("v_div_fixup_f64", "v_div_fmas_f64") else "compare" if "cmp_" in op and "class" not in op else "class" for op in BASE} | ||
| 54 | EXPORT = "exp mrt0 v8, v9, v10, v11 done vm" | ||
| 55 | KNOWN_DIVERGENCES = { | ||
| 56 | "f64-omod": "SHADER-721: f64 output modifiers; owned by @fiestorra.", | ||
| 57 | "double-neg-abs": "TEST-912 (#4172): spirv_mini_interp rounds binary64 OpFNegate/FAbs through binary32, changing values as well as NaN payloads.", | ||
| 58 | "fclamp-nan-zero": "FClamp NaN and signed-zero results are driver-dependent after f64 clamp/omod.", | ||
| 59 | "div-fixup-nan-s0": "RDNA2 ISA maps NaN(S0) to signed infinity; current translator preserves the NaN payload.", | ||
| 60 | } | ||
| 61 | |||
| 62 | |||
| 63 | class HarnessError(Exception): | ||
| 64 | pass | ||
| 65 | |||
| 66 | |||
| 67 | class SkipCase(Exception): | ||
| 68 | pass | ||
| 69 | |||
| 70 | |||
| 71 | class GPUUnavailable(Exception): | ||
| 72 | pass | ||
| 73 | |||
| 74 | |||
| 75 | def words_to_bits(lo, hi): | ||
| 76 | return ((hi & M32) << 32) | (lo & M32) | ||
| 77 | |||
| 78 | |||
| 79 | def bits_to_words(bits): | ||
| 80 | return bits & M32, (bits >> 32) & M32 | ||
| 81 | |||
| 82 | |||
| 83 | def is_nan(x): | ||
| 84 | return (x & EXP) == EXP and (x & FRAC) != 0 | ||
| 85 | |||
| 86 | |||
| 87 | def is_inf(x): | ||
| 88 | return x & 0x7FFFFFFFFFFFFFFF == EXP | ||
| 89 | |||
| 90 | |||
| 91 | def is_zero(x): | ||
| 92 | return x & 0x7FFFFFFFFFFFFFFF == 0 | ||
| 93 | |||
| 94 | |||
| 95 | def is_subnormal(x): | ||
| 96 | return (x & EXP) == 0 and (x & FRAC) != 0 | ||
| 97 | |||
| 98 | |||
| 99 | def is_f32_subnormal(x): | ||
| 100 | return (x & 0x7F800000) == 0 and (x & 0x7FFFFF) != 0 | ||
| 101 | |||
| 102 | |||
| 103 | def to_float(bits): | ||
| 104 | return struct.unpack("<d", struct.pack("<Q", bits & M64))[0] | ||
| 105 | |||
| 106 | |||
| 107 | def from_float(value): | ||
| 108 | try: | ||
| 109 | return struct.unpack("<Q", struct.pack("<d", value))[0] | ||
| 110 | except OverflowError: | ||
| 111 | return 0xFFF0000000000000 if value < 0 else EXP | ||
| 112 | |||
| 113 | |||
| 114 | def to_fraction(bits): | ||
| 115 | e, m = (bits >> 52) & 0x7FF, bits & FRAC | ||
| 116 | if e == 0: | ||
| 117 | n, p = m, -1074 | ||
| 118 | else: | ||
| 119 | n, p = m | (1 << 52), e - 1075 | ||
| 120 | f = Fraction(n) * (Fraction(2) ** p) | ||
| 121 | return -f if bits >> 63 else f | ||
| 122 | |||
| 123 | |||
| 124 | def round_fraction(value, mode=0, negative_zero=False): | ||
| 125 | """Round a finite rational to binary64: nearest-even, +inf, -inf, or toward zero.""" | ||
| 126 | if not value: | ||
| 127 | return 0x8000000000000000 if negative_zero else 0 | ||
| 128 | sign = 0x8000000000000000 if value < 0 else 0 | ||
| 129 | a = abs(value) | ||
| 130 | e = a.numerator.bit_length() - a.denominator.bit_length() | ||
| 131 | while Fraction(2) ** e > a: | ||
| 132 | e -= 1 | ||
| 133 | while Fraction(2) ** (e + 1) <= a: | ||
| 134 | e += 1 | ||
| 135 | def overflow(): | ||
| 136 | negative = bool(sign) | ||
| 137 | if mode == 3 or (mode == 1 and negative) or (mode == 2 and not negative): | ||
| 138 | return sign | 0x7FEFFFFFFFFFFFFF | ||
| 139 | return sign | EXP | ||
| 140 | |||
| 141 | if e > 1023: return overflow() | ||
| 142 | if e < -1022: | ||
| 143 | scaled = a * Fraction(2 ** 1074) | ||
| 144 | q, r = divmod(scaled.numerator, scaled.denominator) | ||
| 145 | increment = (2 * r > scaled.denominator or (2 * r == scaled.denominator and q & 1)) if mode == 0 else bool(r) and ((mode == 1 and not sign) or (mode == 2 and bool(sign))) | ||
| 146 | if increment: | ||
| 147 | q += 1 | ||
| 148 | return sign | q | ||
| 149 | scaled = a / Fraction(2) ** (e - 52) | ||
| 150 | q, r = divmod(scaled.numerator, scaled.denominator) | ||
| 151 | increment = (2 * r > scaled.denominator or (2 * r == scaled.denominator and q & 1)) if mode == 0 else bool(r) and ((mode == 1 and not sign) or (mode == 2 and bool(sign))) | ||
| 152 | if increment: | ||
| 153 | q += 1 | ||
| 154 | if q == 1 << 53: | ||
| 155 | q >>= 1 | ||
| 156 | e += 1 | ||
| 157 | if e > 1023: | ||
| 158 | return overflow() | ||
| 159 | return sign | ((e + 1023) << 52) | (q & FRAC) | ||
| 160 | |||
| 161 | |||
| 162 | def add_bits(a, b, mode=0): | ||
| 163 | """IEEE sum; MODE 3 (toward zero) steps back if nearest-even rounded away from zero.""" | ||
| 164 | if is_nan(a) or is_nan(b): | ||
| 165 | return QNAN | ||
| 166 | if is_inf(a) or is_inf(b): | ||
| 167 | af, bf = to_float(a), to_float(b) | ||
| 168 | return from_float(af + bf) | ||
| 169 | negzero = (is_zero(a) and is_zero(b) and bool((a & b) >> 63)) or mode == 2 | ||
| 170 | exact = to_fraction(a) + to_fraction(b) | ||
| 171 | return round_fraction(exact, mode, negzero) | ||
| 172 | |||
| 173 | |||
| 174 | def class_index(bits): | ||
| 175 | sign, e, m = bits >> 63, (bits >> 52) & 0x7FF, bits & FRAC | ||
| 176 | if e == 0x7FF: | ||
| 177 | if m: | ||
| 178 | return 0 if not (m & (1 << 51)) else 1 | ||
| 179 | return 2 if sign else 9 | ||
| 180 | if e == 0: | ||
| 181 | if not m: | ||
| 182 | return 5 if sign else 6 | ||
| 183 | return 4 if sign else 7 | ||
| 184 | return 3 if sign else 8 | ||
| 185 | |||
| 186 | |||
| 187 | def compare(cond, a, b): | ||
| 188 | unordered = is_nan(a) or is_nan(b) | ||
| 189 | if cond == "f": return 0 | ||
| 190 | if cond == "tru": return 1 | ||
| 191 | if cond == "o": return int(not unordered) | ||
| 192 | if cond == "u": return int(unordered) | ||
| 193 | if unordered: | ||
| 194 | return int({"nge": 0, "nlg": 1, "ngt": 2, "nle": 3, "neq": 4, "nlt": 5}.get(cond, -1) >= 0) | ||
| 195 | x, y = to_float(a), to_float(b) | ||
| 196 | result = {"lt": x < y, "eq": x == y, "le": x <= y, "gt": x > y, "lg": x != y, | ||
| 197 | "ge": x >= y, "nge": x < y, "nlg": x == y, "ngt": x <= y, | ||
| 198 | "nle": x > y, "neq": x != y, "nlt": x >= y} | ||
| 199 | return int(result[cond]) | ||
| 200 | |||
| 201 | |||
| 202 | def fixup(s0, s1, s2): | ||
| 203 | sign = (s1 ^ s2) & 0x8000000000000000 | ||
| 204 | if is_nan(s2): return s2 | (1 << 51) | ||
| 205 | if is_nan(s1): return s1 | (1 << 51) | ||
| 206 | z1, z2, i1, i2 = is_zero(s1), is_zero(s2), is_inf(s1), is_inf(s2) | ||
| 207 | if (z1 and z2) or (i1 and i2): return 0xFFF8000000000000 | ||
| 208 | e1, e2 = (s1 >> 52) & 0x7FF, (s2 >> 52) & 0x7FF | ||
| 209 | ediff = e2 - e1 | ||
| 210 | if i1 or z2 or ediff < -1074: return sign | ||
| 211 | if z1 or i2 or ediff >= 1024 or is_nan(s0): return sign | EXP | ||
| 212 | return (s0 & 0x7FFFFFFFFFFFFFFF) | sign | ||
| 213 | |||
| 214 | |||
| 215 | def frexp(bits): | ||
| 216 | sign = bits & 0x8000000000000000 | ||
| 217 | e, m = (bits >> 52) & 0x7FF, bits & FRAC | ||
| 218 | if e == 0x7FF or (e == 0 and m == 0): return bits, 0 | ||
| 219 | if e: | ||
| 220 | return sign | (0x3FE << 52) | m, e - 1022 | ||
| 221 | top = m.bit_length() - 1 | ||
| 222 | exp = top - 1073 | ||
| 223 | mantissa = m << (52 - top) | ||
| 224 | return sign | (0x3FE << 52) | (mantissa & FRAC), exp | ||
| 225 | |||
| 226 | |||
| 227 | def rounded_unary(op, bits): | ||
| 228 | if is_nan(bits) or is_inf(bits) or is_zero(bits): return bits | ||
| 229 | x = to_float(bits) | ||
| 230 | value = {"v_trunc_f64": math.trunc, "v_ceil_f64": math.ceil, | ||
| 231 | "v_rndne_f64": round, "v_floor_f64": math.floor}[op](x) | ||
| 232 | if value == 0 and bits >> 63: return 0x8000000000000000 | ||
| 233 | return from_float(float(value)) | ||
| 234 | |||
| 235 | |||
| 236 | def read_source(tok, vgpr, sgpr): | ||
| 237 | tok = tok.strip() | ||
| 238 | neg = tok.startswith("neg(") or tok.startswith("-|") or (tok.startswith("-") and tok[1:].startswith(("v[", "s[", "v", "s", "|"))) | ||
| 239 | absmod = "|" in tok | ||
| 240 | tok = tok.replace("|", "").replace("neg(", "").replace(")", "").strip() | ||
| 241 | if neg and tok.startswith("-"): | ||
| 242 | tok = tok[1:].strip() | ||
| 243 | m = re.fullmatch(r"([sv])\[(\d+):(\d+)\]", tok) | ||
| 244 | if m: | ||
| 245 | regs = vgpr if m.group(1) == "v" else sgpr | ||
| 246 | lo, hi = int(m.group(2)), int(m.group(3)) | ||
| 247 | value = words_to_bits(regs.get(lo, 0), regs.get(hi, 0)) | ||
| 248 | elif tok.startswith(("v", "s")) and tok[1:].isdigit(): | ||
| 249 | raise HarnessError("binary64 source must be an even register pair") | ||
| 250 | elif tok.startswith("0x"): | ||
| 251 | # A printed 32-bit ISA literal occupies bits 63:32 in forms marked by shader_ir; | ||
| 252 | # a full 64-bit hexadecimal operand is already the complete IEEE word. | ||
| 253 | value = int(tok, 16) | ||
| 254 | if value <= M32: value <<= 32 | ||
| 255 | value &= M64 | ||
| 256 | elif re.fullmatch(r"[-+]?\d+", tok): | ||
| 257 | n = int(tok) | ||
| 258 | value = n & M64 | ||
| 259 | else: | ||
| 260 | try: value = from_float(float(tok)) | ||
| 261 | except (ValueError, OverflowError) as exc: raise HarnessError(f"bad source {tok!r}") from exc | ||
| 262 | if absmod: value &= 0x7FFFFFFFFFFFFFFF | ||
| 263 | if neg: value ^= 0x8000000000000000 | ||
| 264 | return value | ||
| 265 | |||
| 266 | |||
| 267 | def parse_source_args(line): | ||
| 268 | head, *args = line.split(",") | ||
| 269 | bits = head.split() | ||
| 270 | return bits[0], bits[1].rstrip(","), [x.strip() for x in args] | ||
| 271 | |||
| 272 | |||
| 273 | def ref_program(lines, include_known=False): | ||
| 274 | vgpr, sgpr, mode, vcc, active = {}, {}, 0, 0, M32 | ||
| 275 | for line in lines: | ||
| 276 | s = line.strip() | ||
| 277 | if not s or s.startswith((";", "exp ", "s_endpgm")): continue | ||
| 278 | if s.startswith("v_mov_b32") or s.startswith("s_mov_b32"): | ||
| 279 | op, dst, srcs = parse_source_args(s) | ||
| 280 | src = srcs[0] | ||
| 281 | if dst == "exec_lo": active = sgpr.get(int(src[1:]), 0) & M32 | ||
| 282 | elif src == "exec_lo": sgpr[int(dst[1:])] = active | ||
| 283 | else: | ||
| 284 | if re.fullmatch(r"[sv]\d+", src): | ||
| 285 | regs = vgpr if src.startswith("v") else sgpr | ||
| 286 | word = regs.get(int(src[1:]), 0) | ||
| 287 | else: word = int(src, 0) | ||
| 288 | (vgpr if dst.startswith("v") else sgpr)[int(dst[1:])] = word & M32 | ||
| 289 | continue | ||
| 290 | if s.startswith("s_round_mode "): | ||
| 291 | mode = (int(s.split(None, 1)[1], 0) >> 2) & 3 | ||
| 292 | continue | ||
| 293 | if "s_setreg_imm32_b32" in s: | ||
| 294 | mode = (int(s.rsplit(",", 1)[1], 0) >> 2) & 3 | ||
| 295 | continue | ||
| 296 | if s.startswith("v_cmp_eq_i32_e32 vcc_lo,"): | ||
| 297 | vcc = int(s.rsplit(",", 2)[1].strip(), 0) == int(s.rsplit(",", 1)[1].strip(), 0) | ||
| 298 | continue | ||
| 299 | op, dst, a = parse_source_args(s) | ||
| 300 | if op in ROUND: | ||
| 301 | out = rounded_unary(op, read_source(a[0], vgpr, sgpr)) | ||
| 302 | lo, hi = bits_to_words(out); vgpr[int(dst[2:-1].split(":")[0])] = lo | ||
| 303 | vgpr[int(dst[2:-1].split(":")[0]) + 1] = hi | ||
| 304 | elif op == "v_add_f64": | ||
| 305 | modifiers = re.findall(r"(?<!\S)(mul:2|mul:4|div:2|clamp)(?=\s|$)", a[1]) | ||
| 306 | right = re.sub(r"(?<!\S)(?:mul:2|mul:4|div:2|clamp)(?=\s|$)", "", a[1]).strip() | ||
| 307 | out = add_bits(read_source(a[0], vgpr, sgpr), read_source(right, vgpr, sgpr), mode) | ||
| 308 | for modifier in modifiers: | ||
| 309 | scale = {"mul:2": 2.0, "mul:4": 4.0, "div:2": 0.5}.get(modifier) | ||
| 310 | if scale is not None: | ||
| 311 | out = QNAN if is_nan(out) else from_float(to_float(out) * scale) | ||
| 312 | if "clamp" in modifiers and not is_nan(out): | ||
| 313 | out = from_float(min(1.0, max(0.0, to_float(out)))) | ||
| 314 | d = int(dst[2:-1].split(":")[0]); vgpr[d], vgpr[d + 1] = bits_to_words(out) | ||
| 315 | elif op in ("v_cvt_f32_f64", "v_rcp_f64", "v_rsq_f64", "v_sqrt_f64"): | ||
| 316 | x = read_source(a[0], vgpr, sgpr) | ||
| 317 | if op == "v_cvt_f32_f64": | ||
| 318 | try: out = struct.unpack("<I", struct.pack("<f", to_float(x)))[0] | ||
| 319 | except OverflowError: out = 0xFF800000 if x >> 63 else 0x7F800000 | ||
| 320 | elif op == "v_rcp_f64": out = from_float(1.0 / to_float(x)) if not is_zero(x) else ((x ^ 0x3FF0000000000000) & 0x8000000000000000) | EXP | ||
| 321 | elif op == "v_sqrt_f64": | ||
| 322 | if is_zero(x): out = x | ||
| 323 | elif x >> 63: out = QNAN | ||
| 324 | else: out = from_float(math.sqrt(to_float(x))) | ||
| 325 | elif is_zero(x): out = (x & 0x8000000000000000) | EXP | ||
| 326 | else: out = QNAN if x >> 63 else from_float(1.0 / math.sqrt(to_float(x))) | ||
| 327 | if op in ("v_rcp_f64", "v_rsq_f64", "v_sqrt_f64") and (is_subnormal(x) or is_subnormal(out)): | ||
| 328 | raise SkipCase(f"{op} subnormal operand/result is driver-dependent (FTZ)") | ||
| 329 | if op == "v_cvt_f32_f64" and is_f32_subnormal(out): | ||
| 330 | raise SkipCase("v_cvt_f32_f64 subnormal f32 result is driver-dependent (FTZ)") | ||
| 331 | if op == "v_cvt_f32_f64": vgpr[int(dst[1:])] = out | ||
| 332 | else: | ||
| 333 | d = int(dst[2:-1].split(":")[0]); vgpr[d], vgpr[d + 1] = bits_to_words(out) | ||
| 334 | elif op == "v_div_fixup_f64": | ||
| 335 | args = [read_source(t, vgpr, sgpr) for t in a[:3]] | ||
| 336 | s0, s1, s2 = args | ||
| 337 | ediff = ((s2 >> 52) & 0x7FF) - ((s1 >> 52) & 0x7FF) | ||
| 338 | normal_division = (not is_nan(s1) and not is_inf(s1) and not is_zero(s1) | ||
| 339 | and not is_nan(s2) and not is_inf(s2) and not is_zero(s2) | ||
| 340 | and -1074 <= ediff < 1024) | ||
| 341 | if not include_known and is_nan(s0) and normal_division: | ||
| 342 | raise SkipCase(f"KNOWN_DIVERGENCE div-fixup-nan-s0: {KNOWN_DIVERGENCES['div-fixup-nan-s0']}") | ||
| 343 | d = int(dst[2:-1].split(":")[0]); vgpr[d], vgpr[d + 1] = bits_to_words(fixup(*args)) | ||
| 344 | elif op == "v_frexp_mant_f64": | ||
| 345 | d = int(dst[2:-1].split(":")[0]); vgpr[d], vgpr[d + 1] = bits_to_words(frexp(read_source(a[0], vgpr, sgpr))[0]) | ||
| 346 | elif op == "v_frexp_exp_i32_f64": | ||
| 347 | vgpr[int(dst[1:])] = frexp(read_source(a[0], vgpr, sgpr))[1] & M32 | ||
| 348 | elif "class" in op: | ||
| 349 | operands = [dst] + a if op.startswith("v_cmpx") else a | ||
| 350 | src = read_source(operands[-2], vgpr, sgpr); mask = int(operands[-1], 0) & 0x3FF | ||
| 351 | hit = int(bool(mask & (1 << class_index(src)))) | ||
| 352 | sgpr[20] = hit | ||
| 353 | if op.startswith("v_cmpx"): active &= M32 if hit else 0 | ||
| 354 | elif op.startswith("v_cmp_") or op.startswith("v_cmpx_"): | ||
| 355 | cond = op.split("_")[2] | ||
| 356 | operands = [dst] + a if op.startswith("v_cmpx") else a | ||
| 357 | hit = compare(cond, read_source(operands[-2], vgpr, sgpr), read_source(operands[-1], vgpr, sgpr)) | ||
| 358 | sgpr[20] = hit | ||
| 359 | if op.startswith("v_cmpx"): active &= M32 if hit else 0 | ||
| 360 | elif op == "v_cndmask_b32_e64": | ||
| 361 | _, dst, a = parse_source_args(s) | ||
| 362 | vgpr[int(dst[1:])] = int(a[1], 0) & M32 if sgpr.get(20, 0) else int(a[0], 0) & M32 | ||
| 363 | elif op == "v_div_fmas_f64": | ||
| 364 | x, y, z = (read_source(t, vgpr, sgpr) for t in a) | ||
| 365 | if any(is_nan(t) or is_inf(t) for t in (x, y, z)): | ||
| 366 | raise SkipCase("non-finite v_div_fmas_f64 operands are not judged") | ||
| 367 | exact = to_fraction(x) * to_fraction(y) + to_fraction(z) | ||
| 368 | if vcc: exact *= 1 << 64 | ||
| 369 | d = int(dst[2:-1].split(":")[0]); vgpr[d], vgpr[d + 1] = bits_to_words(round_fraction(exact)) | ||
| 370 | else: | ||
| 371 | raise HarnessError(f"reference does not implement {op}") | ||
| 372 | return [vgpr.get(r, 0) & M32 for r in range(8, 12)] | ||
| 373 | |||
| 374 | |||
| 375 | def write_listing(path, lines, name): | ||
| 376 | with open(path, "w", encoding="utf-8", newline="\n") as f: | ||
| 377 | f.write(f"; {name} code 0x0..0x1000\n") | ||
| 378 | for line in lines: f.write("\t" + line + "\n") | ||
| 379 | f.write("\t" + EXPORT + "\n\ts_endpgm\n") | ||
| 380 | |||
| 381 | |||
| 382 | def translate_assembly(lines, name, tmpdir): | ||
| 383 | dis = os.path.join(tmpdir, "disasm"); os.makedirs(dis, exist_ok=True) | ||
| 384 | src = os.path.join(dis, name + ".s") | ||
| 385 | write_listing(src, lines, name) | ||
| 386 | with open(os.path.join(tmpdir, name + ".dxbc"), "wb") as f: f.write(STUB_DXBC) | ||
| 387 | with warnings.catch_warnings(): | ||
| 388 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 389 | return rdna2spirv.translate(src) | ||
| 390 | |||
| 391 | |||
| 392 | def translate(lines, name, tmpdir): | ||
| 393 | asm = translate_assembly(lines, name, tmpdir) | ||
| 394 | gc.collect() | ||
| 395 | if "OpCapability Float64" in asm: | ||
| 396 | if "OpFDiv %double" in asm: | ||
| 397 | raise SkipCase("the available SPIR-V CPU interpreters do not model binary64 OpFDiv") | ||
| 398 | if "OpFConvert" in asm: | ||
| 399 | raise SkipCase("the available SPIR-V CPU interpreters do not model binary64 OpFConvert") | ||
| 400 | try: return [int(x) & M32 for x in spirv_interp.run(asm).vgpr[8:12]] | ||
| 401 | except (NotImplementedError, ZeroDivisionError, OverflowError, ValueError) as exc: | ||
| 402 | raise SkipCase(f"binary64 SPIR-V interpreter limitation: {type(exc).__name__}: {exc}") from exc | ||
| 403 | try: out = run_fragment(asm) | ||
| 404 | except UnsupportedConstruct as exc: raise SkipCase(str(exc)) from exc | ||
| 405 | if list(out) != ["%out_mrt0"]: raise HarnessError(f"unexpected outputs: {list(out)}") | ||
| 406 | return [int(x) & M32 for x in out["%out_mrt0"]] | ||
| 407 | |||
| 408 | |||
| 409 | def sdk_tool(name): | ||
| 410 | exe = name + (".exe" if os.name == "nt" else "") | ||
| 411 | found = shutil.which(exe) or shutil.which(name) | ||
| 412 | if found: return found | ||
| 413 | sdk = os.environ.get("VULKAN_SDK") | ||
| 414 | candidate = os.path.join(sdk, "Bin", exe) if sdk else "" | ||
| 415 | return candidate if candidate and os.path.isfile(candidate) else None | ||
| 416 | |||
| 417 | |||
| 418 | def prepare_gpu(exe, tmpdir): | ||
| 419 | if not os.path.isfile(exe): raise GPUUnavailable(f"vk_harness not found: {exe}") | ||
| 420 | glslc, spirv_as = sdk_tool("glslc"), sdk_tool("spirv-as") | ||
| 421 | if not glslc or not spirv_as: raise GPUUnavailable("Vulkan SDK glslc and spirv-as are required for --oracle gpu") | ||
| 422 | vertex = os.path.join(ROOT, "runtime", "test", "glsl", "vs_fullscreen.vert") | ||
| 423 | if not os.path.isfile(vertex): raise HarnessError(f"full-screen vertex shader is missing: {vertex}") | ||
| 424 | vs_spv = os.path.join(tmpdir, "f64_diff_vs.spv") | ||
| 425 | try: | ||
| 426 | r = subprocess.run([glslc, vertex, "-o", vs_spv], capture_output=True, text=True, timeout=30) | ||
| 427 | except subprocess.TimeoutExpired: raise HarnessError("glslc timed out while compiling the full-screen vertex shader") from None | ||
| 428 | if r.returncode: raise HarnessError(f"glslc failed: {(r.stdout + r.stderr).strip()}") | ||
| 429 | return {"exe": exe, "glslc": glslc, "spirv_as": spirv_as, "vs_spv": vs_spv} | ||
| 430 | |||
| 431 | |||
| 432 | def run_gpu(lines, name, tmpdir, gpu): | ||
| 433 | asm = translate_assembly(lines, name, tmpdir) | ||
| 434 | asm_path = os.path.join(tmpdir, name + ".spvasm") | ||
| 435 | fs_spv = os.path.join(tmpdir, name + ".spv") | ||
| 436 | raw = os.path.join(tmpdir, name + ".raw") | ||
| 437 | with open(asm_path, "w", encoding="utf-8", newline="\n") as f: f.write(asm) | ||
| 438 | try: | ||
| 439 | r = subprocess.run([gpu["spirv_as"], "--target-env", "vulkan1.2", asm_path, "-o", fs_spv], | ||
| 440 | capture_output=True, text=True, timeout=30) | ||
| 441 | except subprocess.TimeoutExpired: raise HarnessError("spirv-as timed out while assembling the translated shader") from None | ||
| 442 | if r.returncode: raise HarnessError(f"spirv-as failed: {(r.stdout + r.stderr).strip()}") | ||
| 443 | try: | ||
| 444 | r = subprocess.run([gpu["exe"], gpu["vs_spv"], fs_spv, raw, "1", "1"], | ||
| 445 | capture_output=True, text=True, timeout=60) | ||
| 446 | except subprocess.TimeoutExpired: raise HarnessError("vk_harness timed out after 60 s") from None | ||
| 447 | detail = " ".join((r.stdout + r.stderr).split()) | ||
| 448 | if r.returncode == 77: raise GPUUnavailable(detail or "vk_harness reports that the Vulkan device cannot run this shader") | ||
| 449 | if r.returncode: raise HarnessError(f"vk_harness exited {r.returncode}: {detail}") | ||
| 450 | if not os.path.isfile(raw) or os.path.getsize(raw) != 16: | ||
| 451 | raise HarnessError("vk_harness did not write exactly four RGBA32F dwords") | ||
| 452 | with open(raw, "rb") as f: return list(struct.unpack("<4I", f.read())) | ||
| 453 | |||
| 454 | |||
| 455 | def rand_bits(rng): | ||
| 456 | # Mostly finite normals, with signed zeros, infinities and NaNs for predicate/class coverage. | ||
| 457 | if rng.random() < .2: | ||
| 458 | return rng.choice((0, 0x8000000000000000, EXP, 0xFFF0000000000000, QNAN, 0xFFF0000000000001, 1, 0x8000000000000001)) | ||
| 459 | return rng.getrandbits(64) & 0xFFEFFFFFFFFFFFFF | (rng.getrandbits(1) << 63) | (rng.randrange(1, 2047) << 52) | ||
| 460 | |||
| 461 | |||
| 462 | def gen_source(rng, idx, allow_literal=True, bus=None): | ||
| 463 | choices = ("v", "s", "fimm", "inline", "literal") if allow_literal else ("v", "s", "fimm", "inline") | ||
| 464 | kind = rng.choice(choices) | ||
| 465 | if bus is not None: | ||
| 466 | if kind == "s" and len(bus[0]) >= 2: kind = "v" | ||
| 467 | if kind == "literal" and bus[1]: kind = "v" | ||
| 468 | if kind == "s": bus[0].add(idx) | ||
| 469 | if kind == "literal": bus[1] = True | ||
| 470 | if kind == "v": return f"v[{8 + 2*idx}:{9 + 2*idx}]" | ||
| 471 | if kind == "s": return f"s[{4 + 2*(idx % 2)}:{5 + 2*(idx % 2)}]" | ||
| 472 | if kind == "fimm": return rng.choice(("0.0", "-0.0", "1.0", "-1.0", "1.5", "2.0", "0.5", "3.25")) | ||
| 473 | if kind == "inline": return str(rng.choice((-16, -1, 0, 1, 2, 16, 64))) | ||
| 474 | if bus is not None and bus[2] == 64: | ||
| 475 | return f"0x{rng.getrandbits(64):016x}" | ||
| 476 | return f"0x{rng.getrandbits(32):08x}" | ||
| 477 | |||
| 478 | |||
| 479 | def maybe_word_modifier(rng, src): | ||
| 480 | """Only add modifiers to integer-word paths (round, compare and class), not %double math.""" | ||
| 481 | if not src.startswith(("v[", "s[")) or rng.random() >= 0.25: return src | ||
| 482 | choice = rng.randrange(3) | ||
| 483 | return f"|{src}|" if choice == 0 else f"-{src}" if choice == 1 else f"-|{src}|" | ||
| 484 | |||
| 485 | |||
| 486 | def make_case(rng, op, allow_literal=True, known_case=None): | ||
| 487 | setup_lines, body_lines = [], [] | ||
| 488 | vg, sg = {}, {} | ||
| 489 | for r in range(4, 8): | ||
| 490 | word = rng.getrandbits(32); sg[r] = word; setup_lines.append(f"s_mov_b32 s{r}, 0x{word:08x}") | ||
| 491 | # Replace both data lanes with selected edge cases for interpretable differential coverage. | ||
| 492 | for d in range(4): | ||
| 493 | bits = rand_bits(rng); lo, hi = bits_to_words(bits); r = 8 + 2*d | ||
| 494 | vg[r], vg[r + 1] = lo, hi | ||
| 495 | setup_lines += [f"v_mov_b32 v{r}, 0x{lo:08x}", f"v_mov_b32 v{r+1}, 0x{hi:08x}"] | ||
| 496 | if op == "v_add_f64": body_lines.append(f"s_round_mode {0 if known_case else rng.choice((0, 4, 8, 12))}") | ||
| 497 | high_literal = op in ROUND or op in ("v_add_f64", "v_cvt_f32_f64") or "cmp" in op or "class" in op | ||
| 498 | bus = [set(), False, 32 if high_literal else 64] | ||
| 499 | if op in ROUND: | ||
| 500 | src = maybe_word_modifier(rng, gen_source(rng, 0, allow_literal, bus)) | ||
| 501 | body_lines.append(f"{op} v[8:9], {src}") | ||
| 502 | elif op in ("v_cvt_f32_f64", "v_rcp_f64", "v_rsq_f64", "v_sqrt_f64", "v_frexp_mant_f64", "v_frexp_exp_i32_f64"): | ||
| 503 | src = gen_source(rng, 0, allow_literal, bus) | ||
| 504 | dst = "v8" if op in ("v_cvt_f32_f64", "v_frexp_exp_i32_f64") else "v[8:9]" | ||
| 505 | body_lines.append(f"{op} {dst}, {src}") | ||
| 506 | elif op == "v_add_f64": | ||
| 507 | left, right = gen_source(rng, 0, allow_literal, bus), gen_source(rng, 1, allow_literal, bus) | ||
| 508 | if known_case == "double-neg-abs": left = "-|v[8:9]|" | ||
| 509 | suffix = " mul:2" if known_case == "f64-omod" else " clamp" if known_case == "fclamp-nan-zero" else "" | ||
| 510 | if known_case == "fclamp-nan-zero": left, right = "0x7ff80001", "1.0" | ||
| 511 | body_lines.append(f"{op} v[8:9], {left}, {right}{suffix}") | ||
| 512 | elif op == "v_div_fixup_f64": | ||
| 513 | if known_case == "div-fixup-nan-s0": | ||
| 514 | setup_lines += ["v_mov_b32 v12, 0x00000000", "v_mov_b32 v13, 0x7ff80000"] | ||
| 515 | body_lines.append(f"{op} v[8:9], v[12:13], 1.0, 2.0") | ||
| 516 | else: | ||
| 517 | body_lines.append(f"{op} v[8:9], {gen_source(rng, 0, allow_literal, bus)}, {gen_source(rng, 1, allow_literal, bus)}, {gen_source(rng, 2, allow_literal, bus)}") | ||
| 518 | elif op == "v_div_fmas_f64": | ||
| 519 | # VCC is initialized true so the f64 scaled FMA path is exercised deterministically. | ||
| 520 | body_lines += ["v_cmp_eq_i32_e32 vcc_lo, 0, 0", f"{op} v[8:9], {gen_source(rng, 0, allow_literal, bus)}, {gen_source(rng, 1, allow_literal, bus)}, {gen_source(rng, 2, allow_literal, bus)}"] | ||
| 521 | elif "class" in op: | ||
| 522 | src, mask = maybe_word_modifier(rng, gen_source(rng, 2 if op.startswith("v_cmpx") else 0, allow_literal, bus)), f"0x{rng.randrange(1024):x}" | ||
| 523 | if op.startswith("v_cmpx"): | ||
| 524 | body_lines += ["s_mov_b32 s10, exec_lo", f"{op}_e64 {src}, {mask}", "s_mov_b32 s22, exec_lo", "s_mov_b32 exec_lo, s10", "v_mov_b32 v9, s22"] | ||
| 525 | body_lines += [f"v_cmp_class_f64_e64 s20, {src}, {mask}"] | ||
| 526 | else: body_lines.append(f"{op}_e64 s20, {src}, {mask}") | ||
| 527 | body_lines.append("v_cndmask_b32_e64 v8, 0, 1, s20") | ||
| 528 | else: | ||
| 529 | cond = op.split("_")[2] | ||
| 530 | source_index = 2 if op.startswith("v_cmpx") else 0 | ||
| 531 | s0 = maybe_word_modifier(rng, gen_source(rng, source_index, allow_literal, bus)) | ||
| 532 | s1 = maybe_word_modifier(rng, gen_source(rng, 3 if op.startswith("v_cmpx") else 1, allow_literal, bus)) | ||
| 533 | if op.startswith("v_cmpx"): | ||
| 534 | body_lines += ["s_mov_b32 s10, exec_lo", f"{op}_e64 {s0}, {s1}", "s_mov_b32 s22, exec_lo", "s_mov_b32 exec_lo, s10", "v_mov_b32 v9, s22"] | ||
| 535 | body_lines += [f"v_cmp_{cond}_f64_e64 s20, {s0}, {s1}", "v_cndmask_b32_e64 v8, 0, 1, s20"] | ||
| 536 | return setup_lines, body_lines, vg, sg | ||
| 537 | |||
| 538 | |||
| 539 | def output_kind(lines): | ||
| 540 | low, high = "int", "int" | ||
| 541 | for line in lines: | ||
| 542 | s = line.strip() | ||
| 543 | if s.startswith(("v_cndmask_b32_e64 v8,", "v_mov_b32 v8,")): low = "int" | ||
| 544 | elif s.startswith("v_mov_b32 v9,"): high = "int" | ||
| 545 | elif s.startswith("v_cvt_f32_f64 v8,"): low = "f32" | ||
| 546 | elif s.startswith("v_frexp_exp_i32_f64 v8,"): low = "int" | ||
| 547 | elif any(s.startswith(op + " v[8:9],") for op in (*ROUND, "v_add_f64", "v_rcp_f64", "v_rsq_f64", "v_sqrt_f64", "v_div_fixup_f64", "v_div_fmas_f64", "v_frexp_mant_f64")): | ||
| 548 | low, high = "f64", "f64" | ||
| 549 | return low, high | ||
| 550 | |||
| 551 | |||
| 552 | def equivalent(a, b, kind="int"): | ||
| 553 | if len(a) != len(b): return False | ||
| 554 | if kind == "f64": | ||
| 555 | x, y = words_to_bits(a[0], a[1]), words_to_bits(b[0], b[1]) | ||
| 556 | if x != y and not (is_nan(x) and is_nan(y)): return False | ||
| 557 | return a[2:] == b[2:] | ||
| 558 | if kind == "f32": | ||
| 559 | x, y = a[0], b[0] | ||
| 560 | if x != y and not (((x & 0x7F800000) == 0x7F800000 and x & 0x7FFFFF) and | ||
| 561 | ((y & 0x7F800000) == 0x7F800000 and y & 0x7FFFFF)): return False | ||
| 562 | return a[1:] == b[1:] | ||
| 563 | if isinstance(kind, tuple): | ||
| 564 | low, high = kind | ||
| 565 | if low == "f64": | ||
| 566 | x, y = words_to_bits(a[0], a[1]), words_to_bits(b[0], b[1]) | ||
| 567 | if x != y and not (is_nan(x) and is_nan(y)): return False | ||
| 568 | elif low == "f32": | ||
| 569 | x, y = a[0], b[0] | ||
| 570 | if x != y and not (((x & 0x7F800000) == 0x7F800000 and x & 0x7FFFFF) and | ||
| 571 | ((y & 0x7F800000) == 0x7F800000 and y & 0x7FFFFF)): return False | ||
| 572 | elif a[0] != b[0]: return False | ||
| 573 | if high == "f64" and low != "f64": | ||
| 574 | x, y = words_to_bits(a[0], a[1]), words_to_bits(b[0], b[1]) | ||
| 575 | if not (is_nan(x) and is_nan(y)) and a[1] != b[1]: return False | ||
| 576 | elif high != "f64" and a[1] != b[1]: return False | ||
| 577 | return a[2:] == b[2:] | ||
| 578 | return a == b | ||
| 579 | |||
| 580 | |||
| 581 | def run_one(lines, name, tmp, oracle="translator", gpu=None, include_known=False): | ||
| 582 | if not include_known: | ||
| 583 | for line in lines: | ||
| 584 | if " mul:" in line or " div:" in line: | ||
| 585 | return "skip", f"KNOWN_DIVERGENCE f64-omod: {KNOWN_DIVERGENCES['f64-omod']}", None, None | ||
| 586 | if " clamp" in line and "f64" in line: | ||
| 587 | return "skip", f"KNOWN_DIVERGENCE fclamp-nan-zero: {KNOWN_DIVERGENCES['fclamp-nan-zero']}", None, None | ||
| 588 | if line.split() and line.split()[0] in ("v_add_f64", "v_cvt_f32_f64", "v_rcp_f64", "v_rsq_f64", "v_sqrt_f64", "v_div_fmas_f64") and ("|" in line or "-v[" in line or "-s[" in line): | ||
| 589 | return "skip", f"KNOWN_DIVERGENCE double-neg-abs: {KNOWN_DIVERGENCES['double-neg-abs']}", None, None | ||
| 590 | try: expected = ref_program(lines, include_known) | ||
| 591 | except SkipCase as exc: return "skip", str(exc), None, None | ||
| 592 | except (ArithmeticError, IndexError, KeyError, ValueError) as exc: | ||
| 593 | return "skip", f"reference limitation: {type(exc).__name__}: {exc}", None, None | ||
| 594 | if oracle == "gpu" and any(line.lstrip().startswith(("v_rsq_f64 ", "v_sqrt_f64 ")) for line in lines): | ||
| 595 | return "skip", "GLSL.std.450 InverseSqrt/Sqrt double-precision result precision is implementation-defined", expected, None | ||
| 596 | try: actual = run_gpu(lines, name, tmp, gpu) if oracle == "gpu" else translate(lines, name, tmp) | ||
| 597 | except (rdna2spirv.Unsupported, UnsupportedConstruct, SkipCase) as exc: return "skip", f"{type(exc).__name__}: {exc}", expected, None | ||
| 598 | except (IndexError, KeyError, ValueError, OverflowError) as exc: return "skip", f"translator/interpreter limitation: {type(exc).__name__}: {exc}", expected, None | ||
| 599 | return ("match", "", expected, actual) if equivalent(expected, actual, output_kind(lines)) else ("mismatch", "word comparison", expected, actual) | ||
| 600 | |||
| 601 | |||
| 602 | def shrink(lines, expected, oracle="translator", gpu=None, gpu_ctx=None, tmpdir=None, include_known=False): | ||
| 603 | """Greedy instruction deletion minimizer, retaining only instructions needed for the mismatch.""" | ||
| 604 | current = list(lines) | ||
| 605 | def reduce(tmp, context): | ||
| 606 | i = 0 | ||
| 607 | while i < len(current): | ||
| 608 | trial = current[:i] + current[i + 1:] | ||
| 609 | try: | ||
| 610 | status, _, _, _ = run_one(trial, "ps_f64_shrink", tmp, oracle, context, include_known) | ||
| 611 | if status == "mismatch": | ||
| 612 | current[:] = trial | ||
| 613 | continue | ||
| 614 | except GPUUnavailable: | ||
| 615 | raise | ||
| 616 | except Exception: | ||
| 617 | pass | ||
| 618 | i += 1 | ||
| 619 | return current | ||
| 620 | if tmpdir is not None: | ||
| 621 | context = gpu_ctx if gpu_ctx is not None else prepare_gpu(gpu, tmpdir) if oracle == "gpu" else None | ||
| 622 | return reduce(tmpdir, context) | ||
| 623 | with tempfile.TemporaryDirectory(prefix="f64-shrink-") as tmp: | ||
| 624 | context = gpu_ctx if gpu_ctx is not None else prepare_gpu(gpu, tmp) if oracle == "gpu" else None | ||
| 625 | return reduce(tmp, context) | ||
| 626 | |||
| 627 | |||
| 628 | def run_batch(ops, programs, seed, max_ops=1, sweep=True, allow_literal=True, known=False, all_failures=False, | ||
| 629 | oracle="translator", gpu=None): | ||
| 630 | counts = Counter(); skips = Counter(); failures = [] | ||
| 631 | rng = random.Random(seed) | ||
| 632 | sequence = [(op, True, None) for op in ops] if sweep else [] | ||
| 633 | sequence += [(rng.choice(ops), False, None) for _ in range(programs)] | ||
| 634 | if known: | ||
| 635 | sequence += [("v_div_fixup_f64" if label == "div-fixup-nan-s0" else "v_add_f64", True, label) | ||
| 636 | for label in KNOWN_DIVERGENCES] | ||
| 637 | with tempfile.TemporaryDirectory(prefix="f64-diff-") as tmp: | ||
| 638 | gpu_ctx = prepare_gpu(gpu, tmp) if oracle == "gpu" else None | ||
| 639 | for idx, (op, is_sweep, known_case) in enumerate(sequence): | ||
| 640 | setup_lines, body_lines, _, _ = make_case(rng, op, allow_literal, known_case) | ||
| 641 | lines = setup_lines + body_lines | ||
| 642 | if not is_sweep and not known_case: | ||
| 643 | n_ops = rng.randint(1, max_ops) | ||
| 644 | for _ in range(n_ops - 1): | ||
| 645 | _, extra_body, _, _ = make_case(rng, rng.choice(ops), allow_literal) | ||
| 646 | lines.extend(extra_body) | ||
| 647 | status, reason, want, got = run_one(lines, f"ps_f64_{idx:05d}", tmp, oracle, gpu_ctx, | ||
| 648 | include_known=bool(known_case)) | ||
| 649 | if status == "skip": skips[reason] += 1 | ||
| 650 | else: counts[status] += 1 | ||
| 651 | if status == "mismatch": | ||
| 652 | reduced = shrink(lines, want, oracle, gpu, gpu_ctx, tmp, bool(known_case)) | ||
| 653 | failures.append((reduced, want, got, reason)) | ||
| 654 | if status == "mismatch" and not all_failures: break | ||
| 655 | return counts, skips, failures | ||
| 656 | |||
| 657 | |||
| 658 | def self_test(): | ||
| 659 | tests = [round_fraction(Fraction(1, 3) + Fraction(2, 3)) == 0x3FF0000000000000, | ||
| 660 | round_fraction(Fraction(1, 1 << 1075)) == 0, | ||
| 661 | add_bits(0x3FF0000000000000, 0x3CA0000000000000) == 0x3FF0000000000000, | ||
| 662 | class_index(0x7FF0000000000001) == 0, | ||
| 663 | class_index(0xFFF8000000000000) == 1, | ||
| 664 | compare("nlt", 0x7FF8000000000000, 0) == 1, | ||
| 665 | round_fraction(Fraction(1) + Fraction(1, 1 << 53), 1) == 0x3FF0000000000001, | ||
| 666 | round_fraction(-(Fraction(1) + Fraction(1, 1 << 53)), 2) == 0xBFF0000000000001, | ||
| 667 | round_fraction(Fraction(1 << 1024), 3) == 0x7FEFFFFFFFFFFFFF, | ||
| 668 | len(BASE) == 47] | ||
| 669 | for i, ok in enumerate(tests, 1): print(f"{'ok' if ok else 'FAIL'} reference invariant {i}") | ||
| 670 | # A planted output error must be reported and remain observable after shrinking. | ||
| 671 | lines = ["v_mov_b32 v12, 0x00000000", "v_mov_b32 v13, 0x3ff80000", | ||
| 672 | "v_trunc_f64 v[8:9], v[12:13]"] | ||
| 673 | original = translate | ||
| 674 | def planted_bug(listing, name, tmp): | ||
| 675 | out = original(listing, name, tmp) | ||
| 676 | if any(line.startswith("v_trunc_f64 ") for line in listing): out[0] ^= 1 | ||
| 677 | return out | ||
| 678 | try: | ||
| 679 | globals()["translate"] = planted_bug | ||
| 680 | with tempfile.TemporaryDirectory(prefix="f64-self-test-") as tmp: | ||
| 681 | status, _, expected, actual = run_one(lines, "ps_f64_self_test_negative", tmp) | ||
| 682 | reduced = shrink(lines, expected) | ||
| 683 | caught = (status == "mismatch" and not equivalent(expected, actual, output_kind(lines)) and len(reduced) == 1 | ||
| 684 | and reduced[0].startswith("v_trunc_f64 ")) | ||
| 685 | print(f"{'ok' if caught else 'FAIL'} planted translator mismatch is caught and shrinkable") | ||
| 686 | finally: | ||
| 687 | globals()["translate"] = original | ||
| 688 | return all(tests) and caught | ||
| 689 | |||
| 690 | |||
| 691 | def main(argv=None): | ||
| 692 | ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | ||
| 693 | ap.add_argument("--sweep", dest="sweep", action="store_true", default=True) | ||
| 694 | ap.add_argument("--no-sweep", dest="sweep", action="store_false") | ||
| 695 | ap.add_argument("--programs", type=int, default=300) | ||
| 696 | ap.add_argument("--seed", type=int, default=1) | ||
| 697 | ap.add_argument("--max-ops", type=int, default=1) | ||
| 698 | ap.add_argument("--ops") | ||
| 699 | ap.add_argument("--list-ops", action="store_true") | ||
| 700 | ap.add_argument("--no-literals", action="store_true") | ||
| 701 | ap.add_argument("--known", action="store_true") | ||
| 702 | ap.add_argument("--self-test", action="store_true") | ||
| 703 | ap.add_argument("--all-failures", action="store_true") | ||
| 704 | ap.add_argument("--oracle", choices=("translator", "gpu", "hw"), default="translator", | ||
| 705 | help="translator (default), Vulkan GPU via vk_harness, or AMD hardware oracle") | ||
| 706 | ap.add_argument("--exe", help="vk_harness executable for --oracle gpu") | ||
| 707 | ap.add_argument("--hw-arch", help="AMD hw_oracle architecture (if configured)") | ||
| 708 | args = ap.parse_args(argv) | ||
| 709 | if args.programs < 0 or args.max_ops < 1: print("programs must be nonnegative and max-ops positive", file=sys.stderr); return 2 | ||
| 710 | ops = [x.strip() for x in args.ops.split(",")] if args.ops else list(BASE) | ||
| 711 | bad = sorted(set(ops) - set(BASE)) | ||
| 712 | if bad: print(f"unknown opcode(s): {','.join(bad)}", file=sys.stderr); return 2 | ||
| 713 | if args.list_ops: | ||
| 714 | for op in BASE: print(op) | ||
| 715 | 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") | ||
| 716 | return 0 | ||
| 717 | if args.self_test: return 0 if self_test() else 1 | ||
| 718 | gpu = None | ||
| 719 | if args.oracle == "hw": | ||
| 720 | print("hardware oracle unavailable: this host has no configured AMD hw_oracle", file=sys.stderr); return 77 | ||
| 721 | if args.oracle == "gpu": | ||
| 722 | ext = ".exe" if os.name == "nt" else "" | ||
| 723 | gpu = args.exe or os.path.join(ROOT, "runtime", "build", "vk_harness" + ext) | ||
| 724 | try: | ||
| 725 | counts, skips, failures = run_batch(ops, args.programs, args.seed, args.max_ops, args.sweep, | ||
| 726 | not args.no_literals, args.known, args.all_failures, | ||
| 727 | args.oracle, gpu) | ||
| 728 | except GPUUnavailable as exc: | ||
| 729 | print(f"GPU oracle unavailable: {exc}", file=sys.stderr); return 77 | ||
| 730 | except HarnessError as exc: | ||
| 731 | print(f"harness error: {exc}", file=sys.stderr); return 2 | ||
| 732 | total = sum(counts.values()) + sum(skips.values()) | ||
| 733 | print(f"{args.oracle}: {counts['match']} match, {counts['mismatch']} mismatch; {total} total, {dict(skips)} skips") | ||
| 734 | if failures: | ||
| 735 | for lines, want, got, reason in failures: | ||
| 736 | print(f"MISMATCH: {reason}\nminimal program:") | ||
| 737 | print("\n".join(" " + x for x in lines)) | ||
| 738 | if want is not None and got is not None: | ||
| 739 | print("expected: " + " ".join(f"{x:08x}" for x in want)) | ||
| 740 | print("actual: " + " ".join(f"{x:08x}" for x in got)) | ||
| 741 | return 1 | ||
| 742 | return 0 | ||
| 743 | |||
| 744 | |||
| 745 | if __name__ == "__main__": | ||
| 746 | sys.exit(main()) | ||