"""Run XboxBvhBuilder.dll's translated compute programs on the GPU with synthetic inputs (TEST-594). docs/embedded_shaders.md: the DLL carries 52 console compute programs, and the translator takes all but one; none had been run on a GPU. This translates them from your own package and runs each one through vk_compute_test: python -I tools/bvh_gpu_smoke.py --game-dir [--work DIR] [--build runtime/build] [--max-shared-memory 32768] [--table-qword 0x2000] [--include-rehydration] [--json report.json] Each program reads its root arguments from a table at s[0:1], which in vk_compute_test is the heap base (Xbox VA 0). The heap starts as that table, 64-bit words that all hold --table-qword, then zeros up to --heap-bytes (seeded with VKC_HEAP_INIT). So every root descriptor points at a zeroed region past the table and every root constant reads --table-qword or 0. That is enough to run each program, not to give it meaningful work: most leave early, and the report says how many words each one changed. A run passes when it exits 0, the Khronos validation layer (when installed) reports no error, and a second run writes the same heap bytes. --checked also runs the programs whose effect reads straight off their code with inputs chosen for them, and compares every byte they write (CHECKED below). Five take a count and write that many 16- or 8-byte entries from thread index 0 up; 32 threads per group, so one group with a count of 20 also shows that entries past the count are left alone. PrefixSum64 scans 64 words in place into their exclusive prefix sum and stores the total. The three rehydration programs (Box16Rehydration, Box32Rehydration, LeafRehydration) belong to TEST-376, which checks them against tools/bvh_rehydrate.py; --include-rehydration runs them too. --max-shared-memory is passed to rdna2spirv.py: set it to the device's maxComputeSharedMemorySize (32768 on AMD's Windows driver; the translator's default is 65536). Over it, a program's LDS array shrinks to what the program uses, which the wave64 bitonic sorts need on a 32 KiB device. Nothing from the package is written outside --work. The report holds module names, statuses and counts only. """ import argparse import contextlib import json import math import os import struct import subprocess import sys import tempfile from pathlib import Path HERE = Path(__file__).resolve().parent if str(HERE) not in sys.path: sys.path.insert(0, str(HERE)) from file_mode import published_mode # noqa: E402 from replace_retry import replace as replace_retry # noqa: E402 from report_paths import same_report_path # noqa: E402 REHYDRATION = ("Box16Rehydration", "Box32Rehydration", "LeafRehydration") TABLE_QWORDS = 512 # a 4 KiB root table def heap_image(table_qword, heap_bytes): """The initial heap: TABLE_QWORDS words of table_qword, then zeros up to heap_bytes.""" table = struct.pack(f"<{TABLE_QWORDS}Q", *([table_qword] * TABLE_QWORDS)) if heap_bytes < len(table): raise ValueError(f"--heap-bytes must be at least {len(table)}") return table + bytes(heap_bytes - len(table)) def changed_words(initial, after): """How many 32-bit words of the heap differ from the initial image.""" n = min(len(initial), len(after)) // 4 a = struct.unpack_from(f"<{n}I", initial) b = struct.unpack_from(f"<{n}I", after) return sum(1 for x, y in zip(a, b) if x != y) def run_program(vkc, spv, init, dump, heap_words, validation, timeout): """One dispatch of one workgroup. Returns (status, last line of output): ok, 'exit N', validation, timeout.""" env = dict(os.environ, VKC_OUT_WORDS=str(heap_words), VKC_HEAP_INIT=str(init), VKC_DUMP=str(dump)) if validation: env["VK_INSTANCE_LAYERS"] = "VK_LAYER_KHRONOS_validation" try: p = subprocess.run([str(vkc), str(spv), "1", "dump"], capture_output=True, text=True, env=env, timeout=timeout) except subprocess.TimeoutExpired: return "timeout", "" out = (p.stdout or "") + (p.stderr or "") last = (out.strip().splitlines() or [""])[-1][:160] if p.returncode != 0: return f"exit {p.returncode}", last if "Validation Error" in out: return "validation", next((line for line in out.splitlines() if "VUID" in line), last)[:160] return "ok", last def smoke(spirv_dir, vkc, *, table_qword, heap_bytes, validation, timeout, include_rehydration, runner=run_program): """Run every program in spirv_dir twice. Returns [{name, status, words_changed, detail}] in name order.""" image = heap_image(table_qword, heap_bytes) results = [] with tempfile.TemporaryDirectory(prefix="bvh_gpu_smoke_") as tmp: tmp = Path(tmp) init = tmp / "heap.bin" init.write_bytes(image) for spv in sorted(Path(spirv_dir).glob("*.spv")): name = spv.stem if name in REHYDRATION and not include_rehydration: continue first, second = tmp / (name + ".1.bin"), tmp / (name + ".2.bin") status, detail = runner(vkc, spv, init, first, heap_bytes // 4, validation, timeout) changed = None if status == "ok": again, detail2 = runner(vkc, spv, init, second, heap_bytes // 4, validation, timeout) a = first.read_bytes() if first.is_file() else b"" b = second.read_bytes() if second.is_file() else b"" if again != "ok": status, detail = again, detail2 elif not a or a != b: status, detail = "nondeterministic", "the two runs wrote different heap bytes" else: status = "pass" changed = changed_words(image, a) if a else None results.append({"name": name, "status": status, "words_changed": changed, "detail": detail}) return results # ---- checked runs ---- # # Root-table fields as each program reads them (offsets in the table at s[0:1]; addresses are 64-bit, counts and # values 32-bit), and what it writes. FILL marks the bytes a program must leave alone. DST, SRC, SUMS = 0x2000, 0x6000, 0x4000 # regions past the 4 KiB table FILL = 0xAA COUNT = 20 # within one 32-thread group def _u32(heap, at): return struct.unpack_from("8} {r['detail'] if r['status'] != 'pass' else ''}") counts = {} for r in results: counts[r["status"]] = counts.get(r["status"], 0) + 1 working = sum(1 for r in results if r["status"] == "pass" and r["words_changed"] and r["words_changed"] > 0) print(f"{counts.get('pass', 0)} of {len(results)} pass; {working} changed heap words beyond running; " + ", ".join(f"{k} {v}" for k, v in sorted(counts.items()) if k != "pass")) checked = [] if a.checked: checked = run_checked(spirv, vkc, heap_bytes=a.heap_bytes, validation=not a.no_validation, timeout=a.timeout) for r in checked: print(f"checked {r['name']:20} {r['status']:10} {r['detail']}") print(f"checked: {sum(r['status'] == 'pass' for r in checked)} of {len(checked)} " f"write exactly what they should") if a.json: payload = {"max_shared_memory": a.max_shared_memory, "table_qword": a.table_qword, "heap_bytes": a.heap_bytes, "results": results, "checked": checked} try: _write_json_atomic(a.json, payload) except OSError as e: print(f"error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) return 2 ok = counts.get("pass", 0) == len(results) and all(r["status"] == "pass" for r in checked) return 0 if ok else 1 if __name__ == "__main__": try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode sys.stdout.reconfigure(errors="replace") except (AttributeError, ValueError, OSError): pass sys.exit(main())