diff options
Diffstat (limited to 'tools/f64_diff.py')
| -rw-r--r-- | tools/f64_diff.py | 102 |
1 files changed, 81 insertions, 21 deletions
diff --git a/tools/f64_diff.py b/tools/f64_diff.py index 8744a5c37..340f3d106 100644 --- a/tools/f64_diff.py +++ b/tools/f64_diff.py | |||
| @@ -7,9 +7,10 @@ and executes their SPIR-V with the semantic one-lane interpreter. Only synthetic | |||
| 7 | are created; no game files are read. | 7 | are created; no game files are read. |
| 8 | 8 | ||
| 9 | The GPU path is deliberately optional. It translates the same fragment shader, runs it | 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 | 10 | through vk_harness, and reads back RGBA32F words. ``--oracle hw`` runs the programs natively |
| 11 | returns 77 when the host has no configured AMD hw_oracle. ``--known`` runs known | 11 | on an AMD GPU through tools/hw_oracle (``--hw-arch`` selects the architecture) and compares |
| 12 | divergence probes; a reproduced mismatch intentionally returns 1. | 12 | them with the reference; it returns 77 only when that oracle is unavailable. ``--known`` runs |
| 13 | known divergence probes; a reproduced mismatch intentionally returns 1. | ||
| 13 | """ | 14 | """ |
| 14 | import argparse | 15 | import argparse |
| 15 | import gc | 16 | import gc |
| @@ -72,6 +73,10 @@ class GPUUnavailable(Exception): | |||
| 72 | pass | 73 | pass |
| 73 | 74 | ||
| 74 | 75 | ||
| 76 | class HWUnavailable(Exception): | ||
| 77 | """No configured AMD hw_oracle on this host (tools/hw_oracle/); the CLI turns it into exit 77.""" | ||
| 78 | |||
| 79 | |||
| 75 | def words_to_bits(lo, hi): | 80 | def words_to_bits(lo, hi): |
| 76 | return ((hi & M32) << 32) | (lo & M32) | 81 | return ((hi & M32) << 32) | (lo & M32) |
| 77 | 82 | ||
| @@ -166,8 +171,13 @@ def add_bits(a, b, mode=0): | |||
| 166 | if is_inf(a) or is_inf(b): | 171 | if is_inf(a) or is_inf(b): |
| 167 | af, bf = to_float(a), to_float(b) | 172 | af, bf = to_float(a), to_float(b) |
| 168 | return from_float(af + bf) | 173 | 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) | 174 | exact = to_fraction(a) + to_fraction(b) |
| 175 | # IEEE 754-2019 6.3: an exact zero sum of two zeros of the same sign keeps that sign in every mode; any other | ||
| 176 | # exact zero (opposite-signed zeros, or x + (-x)) is -0 only when rounding toward negative, +0 otherwise. | ||
| 177 | if is_zero(a) and is_zero(b) and (a ^ b) >> 63 == 0: | ||
| 178 | negzero = bool(a >> 63) | ||
| 179 | else: | ||
| 180 | negzero = mode == 2 | ||
| 171 | return round_fraction(exact, mode, negzero) | 181 | return round_fraction(exact, mode, negzero) |
| 172 | 182 | ||
| 173 | 183 | ||
| @@ -452,6 +462,31 @@ def run_gpu(lines, name, tmpdir, gpu): | |||
| 452 | with open(raw, "rb") as f: return list(struct.unpack("<4I", f.read())) | 462 | with open(raw, "rb") as f: return list(struct.unpack("<4I", f.read())) |
| 453 | 463 | ||
| 454 | 464 | ||
| 465 | # The float MODE the hardware kernels start with: the one docs/design.md infers for the game's shaders (the same as | ||
| 466 | # tools/fmisc_diff.py): IEEE off so output modifiers apply, DX10_CLAMP on. Directives an architecture cannot set make | ||
| 467 | # the program a counted skip (runner.Oracle.run returns the reason). | ||
| 468 | HW_MODE = {"ieee": 0, "dx10_clamp": 1, "denorm32": 0} | ||
| 469 | |||
| 470 | |||
| 471 | def hw_kernel(lines): | ||
| 472 | """A raw tools/hw_oracle kernel: the program on one lane, then v8..v11 stored at the output pointer.""" | ||
| 473 | from hw_oracle import asm | ||
| 474 | return asm.Kernel(list(lines) + ["v_mov_b32 v0, 0", "global_store_b128 v0, v[8:11], s[2:3]", "s_endpgm"], | ||
| 475 | wave=32, threads=1, words=4, raw=True, mode=HW_MODE) | ||
| 476 | |||
| 477 | |||
| 478 | def open_hw_oracle(arch=None): | ||
| 479 | """The AMD hardware oracle, or HWUnavailable when its tools or device are missing.""" | ||
| 480 | try: | ||
| 481 | from hw_oracle import runner | ||
| 482 | except ImportError as exc: | ||
| 483 | raise HWUnavailable(f"tools/hw_oracle cannot be imported: {exc}") from exc | ||
| 484 | try: | ||
| 485 | return runner.open_oracle(arch=arch) | ||
| 486 | except runner.Unavailable as exc: | ||
| 487 | raise HWUnavailable(str(exc)) from exc | ||
| 488 | |||
| 489 | |||
| 455 | def rand_bits(rng): | 490 | def rand_bits(rng): |
| 456 | # Mostly finite normals, with signed zeros, infinities and NaNs for predicate/class coverage. | 491 | # Mostly finite normals, with signed zeros, infinities and NaNs for predicate/class coverage. |
| 457 | if rng.random() < .2: | 492 | if rng.random() < .2: |
| @@ -578,7 +613,13 @@ def equivalent(a, b, kind="int"): | |||
| 578 | return a == b | 613 | return a == b |
| 579 | 614 | ||
| 580 | 615 | ||
| 581 | def run_one(lines, name, tmp, oracle="translator", gpu=None, include_known=False): | 616 | def run_one(lines, name, tmp, oracle="translator", gpu=None, include_known=False, hw_words=None): |
| 617 | """Compare one program with the reference. ``gpu`` is the prepared Vulkan context for --oracle gpu, or the open | ||
| 618 | hw_oracle for --oracle hw (whose result may be passed in as ``hw_words``: four words or a skip reason).""" | ||
| 619 | if oracle == "hw": | ||
| 620 | # The hardware runs every form natively, so the translator-only exclusions do not apply: compare it with the | ||
| 621 | # whole reference, the known cases included. | ||
| 622 | include_known = True | ||
| 582 | if not include_known: | 623 | if not include_known: |
| 583 | for line in lines: | 624 | for line in lines: |
| 584 | if " mul:" in line or " div:" in line: | 625 | if " mul:" in line or " div:" in line: |
| @@ -593,6 +634,14 @@ def run_one(lines, name, tmp, oracle="translator", gpu=None, include_known=False | |||
| 593 | return "skip", f"reference limitation: {type(exc).__name__}: {exc}", None, None | 634 | 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): | 635 | 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 | 636 | return "skip", "GLSL.std.450 InverseSqrt/Sqrt double-precision result precision is implementation-defined", expected, None |
| 637 | if oracle == "hw": | ||
| 638 | if any(line.lstrip().startswith(("v_rcp_f64 ", "v_rsq_f64 ", "v_sqrt_f64 ")) for line in lines): | ||
| 639 | return "skip", ("native v_rcp_f64/v_rsq_f64/v_sqrt_f64 are approximations (about 26 bits, PROC-216) and " | ||
| 640 | "the reference is exact, so their result is not judged"), expected, None | ||
| 641 | actual = hw_words if hw_words is not None else gpu.run([hw_kernel(lines)])[0] | ||
| 642 | if isinstance(actual, str): return "skip", f"hardware: {actual}", expected, None | ||
| 643 | actual = [int(x) & M32 for x in actual] | ||
| 644 | return ("match", "", expected, actual) if equivalent(expected, actual, output_kind(lines)) else ("mismatch", "word comparison", expected, actual) | ||
| 596 | try: actual = run_gpu(lines, name, tmp, gpu) if oracle == "gpu" else translate(lines, name, tmp) | 645 | 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 | 646 | 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 | 647 | except (IndexError, KeyError, ValueError, OverflowError) as exc: return "skip", f"translator/interpreter limitation: {type(exc).__name__}: {exc}", expected, None |
| @@ -626,7 +675,7 @@ def shrink(lines, expected, oracle="translator", gpu=None, gpu_ctx=None, tmpdir= | |||
| 626 | 675 | ||
| 627 | 676 | ||
| 628 | def run_batch(ops, programs, seed, max_ops=1, sweep=True, allow_literal=True, known=False, all_failures=False, | 677 | def run_batch(ops, programs, seed, max_ops=1, sweep=True, allow_literal=True, known=False, all_failures=False, |
| 629 | oracle="translator", gpu=None): | 678 | oracle="translator", gpu=None, hw=None): |
| 630 | counts = Counter(); skips = Counter(); failures = [] | 679 | counts = Counter(); skips = Counter(); failures = [] |
| 631 | rng = random.Random(seed) | 680 | rng = random.Random(seed) |
| 632 | sequence = [(op, True, None) for op in ops] if sweep else [] | 681 | sequence = [(op, True, None) for op in ops] if sweep else [] |
| @@ -634,18 +683,24 @@ def run_batch(ops, programs, seed, max_ops=1, sweep=True, allow_literal=True, kn | |||
| 634 | if known: | 683 | if known: |
| 635 | sequence += [("v_div_fixup_f64" if label == "div-fixup-nan-s0" else "v_add_f64", True, label) | 684 | sequence += [("v_div_fixup_f64" if label == "div-fixup-nan-s0" else "v_add_f64", True, label) |
| 636 | for label in KNOWN_DIVERGENCES] | 685 | for label in KNOWN_DIVERGENCES] |
| 686 | cases = [] | ||
| 687 | for idx, (op, is_sweep, known_case) in enumerate(sequence): | ||
| 688 | setup_lines, body_lines, _, _ = make_case(rng, op, allow_literal, known_case) | ||
| 689 | lines = setup_lines + body_lines | ||
| 690 | if not is_sweep and not known_case: | ||
| 691 | n_ops = rng.randint(1, max_ops) | ||
| 692 | for _ in range(n_ops - 1): | ||
| 693 | _, extra_body, _, _ = make_case(rng, rng.choice(ops), allow_literal) | ||
| 694 | lines.extend(extra_body) | ||
| 695 | cases.append((idx, lines, known_case)) | ||
| 696 | # One launch for the whole campaign; a failing program is re-run alone while it is shrunk. | ||
| 697 | hw_results = hw.run([hw_kernel(lines) for _, lines, _ in cases]) if oracle == "hw" else None | ||
| 637 | with tempfile.TemporaryDirectory(prefix="f64-diff-") as tmp: | 698 | with tempfile.TemporaryDirectory(prefix="f64-diff-") as tmp: |
| 638 | gpu_ctx = prepare_gpu(gpu, tmp) if oracle == "gpu" else None | 699 | gpu_ctx = prepare_gpu(gpu, tmp) if oracle == "gpu" else hw if oracle == "hw" else None |
| 639 | for idx, (op, is_sweep, known_case) in enumerate(sequence): | 700 | for idx, lines, known_case in cases: |
| 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, | 701 | status, reason, want, got = run_one(lines, f"ps_f64_{idx:05d}", tmp, oracle, gpu_ctx, |
| 648 | include_known=bool(known_case)) | 702 | include_known=bool(known_case), |
| 703 | hw_words=hw_results[idx] if hw_results is not None else None) | ||
| 649 | if status == "skip": skips[reason] += 1 | 704 | if status == "skip": skips[reason] += 1 |
| 650 | else: counts[status] += 1 | 705 | else: counts[status] += 1 |
| 651 | if status == "mismatch": | 706 | if status == "mismatch": |
| @@ -704,7 +759,7 @@ def main(argv=None): | |||
| 704 | ap.add_argument("--oracle", choices=("translator", "gpu", "hw"), default="translator", | 759 | ap.add_argument("--oracle", choices=("translator", "gpu", "hw"), default="translator", |
| 705 | help="translator (default), Vulkan GPU via vk_harness, or AMD hardware oracle") | 760 | help="translator (default), Vulkan GPU via vk_harness, or AMD hardware oracle") |
| 706 | ap.add_argument("--exe", help="vk_harness executable for --oracle gpu") | 761 | ap.add_argument("--exe", help="vk_harness executable for --oracle gpu") |
| 707 | ap.add_argument("--hw-arch", help="AMD hw_oracle architecture (if configured)") | 762 | ap.add_argument("--hw-arch", help="GPU architecture hw_oracle assembles for (default: detected)") |
| 708 | args = ap.parse_args(argv) | 763 | 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 | 764 | 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) | 765 | ops = [x.strip() for x in args.ops.split(",")] if args.ops else list(BASE) |
| @@ -715,20 +770,25 @@ def main(argv=None): | |||
| 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") | 770 | 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 | 771 | return 0 |
| 717 | if args.self_test: return 0 if self_test() else 1 | 772 | if args.self_test: return 0 if self_test() else 1 |
| 718 | gpu = None | 773 | gpu = hw = None |
| 719 | if args.oracle == "hw": | 774 | if args.oracle == "hw": |
| 720 | print("hardware oracle unavailable: this host has no configured AMD hw_oracle", file=sys.stderr); return 77 | 775 | try: hw = open_hw_oracle(args.hw_arch) |
| 776 | except HWUnavailable as exc: | ||
| 777 | print(f"hardware oracle unavailable: {exc}", file=sys.stderr); return 77 | ||
| 778 | print(f"hardware oracle: {getattr(hw, 'device', 'AMD GPU')}") | ||
| 721 | if args.oracle == "gpu": | 779 | if args.oracle == "gpu": |
| 722 | ext = ".exe" if os.name == "nt" else "" | 780 | ext = ".exe" if os.name == "nt" else "" |
| 723 | gpu = args.exe or os.path.join(ROOT, "runtime", "build", "vk_harness" + ext) | 781 | gpu = args.exe or os.path.join(ROOT, "runtime", "build", "vk_harness" + ext) |
| 724 | try: | 782 | try: |
| 725 | counts, skips, failures = run_batch(ops, args.programs, args.seed, args.max_ops, args.sweep, | 783 | 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, | 784 | not args.no_literals, args.known, args.all_failures, |
| 727 | args.oracle, gpu) | 785 | args.oracle, gpu, hw) |
| 728 | except GPUUnavailable as exc: | 786 | except GPUUnavailable as exc: |
| 729 | print(f"GPU oracle unavailable: {exc}", file=sys.stderr); return 77 | 787 | print(f"GPU oracle unavailable: {exc}", file=sys.stderr); return 77 |
| 730 | except HarnessError as exc: | 788 | except (HarnessError, RuntimeError) as exc: |
| 731 | print(f"harness error: {exc}", file=sys.stderr); return 2 | 789 | print(f"harness error: {exc}", file=sys.stderr); return 2 |
| 790 | finally: | ||
| 791 | if hw is not None: hw.close() | ||
| 732 | total = sum(counts.values()) + sum(skips.values()) | 792 | total = sum(counts.values()) + sum(skips.values()) |
| 733 | print(f"{args.oracle}: {counts['match']} match, {counts['mismatch']} mismatch; {total} total, {dict(skips)} skips") | 793 | print(f"{args.oracle}: {counts['match']} match, {counts['mismatch']} mismatch; {total} total, {dict(skips)} skips") |
| 734 | if failures: | 794 | if failures: |