diff options
| author | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-25 19:04:24 -0500 |
|---|---|---|
| committer | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-25 19:04:24 -0500 |
| commit | 8d832fd10913064e1c8aec74191e3ba8f70211c8 (patch) | |
| tree | e365199d7d86ebf592a5a0dc2f07cda4b74b58a7 /scripts | |
| parent | 5da3b6be3cefc1499452ba8c8370a50092674d61 (diff) | |
| parent | c50ed94b35b37b697ab9c5fd176f3738480b4db5 (diff) | |
Merge main into rt-title-every-budget (#2122)
#2098 split the every-pass loop of refresh_title_textures by mode: with
LEONIDA_TEXTURE_REFRESH_ASYNC every persistent mapping is polled each
pass and only stale unmapped textures are visited, without it all mapped
or stale ones are. The async branch is kept as main has it.
LEONIDA_TITLE_EVERY_BUDGET_US applies to the synchronous pass, the one
before a submission on the submitting thread; under async the pass runs
on the refresh worker and the limit does not apply (README says so).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'scripts')
| -rw-r--r-- | scripts/audit_shader4_regs.py | 19 | ||||
| -rw-r--r-- | scripts/check_compute_journal_overlay.py | 106 | ||||
| -rw-r--r-- | scripts/compute_workers_win.py | 190 | ||||
| -rw-r--r-- | scripts/corpus_watch.py | 195 | ||||
| -rw-r--r-- | scripts/first_look.ps1 | 10 | ||||
| -rw-r--r-- | scripts/run_gpu_tests.py | 28 | ||||
| -rw-r--r-- | scripts/translate_pipeline_compute.py | 208 | ||||
| -rw-r--r-- | scripts/vs_layout_census.py | 40 |
8 files changed, 722 insertions, 74 deletions
diff --git a/scripts/audit_shader4_regs.py b/scripts/audit_shader4_regs.py index 59aff3bc6..50fc5500e 100644 --- a/scripts/audit_shader4_regs.py +++ b/scripts/audit_shader4_regs.py | |||
| @@ -263,8 +263,8 @@ def detect_wave64(insns): | |||
| 263 | 263 | ||
| 264 | 264 | ||
| 265 | def audit(disasm_dir, fssm_dir=None, dxbc_dir=None, stages=("cs", "ms", "gs"), limit=None, *, report_path=None): | 265 | def audit(disasm_dir, fssm_dir=None, dxbc_dir=None, stages=("cs", "ms", "gs"), limit=None, *, report_path=None): |
| 266 | if limit is not None and limit < 0: | 266 | if limit is not None and limit < 1: |
| 267 | raise ValueError("limit must be non-negative") | 267 | raise ValueError("limit must be at least 1") |
| 268 | parent = os.path.dirname(os.path.realpath(disasm_dir)) | 268 | parent = os.path.dirname(os.path.realpath(disasm_dir)) |
| 269 | fssm_dir = fssm_dir or os.path.join(parent, "fssm") | 269 | fssm_dir = fssm_dir or os.path.join(parent, "fssm") |
| 270 | dxbc_dir = dxbc_dir or parent | 270 | dxbc_dir = dxbc_dir or parent |
| @@ -395,16 +395,25 @@ def print_report(rep): | |||
| 395 | print(f" {v:6d} {k}") | 395 | print(f" {v:6d} {k}") |
| 396 | 396 | ||
| 397 | 397 | ||
| 398 | def shader_count(text): | ||
| 399 | """--limit: at least 1; 0 used to mean an audit of nothing that still printed a zero report.""" | ||
| 400 | try: | ||
| 401 | value = int(text, 0) | ||
| 402 | except ValueError: | ||
| 403 | raise argparse.ArgumentTypeError("must be at least 1") from None | ||
| 404 | if value < 1: | ||
| 405 | raise argparse.ArgumentTypeError("must be at least 1") | ||
| 406 | return value | ||
| 407 | |||
| 408 | |||
| 398 | def main(argv=None): | 409 | def main(argv=None): |
| 399 | ap = argparse.ArgumentParser(description="Audit CS/MS/GS RSRC2/PSV0 headers and read-before-write registers.") | 410 | ap = argparse.ArgumentParser(description="Audit CS/MS/GS RSRC2/PSV0 headers and read-before-write registers.") |
| 400 | ap.add_argument("disasm_dir", help="directory of disassembled .s files") | 411 | ap.add_argument("disasm_dir", help="directory of disassembled .s files") |
| 401 | ap.add_argument("--fssm", default=None, help="directory of .fssm files (default: <disasm_dir>/../fssm)") | 412 | ap.add_argument("--fssm", default=None, help="directory of .fssm files (default: <disasm_dir>/../fssm)") |
| 402 | ap.add_argument("--dxbc", default=None, help="directory of .dxbc files (default: <disasm_dir>/..)") | 413 | ap.add_argument("--dxbc", default=None, help="directory of .dxbc files (default: <disasm_dir>/..)") |
| 403 | ap.add_argument("--json", dest="json_out", default=None, help="optional path to write full JSON report") | 414 | ap.add_argument("--json", dest="json_out", default=None, help="optional path to write full JSON report") |
| 404 | ap.add_argument("--limit", type=int, default=None, help="stop after N .s files") | 415 | ap.add_argument("--limit", type=shader_count, default=None, help="stop after N .s files (at least 1)") |
| 405 | a = ap.parse_args(argv) | 416 | a = ap.parse_args(argv) |
| 406 | if a.limit is not None and a.limit < 0: | ||
| 407 | ap.exit(2, f"{ap.prog}: error: --limit must be non-negative\n") | ||
| 408 | # A bad path is one ERROR line, not a traceback out of os.listdir: the audit of a whole corpus can | 417 | # A bad path is one ERROR line, not a traceback out of os.listdir: the audit of a whole corpus can |
| 409 | # run for minutes, and an explicit --fssm/--dxbc that does not exist would otherwise be counted as | 418 | # run for minutes, and an explicit --fssm/--dxbc that does not exist would otherwise be counted as |
| 410 | # "(missing fssm)" and print a report that looks right. | 419 | # "(missing fssm)" and print a report that looks right. |
diff --git a/scripts/check_compute_journal_overlay.py b/scripts/check_compute_journal_overlay.py new file mode 100644 index 000000000..c346436f9 --- /dev/null +++ b/scripts/check_compute_journal_overlay.py | |||
| @@ -0,0 +1,106 @@ | |||
| 1 | """Check a disposable journal against two locally generated compute PSOs. No game files needed. | ||
| 2 | |||
| 3 | Build d3d12_compute_journal_test first, then run this script with the path to that executable. | ||
| 4 | --require-hit also requires the driver's application-cache-hit bit (not a timing heuristic). | ||
| 5 | """ | ||
| 6 | import argparse | ||
| 7 | import hashlib | ||
| 8 | import json | ||
| 9 | import os | ||
| 10 | from pathlib import Path | ||
| 11 | import re | ||
| 12 | import shutil | ||
| 13 | import subprocess | ||
| 14 | import tempfile | ||
| 15 | import time | ||
| 16 | |||
| 17 | |||
| 18 | def require(ok, message): | ||
| 19 | if not ok: | ||
| 20 | raise RuntimeError(message) | ||
| 21 | |||
| 22 | |||
| 23 | def entries(cache): | ||
| 24 | d = cache / "pipeline_cache.d" | ||
| 25 | if not d.exists(): | ||
| 26 | return {} | ||
| 27 | out = {} | ||
| 28 | for p in d.iterdir(): | ||
| 29 | require(re.fullmatch(r"cs-[0-9a-f]{16}\.bin", p.name) and p.is_file() and | ||
| 30 | 32 < p.stat().st_size <= 8 << 20, "unexpected file in one-PSO journal") | ||
| 31 | out[p.name] = (hashlib.sha256(p.read_bytes()).digest(), p.stat().st_mtime_ns) | ||
| 32 | return out | ||
| 33 | |||
| 34 | |||
| 35 | def run(exe, root, device, strict): | ||
| 36 | seed = root / "cold" | ||
| 37 | before = None | ||
| 38 | results = {} | ||
| 39 | adapter = None | ||
| 40 | for label, second in (("cold", False), ("external-A", False), | ||
| 41 | ("new-B", True), ("local-B", True)): | ||
| 42 | cache = root / label | ||
| 43 | cache.mkdir() | ||
| 44 | if label == "local-B": | ||
| 45 | # Bring only B into a fresh process; no session or shared cache crosses this boundary. | ||
| 46 | (cache / "pipeline_cache.d").mkdir() | ||
| 47 | src, = (root / "new-B" / "pipeline_cache.d").iterdir() | ||
| 48 | shutil.copy2(src, cache / "pipeline_cache.d" / src.name) | ||
| 49 | local_before = entries(cache) | ||
| 50 | env = {k: v for k, v in os.environ.items() if not k.upper().startswith("LEONIDA_")} | ||
| 51 | env.update(LEONIDA_PIPELINE_CACHE_DIR=str(cache), LEONIDA_TRACE_PIPELINE_COMPILE="1", | ||
| 52 | LEONIDA_PIPELINE_CACHE_BYTES=str(8 << 20), LEONIDA_PIPELINE_JOURNAL_BYTES=str(8 << 20), | ||
| 53 | LEONIDA_PIPELINE_JOURNAL="1") | ||
| 54 | if device: | ||
| 55 | env["LEONIDA_VK_DEVICE"] = device | ||
| 56 | if label != "cold": | ||
| 57 | env["LEONIDA_PIPELINE_JOURNAL_SEED_DIR"] = str(seed / "pipeline_cache.d") | ||
| 58 | p = subprocess.run([str(exe)] + (["--second-shader"] if second else []), | ||
| 59 | stdin=subprocess.DEVNULL, capture_output=True, text=True, errors="replace", | ||
| 60 | cwd=cache, env=env, timeout=60) | ||
| 61 | if p.returncode == 77: | ||
| 62 | print("SKIP: the authored compute fixture is unsupported on this device") | ||
| 63 | return 77 | ||
| 64 | expected = 14 if second else 10 | ||
| 65 | require(p.returncode == 0 and | ||
| 66 | f"compute journal: direct Dispatch(4,1,1) copied both expected words (4,{expected})" | ||
| 67 | in p.stdout.splitlines(), f"{label}: GPU readback did not match") | ||
| 68 | devices = [x.removeprefix("device: ") for x in p.stdout.splitlines() if x.startswith("device: ")] | ||
| 69 | require(len(devices) == 1 and (adapter is None or adapter == devices[0]), "inconsistent GPU selection") | ||
| 70 | adapter = devices[0] | ||
| 71 | calls = [x for x in p.stderr.splitlines() if x.startswith("[rt] pipeline-compile trigger=")] | ||
| 72 | require(len(calls) == 1, f"{label}: expected one compute creation") | ||
| 73 | m = re.search(r" hit=(-1|0|1) bytes=\d+ variant=\d+ result=0 ", calls[0]) | ||
| 74 | require(m is not None, f"{label}: missing feedback field or unsuccessful create") | ||
| 75 | hit = int(m[1]) | ||
| 76 | local = entries(cache) | ||
| 77 | if label == "cold": | ||
| 78 | require(len(local) == 1, "cold A was not journaled") | ||
| 79 | source, = (seed / "pipeline_cache.d").iterdir() | ||
| 80 | # Make an erroneous hourly LRU touch observable without making the probe depend on system time. | ||
| 81 | old = time.time_ns() - 48 * 3600 * 10**9 | ||
| 82 | os.utime(source, ns=(old, old)) | ||
| 83 | before = entries(seed) | ||
| 84 | elif label == "new-B": | ||
| 85 | require(len(local) == 1 and not (local.keys() & before.keys()), "missing distinct local B") | ||
| 86 | else: | ||
| 87 | if strict: | ||
| 88 | require(hit == 1, f"{label}: driver reported no application-cache hit") | ||
| 89 | if hit == 1: | ||
| 90 | require(local == local_before, f"{label}: cache hit changed disposable journal") | ||
| 91 | require(entries(seed) == before, f"{label}: seed contents or last-write time changed") | ||
| 92 | results[label] = {"readback": [4, expected], "driver_hit": hit, "local_entries": len(local)} | ||
| 93 | print(json.dumps({"device": adapter, "runs": results}, sort_keys=True)) | ||
| 94 | return 0 | ||
| 95 | |||
| 96 | |||
| 97 | if __name__ == "__main__": | ||
| 98 | parser = argparse.ArgumentParser(description=__doc__) | ||
| 99 | parser.add_argument("executable", type=Path, help="built d3d12_compute_journal_test.exe") | ||
| 100 | parser.add_argument("--device", help="optional LEONIDA_VK_DEVICE selector") | ||
| 101 | parser.add_argument("--require-hit", action="store_true") | ||
| 102 | args = parser.parse_args() | ||
| 103 | exe = args.executable.resolve(strict=True) | ||
| 104 | require(exe.name.lower() == "d3d12_compute_journal_test.exe", "expected the compute test, not the game") | ||
| 105 | with tempfile.TemporaryDirectory(prefix="leonida-authored-journal-") as tmp: | ||
| 106 | raise SystemExit(run(exe, Path(tmp), args.device, args.require_hit)) | ||
diff --git a/scripts/compute_workers_win.py b/scripts/compute_workers_win.py new file mode 100644 index 000000000..04eab8adb --- /dev/null +++ b/scripts/compute_workers_win.py | |||
| @@ -0,0 +1,190 @@ | |||
| 1 | """Windows process/lock adapter for translate_pipeline_compute.py (CPython, no extra packages). | ||
| 2 | |||
| 3 | Only a small bootstrap runs before job assignment. It receives no input path or work until the | ||
| 4 | parent verifies its job and opens the gate. Parent death closes the gate or the kill-on-close job. | ||
| 5 | """ | ||
| 6 | import contextlib | ||
| 7 | import ctypes as c | ||
| 8 | from ctypes import wintypes as w | ||
| 9 | import json | ||
| 10 | import os | ||
| 11 | from pathlib import Path | ||
| 12 | import subprocess | ||
| 13 | import sys | ||
| 14 | import time | ||
| 15 | |||
| 16 | kernel = c.WinDLL("kernel32", use_last_error=True) | ||
| 17 | H, D, Z = w.HANDLE, w.DWORD, c.c_size_t | ||
| 18 | |||
| 19 | |||
| 20 | def api(name, result, *args): | ||
| 21 | f = getattr(kernel, name) | ||
| 22 | f.argtypes, f.restype = args, result | ||
| 23 | return f | ||
| 24 | |||
| 25 | |||
| 26 | def check(value): | ||
| 27 | if not value: | ||
| 28 | raise c.WinError(c.get_last_error()) | ||
| 29 | return value | ||
| 30 | |||
| 31 | |||
| 32 | class Basic(c.Structure): | ||
| 33 | _fields_ = [("time", c.c_int64 * 2), ("flags", D), ("min_ws", Z), ("max_ws", Z), | ||
| 34 | ("processes", D), ("affinity", Z), ("priority", D), ("scheduling", D)] | ||
| 35 | |||
| 36 | |||
| 37 | class Extended(c.Structure): | ||
| 38 | _fields_ = [("basic", Basic), ("io", c.c_uint64 * 6), ("process_mem", Z), | ||
| 39 | ("job_mem", Z), ("peak_process", Z), ("peak_job", Z)] | ||
| 40 | |||
| 41 | |||
| 42 | class Accounting(c.Structure): | ||
| 43 | _fields_ = [("time", c.c_int64 * 4), ("faults", D), ("total", D), ("active", D), ("ended", D)] | ||
| 44 | |||
| 45 | |||
| 46 | close = api("CloseHandle", w.BOOL, H) | ||
| 47 | create_job = api("CreateJobObjectW", H, H, w.LPCWSTR) | ||
| 48 | set_job = api("SetInformationJobObject", w.BOOL, H, D, H, D) | ||
| 49 | query_job = api("QueryInformationJobObject", w.BOOL, H, D, H, D, H) | ||
| 50 | assign = api("AssignProcessToJobObject", w.BOOL, H, H) | ||
| 51 | inside = api("IsProcessInJob", w.BOOL, H, H, c.POINTER(w.BOOL)) | ||
| 52 | terminate = api("TerminateJobObject", w.BOOL, H, D) | ||
| 53 | current = api("GetCurrentProcess", H) | ||
| 54 | priority = api("GetPriorityClass", D, H) | ||
| 55 | create_file = api("CreateFileW", H, w.LPCWSTR, D, D, H, D, D, H) | ||
| 56 | LOW = subprocess.BELOW_NORMAL_PRIORITY_CLASS | ||
| 57 | PROCESS_MEMORY, PRIORITY, TWO_ACTIVE, KILL_ON_CLOSE = 0x100, 0x20, 0x8, 0x2000 | ||
| 58 | |||
| 59 | |||
| 60 | def flags(worker): | ||
| 61 | return PROCESS_MEMORY | PRIORITY | ((TWO_ACTIVE | KILL_ON_CLOSE) if worker else 0) | ||
| 62 | |||
| 63 | |||
| 64 | def verify(job, process, mib, worker): | ||
| 65 | info, member = Extended(), w.BOOL() | ||
| 66 | check(inside(process, job, c.byref(member))) | ||
| 67 | check(query_job(job, 9, c.byref(info), c.sizeof(info), None)) | ||
| 68 | if (not member.value or info.basic.flags != flags(worker) or info.process_mem != mib << 20 or | ||
| 69 | info.basic.priority != LOW or priority(process) != LOW or | ||
| 70 | (worker and info.basic.processes != 2)): | ||
| 71 | raise RuntimeError("Windows compute job limits not in force") | ||
| 72 | |||
| 73 | |||
| 74 | @contextlib.contextmanager | ||
| 75 | def job(mib, worker): | ||
| 76 | if not 0 < mib <= ((1 << (c.sizeof(Z)*8))-1) >> 20: | ||
| 77 | raise ValueError("invalid --memory-mib for Windows job") | ||
| 78 | h = check(create_job(None, None)) # unnamed, never inherited; no breakaway | ||
| 79 | try: | ||
| 80 | info = Extended() | ||
| 81 | info.basic.flags, info.basic.priority = flags(worker), LOW | ||
| 82 | info.basic.processes, info.process_mem = (2 if worker else 0), mib << 20 | ||
| 83 | check(set_job(h, 9, c.byref(info), c.sizeof(info))) | ||
| 84 | yield h | ||
| 85 | finally: | ||
| 86 | check(close(h)) | ||
| 87 | |||
| 88 | |||
| 89 | def budget_coordinator(mib): | ||
| 90 | # No KILL_ON_CLOSE for the caller itself. Its limits survive handle close until process exit. | ||
| 91 | with job(mib, False) as h: | ||
| 92 | check(assign(h, current())) | ||
| 93 | verify(h, current(), mib, False) | ||
| 94 | |||
| 95 | |||
| 96 | @contextlib.contextmanager | ||
| 97 | def output_lock(path): | ||
| 98 | # One nonblocking, no-share open; duplicated into workers so an interrupted parent cannot | ||
| 99 | # release exclusivity before the last worker has actually left. Never delete/recreate the lock. | ||
| 100 | h = create_file(str(path), 0xc0000000, 0, None, 4, 0x80, None) | ||
| 101 | if h == H(-1).value: | ||
| 102 | raise c.WinError(c.get_last_error()) | ||
| 103 | try: | ||
| 104 | yield h | ||
| 105 | finally: | ||
| 106 | check(close(h)) | ||
| 107 | |||
| 108 | |||
| 109 | def drain(h): | ||
| 110 | check(terminate(h, 1)) | ||
| 111 | end = time.monotonic()+10 | ||
| 112 | while True: | ||
| 113 | a = Accounting() | ||
| 114 | check(query_job(h, 1, c.byref(a), c.sizeof(a), None)) | ||
| 115 | if not a.active: | ||
| 116 | return | ||
| 117 | if time.monotonic() >= end: | ||
| 118 | raise RuntimeError("Windows compute job did not drain") | ||
| 119 | time.sleep(.02) | ||
| 120 | |||
| 121 | |||
| 122 | @contextlib.contextmanager | ||
| 123 | def start(request, mib, lock): | ||
| 124 | with job(mib, True) as h: | ||
| 125 | si = subprocess.STARTUPINFO(lpAttributeList={"handle_list": [lock]}) | ||
| 126 | os.set_handle_inheritable(lock, True) | ||
| 127 | try: | ||
| 128 | p = subprocess.Popen([sys.executable, "-I", "-B", str(Path(__file__).resolve()), "--shard"], | ||
| 129 | stdin=subprocess.PIPE, startupinfo=si, close_fds=True, creationflags=LOW) | ||
| 130 | finally: | ||
| 131 | os.set_handle_inheritable(lock, False) | ||
| 132 | attached = False | ||
| 133 | try: | ||
| 134 | check(assign(h, int(p._handle))) | ||
| 135 | attached = True | ||
| 136 | verify(h, int(p._handle), mib, True) | ||
| 137 | # A single framed gate. EOF, even after a short write, is not permission to start. | ||
| 138 | gate = (json.dumps([str(request), mib, lock])+"\n").encode("ascii") | ||
| 139 | if len(gate)>65536: | ||
| 140 | raise ValueError("compute worker gate too large") | ||
| 141 | p.stdin.write(gate) | ||
| 142 | p.stdin.close() | ||
| 143 | yield p | ||
| 144 | finally: | ||
| 145 | try: | ||
| 146 | if attached: | ||
| 147 | drain(h) # also stop/wait for a descendant if the Python worker died early | ||
| 148 | elif p.poll() is None: | ||
| 149 | p.kill() # gated bootstrap, no descendant or input path | ||
| 150 | finally: | ||
| 151 | try: | ||
| 152 | if not p.stdin.closed: | ||
| 153 | p.stdin.close() | ||
| 154 | finally: | ||
| 155 | p.wait(timeout=10) | ||
| 156 | |||
| 157 | |||
| 158 | def run(requests, mib, lock): | ||
| 159 | with contextlib.ExitStack() as stack: | ||
| 160 | procs = [stack.enter_context(start(p, mib, lock)) for p in requests] | ||
| 161 | while True: | ||
| 162 | codes = [p.poll() for p in procs] | ||
| 163 | if any(rc not in (None, 0) for rc in codes): | ||
| 164 | raise RuntimeError(f"Windows translation worker failed: {codes}") | ||
| 165 | if all(rc == 0 for rc in codes): | ||
| 166 | return | ||
| 167 | time.sleep(.05) | ||
| 168 | |||
| 169 | |||
| 170 | def child(): | ||
| 171 | line = sys.stdin.buffer.readline(65537) | ||
| 172 | if not line.endswith(b"\n") or len(line)>65536: | ||
| 173 | raise ValueError("no complete Windows compute gate") | ||
| 174 | request, mib, lock = json.loads(line) | ||
| 175 | # NULL queries this worker's immediate job. No job handle in a worker can keep it alive after | ||
| 176 | # coordinator death. No library/source inputs touched before membership and effective limits. | ||
| 177 | verify(None, current(), mib, True) | ||
| 178 | os.set_handle_inheritable(lock, False) | ||
| 179 | try: | ||
| 180 | sys.path.insert(0, str(Path(__file__).resolve().parent)) | ||
| 181 | from translate_pipeline_compute import run_request | ||
| 182 | run_request(Path(request)) | ||
| 183 | finally: | ||
| 184 | check(close(lock)) | ||
| 185 | |||
| 186 | |||
| 187 | if __name__ == "__main__": | ||
| 188 | if sys.argv[1:] != ["--shard"]: | ||
| 189 | raise SystemExit(2) | ||
| 190 | child() | ||
diff --git a/scripts/corpus_watch.py b/scripts/corpus_watch.py new file mode 100644 index 000000000..8d12ea69f --- /dev/null +++ b/scripts/corpus_watch.py | |||
| @@ -0,0 +1,195 @@ | |||
| 1 | #!/usr/bin/env python3 | ||
| 2 | """Counts-only corpus regression watch. | ||
| 3 | |||
| 4 | Runs `make_game.py --stages check,shaders` against your own copy, then records | ||
| 5 | COUNTS ONLY (carved / translated / spirv-val-validated, per stage) against the | ||
| 6 | checked-out commit. This is the same counting the progress dashboard uses, so | ||
| 7 | a drop between snapshots is a regression. | ||
| 8 | |||
| 9 | Nothing derived from game data is written to the results file: no shader names, | ||
| 10 | no carved file names, no paths into the game copy. Diagnostic logs stay local | ||
| 11 | and may contain paths; never publish them. | ||
| 12 | |||
| 13 | python3 -I scripts/corpus_watch.py --game <pkg> --work <work> --out <out> \ | ||
| 14 | --report <folder outside the repo> --results <counts.jsonl> --once | ||
| 15 | python3 -I scripts/corpus_watch.py ... --interval 6 --pull | ||
| 16 | |||
| 17 | Standard library only; all text writes name their line ending. | ||
| 18 | """ | ||
| 19 | import argparse | ||
| 20 | import json | ||
| 21 | import os | ||
| 22 | import shutil | ||
| 23 | import subprocess | ||
| 24 | import sys | ||
| 25 | import time | ||
| 26 | from datetime import datetime, timezone | ||
| 27 | |||
| 28 | # -I removes the script folder from sys.path, so add tools/ explicitly. | ||
| 29 | sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tools")) | ||
| 30 | from report_paths import same_report_path # noqa: E402 | ||
| 31 | |||
| 32 | MIN_FREE = 40 * 1024**3 | ||
| 33 | |||
| 34 | |||
| 35 | def corpus_counts(work): | ||
| 36 | """Return counts-only dict, or None when the shader stage produced no indexes. | ||
| 37 | |||
| 38 | Mirrors tools/progress_dashboard.py: entries in dxbc/index.json are carved; | ||
| 39 | entries in spirv/index.json without an 'error' key passed spirv-val. | ||
| 40 | """ | ||
| 41 | dxbc = os.path.join(work, "shaders", "dxbc", "index.json") | ||
| 42 | spirv_path = os.path.join(work, "shaders", "spirv", "index.json") | ||
| 43 | if not os.path.isfile(dxbc): | ||
| 44 | old_dxbc = os.path.join(work, "dxbc", "index.json") | ||
| 45 | if not os.path.isfile(old_dxbc): | ||
| 46 | return None | ||
| 47 | dxbc = old_dxbc | ||
| 48 | spirv_path = os.path.join(work, "spirv", "index.json") | ||
| 49 | |||
| 50 | with open(dxbc, encoding="utf-8") as f: | ||
| 51 | carved = json.load(f) | ||
| 52 | entries = carved if isinstance(carved, list) else list(carved.values()) | ||
| 53 | |||
| 54 | per_stage = {} | ||
| 55 | validated = 0 | ||
| 56 | spirv_entries = 0 | ||
| 57 | if os.path.isfile(spirv_path): | ||
| 58 | with open(spirv_path, encoding="utf-8") as f: | ||
| 59 | spirv = json.load(f) | ||
| 60 | spirv_entries = len(spirv) | ||
| 61 | for meta in spirv.values(): | ||
| 62 | if isinstance(meta, dict) and "error" not in meta: | ||
| 63 | stage = meta.get("stage") or "unknown" | ||
| 64 | per_stage.setdefault(stage, [0, 0])[1] += 1 | ||
| 65 | validated += 1 | ||
| 66 | for entry in entries: | ||
| 67 | stage = (entry.get("stage") if isinstance(entry, dict) else None) or "unknown" | ||
| 68 | per_stage.setdefault(stage, [0, 0])[0] += 1 | ||
| 69 | |||
| 70 | return {"carved": len(entries), "spirv_entries": spirv_entries, | ||
| 71 | "validated": validated, "per_stage": per_stage} | ||
| 72 | |||
| 73 | |||
| 74 | def outputs_collide(work, report, results, log): | ||
| 75 | """Refuse an output that names an input or another output.""" | ||
| 76 | outputs = [p for p in (report, results, log) if p] | ||
| 77 | for i, first in enumerate(outputs): | ||
| 78 | for second in outputs[i + 1:]: | ||
| 79 | if same_report_path(first, second): | ||
| 80 | return True | ||
| 81 | for out in outputs: | ||
| 82 | if same_report_path(out, work): | ||
| 83 | return True | ||
| 84 | return False | ||
| 85 | |||
| 86 | |||
| 87 | def main(): | ||
| 88 | ap = argparse.ArgumentParser(description=__doc__) | ||
| 89 | ap.add_argument("--game", required=True, help="your package folder") | ||
| 90 | ap.add_argument("--work", required=True, help="work folder (outside the repo)") | ||
| 91 | ap.add_argument("--out", required=True, help="built port folder (outside the repo)") | ||
| 92 | ap.add_argument("--report", required=True, help="progress dashboard folder (outside the repo)") | ||
| 93 | ap.add_argument("--results", required=True, help="counts-only JSONL file") | ||
| 94 | ap.add_argument("--log", help="local diagnostic log (may contain paths; never publish)") | ||
| 95 | ap.add_argument("--stages", default="check,shaders") | ||
| 96 | ap.add_argument("--interval", type=float, metavar="HOURS", default=0) | ||
| 97 | ap.add_argument("--once", action="store_true") | ||
| 98 | ap.add_argument("--pull", action="store_true", help="git pull --ff-only before each run") | ||
| 99 | ap.add_argument("--github", action="store_true", help="also refresh dashboard PR/CI panels") | ||
| 100 | ap.add_argument("--jobs", type=int) | ||
| 101 | a = ap.parse_args() | ||
| 102 | if not a.once and a.interval <= 0: | ||
| 103 | ap.error("use --once or --interval HOURS") | ||
| 104 | |||
| 105 | repo = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 106 | log_path = a.log | ||
| 107 | |||
| 108 | def log(msg): | ||
| 109 | line = f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {msg}" | ||
| 110 | print(line, flush=True) | ||
| 111 | if log_path: | ||
| 112 | with open(log_path, "a", encoding="utf-8", newline="\n") as f: | ||
| 113 | f.write(line + "\n") | ||
| 114 | |||
| 115 | if outputs_collide(a.work, a.report, a.results, log_path): | ||
| 116 | ap.error("an output names the work folder or another output") | ||
| 117 | |||
| 118 | for tool in ("llvm-mc", "spirv-val", "git"): | ||
| 119 | if not shutil.which(tool): | ||
| 120 | ap.error(f"missing tool: {tool}") | ||
| 121 | if not os.path.isdir(a.game): | ||
| 122 | ap.error("game folder not found") | ||
| 123 | probe = subprocess.run( | ||
| 124 | ["llvm-mc", "-triple=amdgcn-amd-amdhsa", "-mcpu=gfx1013", | ||
| 125 | "-filetype=obj", "-o", os.devnull], | ||
| 126 | input="s_nop 0\n", text=True, capture_output=True) | ||
| 127 | if probe.returncode != 0: | ||
| 128 | ap.error("llvm-mc cannot assemble gfx1013 (AMDGPU target missing)") | ||
| 129 | |||
| 130 | def run(cmd, timeout): | ||
| 131 | return subprocess.run(cmd, cwd=repo, text=True, stdout=subprocess.PIPE, | ||
| 132 | stderr=subprocess.STDOUT, timeout=timeout) | ||
| 133 | |||
| 134 | def run_once(): | ||
| 135 | if a.pull: | ||
| 136 | r = run(["git", "pull", "--ff-only"], 300) | ||
| 137 | if r.returncode != 0: | ||
| 138 | log("git pull failed:\n" + r.stdout[-2000:]) | ||
| 139 | return 1 | ||
| 140 | sha = run(["git", "rev-parse", "HEAD"], 60).stdout.strip() | ||
| 141 | log(f"commit {sha}") | ||
| 142 | for folder in (a.work, a.out, a.report): | ||
| 143 | os.makedirs(folder, exist_ok=True) | ||
| 144 | cmd = [sys.executable, "-I", "make_game.py", "--game", a.game, | ||
| 145 | "--work", a.work, "--out", a.out, "--stages", a.stages] | ||
| 146 | if a.jobs: | ||
| 147 | cmd += ["--jobs", str(a.jobs)] | ||
| 148 | log("running make_game.py (paths omitted from the local log)") | ||
| 149 | r = run(cmd, 6 * 3600) | ||
| 150 | if log_path: | ||
| 151 | with open(log_path, "a", encoding="utf-8", newline="\n") as f: | ||
| 152 | f.write(r.stdout + "\n") | ||
| 153 | log(f"make_game.py exit {r.returncode}") | ||
| 154 | |||
| 155 | counts = corpus_counts(a.work) | ||
| 156 | record = {"time": datetime.now(timezone.utc).isoformat(), "commit": sha, | ||
| 157 | "make_game_exit": r.returncode, "counts": counts} | ||
| 158 | with open(a.results, "a", encoding="utf-8", newline="\n") as f: | ||
| 159 | f.write(json.dumps(record, sort_keys=True) + "\n") | ||
| 160 | |||
| 161 | dash = [sys.executable, "-I", "tools/progress_dashboard.py", | ||
| 162 | "--work", a.work, "--out", a.report, "--run-tests"] | ||
| 163 | if a.github: | ||
| 164 | dash.append("--github") | ||
| 165 | d = run(dash, 900) | ||
| 166 | log(f"dashboard exit {d.returncode}") | ||
| 167 | |||
| 168 | if counts: | ||
| 169 | log(f"COUNTS carved={counts['carved']} spirv={counts['spirv_entries']} " | ||
| 170 | f"validated={counts['validated']}") | ||
| 171 | for stage, (nc, nv) in sorted(counts["per_stage"].items()): | ||
| 172 | log(f" {stage}: {nv}/{nc} validated") | ||
| 173 | with open(a.results, encoding="utf-8") as f: | ||
| 174 | previous = [json.loads(x) for x in f if x.strip()] | ||
| 175 | if len(previous) >= 2: | ||
| 176 | before = previous[-2].get("counts") or {} | ||
| 177 | log(f"DELTA validated {before.get('validated')} -> {counts['validated']}, " | ||
| 178 | f"carved {before.get('carved')} -> {counts['carved']}") | ||
| 179 | if counts["validated"] < before.get("validated", 0): | ||
| 180 | log("REGRESSION: validated count decreased") | ||
| 181 | else: | ||
| 182 | log("no corpus indexes produced") | ||
| 183 | log(f"counts-only record: {a.results}") | ||
| 184 | return 0 | ||
| 185 | |||
| 186 | rc = run_once() | ||
| 187 | if a.once or a.interval <= 0: | ||
| 188 | return rc | ||
| 189 | while True: | ||
| 190 | time.sleep(a.interval * 3600) | ||
| 191 | run_once() | ||
| 192 | |||
| 193 | |||
| 194 | if __name__ == "__main__": | ||
| 195 | sys.exit(main()) | ||
diff --git a/scripts/first_look.ps1 b/scripts/first_look.ps1 index 6fb7ca36b..f302d5701 100644 --- a/scripts/first_look.ps1 +++ b/scripts/first_look.ps1 | |||
| @@ -105,9 +105,19 @@ $dryRunExitCode = $LASTEXITCODE | |||
| 105 | $report = Get-Content -LiteralPath (Join-Path $out "$([IO.Path]::GetFileName($Exe)).json") -Raw | ConvertFrom-Json | 105 | $report = Get-Content -LiteralPath (Join-Path $out "$([IO.Path]::GetFileName($Exe)).json") -Raw | ConvertFrom-Json |
| 106 | $todo = $report.imports | Where-Object { $_.where -eq "shim" } | Sort-Object { -$_.functions.Count } | 106 | $todo = $report.imports | Where-Object { $_.where -eq "shim" } | Sort-Object { -$_.functions.Count } |
| 107 | $lines = foreach ($t in $todo) { "{0,-40} {1,5}" -f $t.dll, $t.functions.Count } | 107 | $lines = foreach ($t in $todo) { "{0,-40} {1,5}" -f $t.dll, $t.functions.Count } |
| 108 | # "unverified" only comes from a host that isn't Windows and has no Wine prefix (pe_inspect.py, classify_dll): most | ||
| 109 | # are system DLLs, but a console DLL the shims don't serve yet is among them, so they follow the list, marked. | ||
| 110 | $unverified = @($report.imports | Where-Object { $_.where -eq "unverified" } | Sort-Object { -$_.functions.Count }) | ||
| 111 | if ($unverified.Count -gt 0) { | ||
| 112 | $lines = @(foreach ($t in $todo) { "{0,-40} {1,5}" -f $t.dll, $t.functions.Count }) + | ||
| 113 | @(foreach ($t in $unverified) { "{0,-40} {1,5} system (unverified)" -f $t.dll, $t.functions.Count }) | ||
| 114 | } | ||
| 108 | Set-Content -LiteralPath (Join-Path $out "shim-todo.txt") -Value $lines | 115 | Set-Content -LiteralPath (Join-Path $out "shim-todo.txt") -Value $lines |
| 109 | Write-Host "`n== Shim to-do (DLL, function count)" | 116 | Write-Host "`n== Shim to-do (DLL, function count)" |
| 110 | $lines | 117 | $lines |
| 118 | if ($unverified.Count -gt 0) { | ||
| 119 | Write-Warning "$($unverified.Count) DLLs could not be checked against system DLLs (no Wine prefix): set WINEPREFIX and run again" | ||
| 120 | } | ||
| 111 | $enc = $report.sections | Where-Object { $_.looks_encrypted } | ForEach-Object { $_.name } | 121 | $enc = $report.sections | Where-Object { $_.looks_encrypted } | ForEach-Object { $_.name } |
| 112 | if ($enc) { Write-Warning "High-entropy sections (still encrypted or packed): $($enc -join ', ')" } | 122 | if ($enc) { Write-Warning "High-entropy sections (still encrypted or packed): $($enc -join ', ')" } |
| 113 | Write-Host "`nReports: $out" | 123 | Write-Host "`nReports: $out" |
diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index a9d18b6ea..f87290ec6 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py | |||
| @@ -1101,6 +1101,7 @@ def run_suite(a, work: str) -> int: | |||
| 1101 | elif name == "cs_tbuffer_store": | 1101 | elif name == "cs_tbuffer_store": |
| 1102 | # tbuffer_store_format_*: the instruction's format, words measured natively on a Radeon 680M (the .asm header) | 1102 | # tbuffer_store_format_*: the instruction's format, words measured natively on a Radeon 680M (the .asm header) |
| 1103 | problem = tbuffer_store_test(a.build, spirv_dir, cs_env) | 1103 | problem = tbuffer_store_test(a.build, spirv_dir, cs_env) |
| 1104 | results.append((name, not problem, problem or "128/128 dumped words exact")) | ||
| 1104 | elif name == "cs_fmt_d16_xyz": | 1105 | elif name == "cs_fmt_d16_xyz": |
| 1105 | # d16_xyz / d16_xy typed-buffer loads and d16_xyz stores (cs_fmt_d16_xyz.asm header) | 1106 | # d16_xyz / d16_xy typed-buffer loads and d16_xyz stores (cs_fmt_d16_xyz.asm header) |
| 1106 | problem = fmt_d16_xyz_test(a.build, spirv_dir, cs_env) | 1107 | problem = fmt_d16_xyz_test(a.build, spirv_dir, cs_env) |
| @@ -1210,8 +1211,8 @@ def run_suite(a, work: str) -> int: | |||
| 1210 | "cs_w64x_branch", "cs_w64x_ballot", "cs_w64x_wg128_branches", "cs_w64x_lds_raw", | 1211 | "cs_w64x_branch", "cs_w64x_ballot", "cs_w64x_wg128_branches", "cs_w64x_lds_raw", |
| 1211 | "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load", | 1212 | "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load", |
| 1212 | "cs_w64x_mask_reuse", "cs_w64x_mask_reuse2", "cs_w64x_chain_barrier", "cs_barrier_divergent", | 1213 | "cs_w64x_mask_reuse", "cs_w64x_mask_reuse2", "cs_w64x_chain_barrier", "cs_barrier_divergent", |
| 1213 | "cs_bpermute32", "cs_w64x_partial_scmp", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_barrier_early_end", | 1214 | "cs_bpermute32", "cs_w64x_partial_scmp", "cs_w64x_partial_swizzle", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_barrier_early_end", |
| 1214 | "cs_barrier_loop", "cs_w64x_andn2_exec", "cs_w64x_saveexec_b64", "cs_w64x_cmp_sdst", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_andn2_exec", | 1215 | "cs_barrier_loop", "cs_w64x_andn2_exec", "cs_w64x_saveexec_b64", "cs_w64x_cmp_sdst", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_w32_andn2_exec", |
| 1215 | "cs_mask_vgpr_exec", "cs_w32_exec_computed", "cs_w64_exec_computed"): | 1216 | "cs_mask_vgpr_exec", "cs_w32_exec_computed", "cs_w64_exec_computed"): |
| 1216 | cs_dump_wants = { | 1217 | cs_dump_wants = { |
| 1217 | "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800, 0x40FF8000, 0x3FF00000], | 1218 | "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800, 0x40FF8000, 0x3FF00000], |
| @@ -1250,6 +1251,12 @@ def run_suite(a, work: str) -> int: | |||
| 1250 | # ds_wrxchg*_rtn_b64, ds_or_rtn_b64, ds_min_f32, ds_max_rtn_f32 (cs_lds_xchg64_ext.asm header) | 1251 | # ds_wrxchg*_rtn_b64, ds_or_rtn_b64, ds_min_f32, ds_max_rtn_f32 (cs_lds_xchg64_ext.asm header) |
| 1251 | "cs_lds_xchg64_ext": [0x11110003, 0x33333333, 0xF00FF000, 0x04030201, | 1252 | "cs_lds_xchg64_ext": [0x11110003, 0x33333333, 0xF00FF000, 0x04030201, |
| 1252 | 0x40302010, 0x70500705, 0x3FC00000, 0x80000000], | 1253 | 0x40302010, 0x70500705, 0x3FC00000, 0x80000000], |
| 1254 | # ds_wrxchg2_rtn_b32's pair cases and ds_wrxchg2st64_rtn_b32 | ||
| 1255 | # (cs_w32_wrxchg2_ext.asm / cs_w32_wrxchg2st64.asm headers) | ||
| 1256 | "cs_w32_wrxchg2_ext": [0x77777777, 0x88880008, 0x99990009, 0xDEADBEEF, | ||
| 1257 | 0xAAAAAAAA, 0xBBBBBBBB, 0x12341234, 0x56785678], | ||
| 1258 | "cs_w32_wrxchg2st64": [0x33333333, 0x44444444, 0x55550005, 0x66660006, | ||
| 1259 | 0xB0B00084, 0xB0B00088, 0xB0B00140, 0xB0B002C0], | ||
| 1253 | # ds_mskor, ds_and/xor_b64, ds_add_rtn_f32, ds_inc/dec/rsub_u32 (cs_lds_atomics_ext.asm header) | 1260 | # ds_mskor, ds_and/xor_b64, ds_add_rtn_f32, ds_inc/dec/rsub_u32 (cs_lds_atomics_ext.asm header) |
| 1254 | "cs_lds_atomics_ext": [0xF0F11234, 0xAB34CD78, 0x12345678, 0xF0F00F0F, | 1261 | "cs_lds_atomics_ext": [0xF0F11234, 0xAB34CD78, 0x12345678, 0xF0F00F0F, |
| 1255 | 0xA5A55A5A, 0x00AA00AA, 0x7FB00000, 0xFE090700], | 1262 | 0xA5A55A5A, 0x00AA00AA, 0x7FB00000, 0xFE090700], |
| @@ -1296,6 +1303,7 @@ def run_suite(a, work: str) -> int: | |||
| 1296 | "cs_w64x_lds_war": [1032, 1063, 1000, 1031, 2032, 2063, 2000, 2031], | 1303 | "cs_w64x_lds_war": [1032, 1063, 1000, 1031, 2032, 2063, 2000, 2031], |
| 1297 | "cs_w64x_partial": [40, 40, 528, 0, 0, 532, 539, 524820], | 1304 | "cs_w64x_partial": [40, 40, 528, 0, 0, 532, 539, 524820], |
| 1298 | "cs_w64x_partial_scmp": [0, 1, 0, 1, 1, 1, 1, 0], # s_cmp mask, -1 in a partial wave | 1305 | "cs_w64x_partial_scmp": [0, 1, 0, 1, 1, 1, 1, 0], # s_cmp mask, -1 in a partial wave |
| 1306 | "cs_w64x_partial_swizzle": [508, 523, 0, 0, 528, 0, 531, 0], # swizzle from a missing lane: 0 | ||
| 1299 | "cs_w32_partial_scmp": [0, 1, 1, 0, 1, 1, 1, 1], # the same in a 20-thread wave32 | 1307 | "cs_w32_partial_scmp": [0, 1, 1, 0, 1, 1, 1, 1], # the same in a 20-thread wave32 |
| 1300 | # ds_permute_b32 in a 20-thread wave32: a never-launched source lane sends nothing (.asm header) | 1308 | # ds_permute_b32 in a 20-thread wave32: a never-launched source lane sends nothing (.asm header) |
| 1301 | "cs_w32_partial_permute": [0, 29, 127, 0, 1, 0, 134, 113], | 1309 | "cs_w32_partial_permute": [0, 29, 127, 0, 1, 0, 134, 113], |
| @@ -1331,21 +1339,23 @@ def run_suite(a, work: str) -> int: | |||
| 1331 | # as check.py does, where the device has none | 1339 | # as check.py does, where the device has none |
| 1332 | # (vk_compute_test exits 77) instead of reporting a failure. With LEONIDA_W64_EMULATE=1 they were | 1340 | # (vk_compute_test exits 77) instead of reporting a failure. With LEONIDA_W64_EMULATE=1 they were |
| 1333 | # translated with --wave64-emulate and run on any subgroup size. | 1341 | # translated with --wave64-emulate and run on any subgroup size. |
| 1334 | # cs_w64x_partial and cs_w64x_partial_scmp (40-thread groups) can't have full subgroups: they ask for | 1342 | # cs_w64x_partial, cs_w64x_partial_scmp and cs_w64x_partial_swizzle (40-thread groups) can't have full |
| 1335 | # size 64 without them. | 1343 | # subgroups: they ask for size 64 without them. With LEONIDA_W64_EMULATE=1 they ask for 32, the width the |
| 1344 | # emulation is for, as check.py's partial_wave_test does. RADV defaults compute to 64, and there | ||
| 1345 | # cs_w64x_partial_swizzle came out right even before its missing-lane reads were fixed; at 32 it did not. | ||
| 1336 | emulated = w64_emulated() | 1346 | emulated = w64_emulated() |
| 1337 | partial = name in ("cs_w64x_partial", "cs_w64x_partial_scmp") | 1347 | partial = name in ("cs_w64x_partial", "cs_w64x_partial_scmp", "cs_w64x_partial_swizzle") |
| 1338 | wave64 = name not in ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", | 1348 | wave64 = name not in ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", |
| 1339 | "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", | 1349 | "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", |
| 1340 | "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", | 1350 | "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", |
| 1341 | "cs_w32_lds_subdword", "cs_w32_lds_wide", | 1351 | "cs_w32_lds_subdword", "cs_w32_lds_wide", |
| 1342 | "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_w32_permlane_fi", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", | 1352 | "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_w32_permlane_fi", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", |
| 1343 | "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_exec_const", "cs_w32_mask_imm", "cs_mask_vgpr_exec", | 1353 | "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_exec_const", "cs_w32_mask_imm", "cs_mask_vgpr_exec", |
| 1344 | "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", | 1354 | "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", |
| 1345 | "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi", "cs_dpp_cmp", "cs_w32_andn2_exec", | 1355 | "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi", "cs_dpp_cmp", "cs_w32_andn2_exec", |
| 1346 | "cs_w32_exec_computed") and not emulated and not partial | 1356 | "cs_w32_exec_computed") and not emulated and not partial |
| 1347 | if partial and not emulated: | 1357 | if partial: |
| 1348 | cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="64") | 1358 | cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="32" if emulated else "64") |
| 1349 | if name in WAVE32_LANE_DUMPS: # 32 lanes even without index.json, as check.py requests (#774) | 1359 | if name in WAVE32_LANE_DUMPS: # 32 lanes even without index.json, as check.py requests (#774) |
| 1350 | cs_env = dict(os.environ, **WAVE32_LANE_ENV) | 1360 | cs_env = dict(os.environ, **WAVE32_LANE_ENV) |
| 1351 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"] + (["--require-wave64"] if wave64 else []), env=cs_env) | 1361 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"] + (["--require-wave64"] if wave64 else []), env=cs_env) |
| @@ -1367,7 +1377,7 @@ def run_suite(a, work: str) -> int: | |||
| 1367 | ok, detail = judge_cs_dump(rc, msg, want, wave64=wave64, partial=partial, emulated=emulated, | 1377 | ok, detail = judge_cs_dump(rc, msg, want, wave64=wave64, partial=partial, emulated=emulated, |
| 1368 | hexwords=name in ("cs_store", "cs_smem_soffset_imm", "cs_w32_lds_u8_d16", | 1378 | hexwords=name in ("cs_store", "cs_smem_soffset_imm", "cs_w32_lds_u8_d16", |
| 1369 | "cs_w32_lds_subdword", "cs_w32_lds_wide", | 1379 | "cs_w32_lds_subdword", "cs_w32_lds_wide", |
| 1370 | "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_signed_zero_nan")) | 1380 | "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_signed_zero_nan")) |
| 1371 | if ok and None in want: | 1381 | if ok and None in want: |
| 1372 | unjudged = ", ".join(str(i) for i, w in enumerate(want) if w is None) | 1382 | unjudged = ", ".join(str(i) for i, w in enumerate(want) if w is None) |
| 1373 | detail += f" (words {unjudged} not judged on this device: UNJUDGED_WORDS in check.py)" | 1383 | detail += f" (words {unjudged} not judged on this device: UNJUDGED_WORDS in check.py)" |
diff --git a/scripts/translate_pipeline_compute.py b/scripts/translate_pipeline_compute.py index 4e691110b..cb6e17768 100644 --- a/scripts/translate_pipeline_compute.py +++ b/scripts/translate_pipeline_compute.py | |||
| @@ -1,26 +1,70 @@ | |||
| 1 | """Build an interrupted or new pipeline compute pack from shader_library.py output (Linux). | 1 | """Build an interrupted or new pipeline compute pack from shader_library.py output (Linux or Windows). |
| 2 | 2 | ||
| 3 | Two translation processes, including the parent, each run at most one SPIRV-Tools process. | 3 | Up to two translation processes each run at most one SPIRV-Tools process. |
| 4 | Validated modules and their receipts survive interruption. The runtime index is published last. | 4 | Validated modules and their receipts survive interruption. The runtime index is published last. |
| 5 | """ | 5 | """ |
| 6 | import argparse | 6 | import argparse |
| 7 | import fcntl | 7 | import contextlib |
| 8 | from dataclasses import dataclass, asdict | ||
| 8 | import hashlib | 9 | import hashlib |
| 10 | import inspect | ||
| 9 | import json | 11 | import json |
| 10 | import os | 12 | import os |
| 11 | import resource | ||
| 12 | import shutil | 13 | import shutil |
| 13 | import sys | 14 | import sys |
| 14 | import tempfile | 15 | import tempfile |
| 15 | from pathlib import Path | 16 | from pathlib import Path |
| 16 | 17 | ||
| 17 | ROOT = Path(__file__).resolve().parents[1] | 18 | ROOT = Path(__file__).resolve().parents[1] |
| 18 | sys.path[:0] = [str(ROOT / "tools"), str(ROOT)] | 19 | sys.path[:0] = [str(ROOT / "tools"), str(ROOT), str(ROOT / "scripts")] |
| 19 | from make_game import file_sha256 as digest, translation_sources_digest | 20 | from make_game import file_sha256 as digest, translation_sources_digest |
| 20 | import rdna2spirv as translator | 21 | import rdna2spirv as translator |
| 21 | 22 | ||
| 22 | 23 | ||
| 24 | @dataclass(frozen=True) | ||
| 25 | class Options: | ||
| 26 | wave64_emulate: bool | ||
| 27 | loop_limit: int | ||
| 28 | descriptor_hash: str | ||
| 29 | compact_spirv: bool | ||
| 30 | |||
| 31 | def __post_init__(self): | ||
| 32 | if (type(self.wave64_emulate) is not bool or type(self.compact_spirv) is not bool or | ||
| 33 | type(self.loop_limit) is not int or not 0 <= self.loop_limit <= 0xffffffff or | ||
| 34 | self.descriptor_hash not in translator.DESCRIPTOR_HASHES): | ||
| 35 | raise ValueError("invalid compute options") | ||
| 36 | |||
| 37 | def apply(self): | ||
| 38 | translator.WAVE64_EMULATE = self.wave64_emulate | ||
| 39 | translator.LOOP_LIMIT = self.loop_limit | ||
| 40 | translator.DESCRIPTOR_HASH = self.descriptor_hash | ||
| 41 | |||
| 42 | |||
| 43 | def observed(compact): | ||
| 44 | return asdict(Options(translator.WAVE64_EMULATE, translator.LOOP_LIMIT, translator.DESCRIPTOR_HASH, compact)) | ||
| 45 | |||
| 46 | |||
| 47 | def recipe(options): | ||
| 48 | if options.compact_spirv and "compact" not in inspect.signature(translator.assemble_spirv).parameters: | ||
| 49 | raise ValueError("this translator does not implement --compact-spirv") | ||
| 50 | binaries = {} | ||
| 51 | for tool in ["spirv-as", "spirv-val"] + (["spirv-opt"] if options.compact_spirv else []): | ||
| 52 | binary = shutil.which(tool) | ||
| 53 | if not binary: | ||
| 54 | raise ValueError(tool + " is required") | ||
| 55 | binaries[tool] = digest(Path(binary)) | ||
| 56 | return {"sources": translation_sources_digest(), "builder": digest(Path(__file__)), | ||
| 57 | "windows_adapter": digest(Path(__file__).with_name("compute_workers_win.py")), | ||
| 58 | "tools": binaries, "options": asdict(options)} | ||
| 59 | |||
| 60 | |||
| 61 | def object_digest(value): | ||
| 62 | return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":")).encode()).hexdigest() | ||
| 63 | |||
| 64 | |||
| 23 | def build_one(src, out, name, settings, compact=False): | 65 | def build_one(src, out, name, settings, compact=False): |
| 66 | if observed(compact) != settings["options"]: | ||
| 67 | raise ValueError("translation options differ from cache recipe") | ||
| 24 | listing = src / "disasm" / (name + ".s") | 68 | listing = src / "disasm" / (name + ".s") |
| 25 | side = src / "fspx" / name | 69 | side = src / "fspx" / name |
| 26 | code, state = (Path(str(side) + suffix) for suffix in (".code", ".state")) | 70 | code, state = (Path(str(side) + suffix) for suffix in (".code", ".state")) |
| @@ -28,12 +72,13 @@ def build_one(src, out, name, settings, compact=False): | |||
| 28 | container = src / (name + ".dxbc") | 72 | container = src / (name + ".dxbc") |
| 29 | inputs = [settings, name, code_key, state_key, digest(listing), digest(Path(str(side) + ".json")), | 73 | inputs = [settings, name, code_key, state_key, digest(listing), digest(Path(str(side) + ".json")), |
| 30 | digest(container) if container.is_file() else None] | 74 | digest(container) if container.is_file() else None] |
| 31 | key = hashlib.sha256(json.dumps(inputs).encode()).hexdigest() | 75 | key = object_digest(inputs) |
| 32 | receipt = out / ".compute-cache" / (key + ".json") | 76 | receipt = out / ".compute-cache" / (key + ".json") |
| 33 | if receipt.exists(): | 77 | if receipt.exists(): |
| 34 | try: | 78 | try: |
| 35 | row = json.loads(receipt.read_text(encoding="utf-8")) | 79 | row = json.loads(receipt.read_text(encoding="utf-8")) |
| 36 | if (row["meta"]["fspx_code_sha256"], row["meta"]["fspx_state_sha256"]) == (code_key, state_key): | 80 | if row["options"] == settings["options"] and ( |
| 81 | row["meta"]["fspx_code_sha256"], row["meta"]["fspx_state_sha256"]) == (code_key, state_key): | ||
| 37 | module_hash = row["module"] | 82 | module_hash = row["module"] |
| 38 | if len(module_hash) == 64 and all(c in "0123456789abcdef" for c in module_hash): | 83 | if len(module_hash) == 64 and all(c in "0123456789abcdef" for c in module_hash): |
| 39 | if digest(out / (name + "_" + module_hash + ".spv")) == module_hash: | 84 | if digest(out / (name + "_" + module_hash + ".spv")) == module_hash: |
| @@ -45,7 +90,9 @@ def build_one(src, out, name, settings, compact=False): | |||
| 45 | with tempfile.TemporaryDirectory(dir=out / ".compute-cache") as tmp: | 90 | with tempfile.TemporaryDirectory(dir=out / ".compute-cache") as tmp: |
| 46 | sa, sv = Path(tmp) / "module.spvasm", Path(tmp) / "module.spv" | 91 | sa, sv = Path(tmp) / "module.spvasm", Path(tmp) / "module.spv" |
| 47 | sa.write_text(asm, encoding="utf-8", newline="\n") | 92 | sa.write_text(asm, encoding="utf-8", newline="\n") |
| 48 | result = translator.assemble_spirv(str(sa), str(sv), asm_text=asm, compact=compact) | 93 | # Older translators support ordinary assembly but do not accept the compact keyword. |
| 94 | # Explicit compact is gated by recipe() before either worker starts; never drop it. | ||
| 95 | result = translator.assemble_spirv(str(sa), str(sv), asm_text=asm, **({"compact": True} if compact else {})) | ||
| 49 | if result.returncode: | 96 | if result.returncode: |
| 50 | raise translator.Unsupported((result.stderr.splitlines() or ["SPIR-V tool failed"])[0]) | 97 | raise translator.Unsupported((result.stderr.splitlines() or ["SPIR-V tool failed"])[0]) |
| 51 | meta = translator.shader_meta(translator.translate.last_gen, asm, src_path=str(listing)) | 98 | meta = translator.shader_meta(translator.translate.last_gen, asm, src_path=str(listing)) |
| @@ -53,50 +100,97 @@ def build_one(src, out, name, settings, compact=False): | |||
| 53 | "cs", code_key, state_key): | 100 | "cs", code_key, state_key): |
| 54 | raise ValueError("compute stage or FSPX identity mismatch") | 101 | raise ValueError("compute stage or FSPX identity mismatch") |
| 55 | module_hash = digest(sv) | 102 | module_hash = digest(sv) |
| 56 | sv.replace(out / (name + "_" + module_hash + ".spv")) | 103 | translator.replace_retry(sv, out / (name + "_" + module_hash + ".spv")) |
| 57 | row = {"meta": meta, "module": module_hash} | 104 | row = {"meta": meta, "module": module_hash, "options": observed(compact)} |
| 58 | translator.write_index(str(receipt), row) | 105 | translator.write_index(str(receipt), row) |
| 59 | return row | 106 | return row |
| 60 | 107 | ||
| 61 | 108 | ||
| 62 | def build_part(src, out, names, settings, report, compact=False): | 109 | def build_part(src, out, names, settings, report, shard): |
| 110 | options = Options(**settings["options"]) | ||
| 111 | options.apply() # identically on the POSIX parent/fork child and a newly spawned Windows interpreter | ||
| 112 | if recipe(options) != settings or observed(options.compact_spirv) != settings["options"]: | ||
| 113 | raise RuntimeError("compute worker recipe differs from coordinator") | ||
| 63 | rows, failures = {}, {} | 114 | rows, failures = {}, {} |
| 64 | for number, name in enumerate(names, 1): | 115 | for number, name in enumerate(names, 1): |
| 65 | try: | 116 | try: |
| 66 | rows[name] = build_one(src, out, name, settings, compact) | 117 | rows[name] = build_one(src, out, name, settings, options.compact_spirv) |
| 67 | except (translator.Unsupported, MemoryError) as e: | 118 | except (translator.Unsupported, MemoryError) as e: |
| 68 | failures[name] = str(e) or type(e).__name__ | 119 | failures[name] = str(e) or type(e).__name__ |
| 69 | if number % 100 == 0 or number == len(names): | 120 | if number % 100 == 0 or number == len(names): |
| 70 | print(f"worker {os.getpid()}: {number}/{len(names)}, {len(failures)} failed", flush=True) | 121 | print(f"worker {os.getpid()}: {number}/{len(names)}, {len(failures)} failed", flush=True) |
| 71 | translator.write_index(str(report), {"rows": rows, "failures": failures}) | 122 | audit = {"shard": shard, "recipe_sha256": object_digest(settings), "names_sha256": object_digest(names), |
| 123 | "options": observed(options.compact_spirv), "accepted": len(rows), "failed": len(failures)} | ||
| 124 | translator.write_index(str(report), {"audit": audit, "rows": rows, "failures": failures}) | ||
| 125 | |||
| 126 | |||
| 127 | def run_request(path): | ||
| 128 | q = json.loads(path.read_text(encoding="utf-8")) | ||
| 129 | build_part(Path(q["src"]), Path(q["out"]), q["names"], q["settings"], Path(q["report"]), q["shard"]) | ||
| 72 | 130 | ||
| 73 | 131 | ||
| 74 | def build(src, out, names, settings, jobs, compact=False): | 132 | @contextlib.contextmanager |
| 133 | def output_lock(path): | ||
| 134 | if os.name == "nt": | ||
| 135 | import compute_workers_win as win | ||
| 136 | with win.output_lock(path) as lock: | ||
| 137 | yield lock | ||
| 138 | else: | ||
| 139 | import fcntl | ||
| 140 | with path.open("ab") as lock: | ||
| 141 | fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) | ||
| 142 | yield lock | ||
| 143 | |||
| 144 | |||
| 145 | def run_parts(src, out, names, settings, jobs, reports, mib, lock): | ||
| 146 | if os.name == "nt": | ||
| 147 | import compute_workers_win as win | ||
| 148 | requests = [] | ||
| 149 | for i, report in enumerate(reports): | ||
| 150 | request = report.with_suffix(".request") | ||
| 151 | translator.write_index(str(request), {"src": str(src), "out": str(out), "names": names[i::jobs], | ||
| 152 | "settings": settings, "report": str(report), "shard": i}) | ||
| 153 | requests.append(request) | ||
| 154 | win.run(requests, mib, lock) | ||
| 155 | return | ||
| 156 | pid = os.fork() if jobs == 2 else None | ||
| 157 | if pid == 0: | ||
| 158 | try: | ||
| 159 | build_part(src, out, names[1::2], settings, reports[1], 1) | ||
| 160 | except BaseException: | ||
| 161 | import traceback | ||
| 162 | traceback.print_exc() | ||
| 163 | os._exit(1) | ||
| 164 | os._exit(0) | ||
| 165 | try: | ||
| 166 | build_part(src, out, names[::jobs], settings, reports[0], 0) | ||
| 167 | finally: | ||
| 168 | if pid and os.waitpid(pid, 0)[1]: | ||
| 169 | raise RuntimeError("second translation worker failed") | ||
| 170 | |||
| 171 | |||
| 172 | def build(src, out, names, settings, jobs, mib): | ||
| 75 | cache = out / ".compute-cache" | 173 | cache = out / ".compute-cache" |
| 76 | cache.mkdir(exist_ok=True) | 174 | cache.mkdir(exist_ok=True) |
| 77 | with (cache / "lock").open("ab") as lock, tempfile.TemporaryDirectory(dir=cache) as tmp: | 175 | with output_lock(cache / "lock") as lock, tempfile.TemporaryDirectory(dir=cache) as tmp: |
| 78 | fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) | ||
| 79 | reports = [Path(tmp) / str(i) for i in range(jobs)] | 176 | reports = [Path(tmp) / str(i) for i in range(jobs)] |
| 80 | pid = os.fork() if jobs == 2 else None | 177 | run_parts(src, out, names, settings, jobs, reports, mib, lock) |
| 81 | if pid == 0: | ||
| 82 | try: | ||
| 83 | build_part(src, out, names[1::2], settings, reports[1], compact) | ||
| 84 | except BaseException: | ||
| 85 | import traceback | ||
| 86 | traceback.print_exc() | ||
| 87 | os._exit(1) | ||
| 88 | os._exit(0) | ||
| 89 | try: | ||
| 90 | build_part(src, out, names[::jobs], settings, reports[0], compact) | ||
| 91 | finally: | ||
| 92 | if pid and os.waitpid(pid, 0)[1]: | ||
| 93 | raise RuntimeError("second translation worker failed") | ||
| 94 | 178 | ||
| 95 | index, failures, pairs = {}, {}, {} | 179 | index, failures, pairs = {}, {}, {} |
| 96 | for report in reports: | 180 | audits = [] |
| 181 | for i, report in enumerate(reports): | ||
| 97 | part = json.loads(report.read_text(encoding="utf-8")) | 182 | part = json.loads(report.read_text(encoding="utf-8")) |
| 183 | accepted, failed = set(part["rows"]), set(part["failures"]) | ||
| 184 | expected = names[i::jobs] | ||
| 185 | audit = {"shard": i, "recipe_sha256": object_digest(settings), "names_sha256": object_digest(expected), | ||
| 186 | "options": settings["options"], "accepted": len(accepted), "failed": len(failed)} | ||
| 187 | if part["audit"] != audit or accepted & failed or accepted | failed != set(expected): | ||
| 188 | raise ValueError("compute shard options or coverage mismatch") | ||
| 189 | audits.append(audit) | ||
| 98 | failures.update(part["failures"]) | 190 | failures.update(part["failures"]) |
| 99 | for name, row in part["rows"].items(): | 191 | for name, row in part["rows"].items(): |
| 192 | if row["options"] != settings["options"]: | ||
| 193 | raise ValueError("cached compute row options mismatch") | ||
| 100 | module, meta = row["module"], row["meta"] | 194 | module, meta = row["module"], row["meta"] |
| 101 | pair = meta["fspx_code_sha256"], meta["fspx_state_sha256"] | 195 | pair = meta["fspx_code_sha256"], meta["fspx_state_sha256"] |
| 102 | if pairs.setdefault(pair, module) != module: | 196 | if pairs.setdefault(pair, module) != module: |
| @@ -110,7 +204,13 @@ def build(src, out, names, settings, jobs, compact=False): | |||
| 110 | state = digest(src / "fspx" / (name + ".state")) | 204 | state = digest(src / "fspx" / (name + ".state")) |
| 111 | by_hash.setdefault(code, {})[state] = reason | 205 | by_hash.setdefault(code, {})[state] = reason |
| 112 | translator.write_index(str(out / "failures.json"), by_hash) | 206 | translator.write_index(str(out / "failures.json"), by_hash) |
| 113 | translator.write_index(str(out / "index.json"), index) | 207 | # An audit, not a publication marker. Associate it with the actual index bytes after commit. |
| 208 | candidate = Path(tmp)/"final-index.json" | ||
| 209 | translator.write_index(str(candidate), index) | ||
| 210 | index_hash = digest(candidate) | ||
| 211 | translator.write_index(str(cache / "worker-receipt.json"), | ||
| 212 | {"schema": 1, "recipe": settings, "index_sha256": index_hash, "shards": audits}) | ||
| 213 | translator.replace_retry(candidate, out / "index.json") | ||
| 114 | print(f"{len(index)}/{len(names)} valid, {len(failures)} failed") | 214 | print(f"{len(index)}/{len(names)} valid, {len(failures)} failed") |
| 115 | return int(bool(failures)) | 215 | return int(bool(failures)) |
| 116 | 216 | ||
| @@ -120,7 +220,8 @@ def main(): | |||
| 120 | ap.add_argument("inputs", type=Path, help="unpacked library with index.json, disasm/ and fspx/") | 220 | ap.add_argument("inputs", type=Path, help="unpacked library with index.json, disasm/ and fspx/") |
| 121 | ap.add_argument("--out", type=Path, required=True, help="dedicated runtime library subdirectory") | 221 | ap.add_argument("--out", type=Path, required=True, help="dedicated runtime library subdirectory") |
| 122 | ap.add_argument("--jobs", type=int, choices=(1, 2), default=2) | 222 | ap.add_argument("--jobs", type=int, choices=(1, 2), default=2) |
| 123 | ap.add_argument("--memory-mib", type=int, default=768, help="virtual memory per process (default 768 MiB)") | 223 | ap.add_argument("--memory-mib", type=int, default=768, |
| 224 | help="per-process limit: virtual space (Linux) or committed memory (Windows); default 768 MiB") | ||
| 124 | ap.add_argument("--descriptor-hash", choices=translator.DESCRIPTOR_HASHES, default="fnv1a", | 225 | ap.add_argument("--descriptor-hash", choices=translator.DESCRIPTOR_HASHES, default="fnv1a", |
| 125 | help="bindless descriptor table hash shared with the runtime") | 226 | help="bindless descriptor table hash shared with the runtime") |
| 126 | ap.add_argument("--loop-limit", type=translator.spirv_loop_guard.parse_limit, | 227 | ap.add_argument("--loop-limit", type=translator.spirv_loop_guard.parse_limit, |
| @@ -133,21 +234,21 @@ def main(): | |||
| 133 | src, out = args.inputs.resolve(), args.out.resolve() | 234 | src, out = args.inputs.resolve(), args.out.resolve() |
| 134 | if out == src or src in out.parents or out in src.parents: | 235 | if out == src or src in out.parents or out in src.parents: |
| 135 | ap.error("input and output directories must be separate") | 236 | ap.error("input and output directories must be separate") |
| 136 | os.setpriority(os.PRIO_PROCESS, 0, 19) | 237 | if os.name == "nt": |
| 137 | soft, hard = resource.getrlimit(resource.RLIMIT_AS) | 238 | import compute_workers_win as win |
| 138 | bound = min(n for n in (args.memory_mib << 20, soft, hard) if n != resource.RLIM_INFINITY) | 239 | win.budget_coordinator(args.memory_mib) |
| 139 | resource.setrlimit(resource.RLIMIT_AS, (bound, hard)) | 240 | else: |
| 140 | versions = [] | 241 | import resource |
| 141 | required_tools = ["spirv-as", "spirv-val"] | 242 | os.setpriority(os.PRIO_PROCESS, 0, 19) |
| 142 | if args.compact_spirv: | 243 | soft, hard = resource.getrlimit(resource.RLIMIT_AS) |
| 143 | required_tools.append("spirv-opt") | 244 | bound = min(n for n in (args.memory_mib << 20, soft, hard) if n != resource.RLIM_INFINITY) |
| 144 | for tool in required_tools: | 245 | resource.setrlimit(resource.RLIMIT_AS, (bound, hard)) |
| 145 | binary = shutil.which(tool) | 246 | options = Options(args.wave64_emulate, args.loop_limit, args.descriptor_hash, args.compact_spirv) |
| 146 | if not binary: | 247 | options.apply() |
| 147 | ap.error(tool + " is required") | 248 | try: |
| 148 | versions.append(digest(Path(binary))) | 249 | settings = recipe(options) |
| 149 | settings = [translation_sources_digest(), digest(Path(__file__)), versions, args.wave64_emulate, | 250 | except ValueError as e: |
| 150 | args.loop_limit, args.descriptor_hash] | 251 | ap.error(str(e)) |
| 151 | rows = json.loads((src / "index.json").read_text(encoding="utf-8")) | 252 | rows = json.loads((src / "index.json").read_text(encoding="utf-8")) |
| 152 | names = [] | 253 | names = [] |
| 153 | for row in rows: | 254 | for row in rows: |
| @@ -156,14 +257,15 @@ def main(): | |||
| 156 | filename = row["file"] | 257 | filename = row["file"] |
| 157 | if Path(filename).name != filename or not filename.endswith(".dxbc") or "\\" in filename: | 258 | if Path(filename).name != filename or not filename.endswith(".dxbc") or "\\" in filename: |
| 158 | ap.error("invalid compute filename in input index") | 259 | ap.error("invalid compute filename in input index") |
| 260 | if os.name == "nt" and (any(ord(c)<32 or c in '<>:"|?*' for c in filename) or | ||
| 261 | (os.path.isreserved(filename) if hasattr(os.path, "isreserved") | ||
| 262 | else Path(filename).is_reserved())): | ||
| 263 | ap.error("invalid Windows compute filename in input index") | ||
| 159 | names.append(filename[:-5]) | 264 | names.append(filename[:-5]) |
| 160 | if not names or len(set(names)) != len(names): | 265 | if not names or len({os.path.normcase(n) for n in names}) != len(names): |
| 161 | ap.error("expected unique compute filenames in the input index") | 266 | ap.error("expected unique compute filenames in the input index") |
| 162 | out.mkdir(parents=True, exist_ok=True) | 267 | out.mkdir(parents=True, exist_ok=True) |
| 163 | translator.DESCRIPTOR_HASH = args.descriptor_hash | 268 | return build(src, out, sorted(names), settings, args.jobs, args.memory_mib) |
| 164 | translator.LOOP_LIMIT = args.loop_limit | ||
| 165 | translator.WAVE64_EMULATE = args.wave64_emulate | ||
| 166 | return build(src, out, sorted(names), settings, args.jobs, args.compact_spirv) | ||
| 167 | 269 | ||
| 168 | 270 | ||
| 169 | if __name__ == "__main__": | 271 | if __name__ == "__main__": |
diff --git a/scripts/vs_layout_census.py b/scripts/vs_layout_census.py index 249a9c74e..1d7174e77 100644 --- a/scripts/vs_layout_census.py +++ b/scripts/vs_layout_census.py | |||
| @@ -31,6 +31,7 @@ sys.path.insert(0, os.path.join(ROOT, "scripts")) | |||
| 31 | import fssm_unpack # noqa: E402 | 31 | import fssm_unpack # noqa: E402 |
| 32 | import pal_stages # noqa: E402 | 32 | import pal_stages # noqa: E402 |
| 33 | import shader_disasm # noqa: E402 | 33 | import shader_disasm # noqa: E402 |
| 34 | from report_paths import same_report_path # noqa: E402 | ||
| 34 | import shader_ir # noqa: E402 | 35 | import shader_ir # noqa: E402 |
| 35 | from vs_input_survey import (FETCH_CALL, MBCNT, PARAM_EXPORT, POS0_EXPORT, PRIM_EXPORT, SENDMSG, # noqa: E402 | 36 | from vs_input_survey import (FETCH_CALL, MBCNT, PARAM_EXPORT, POS0_EXPORT, PRIM_EXPORT, SENDMSG, # noqa: E402 |
| 36 | read_before_write) | 37 | read_before_write) |
| @@ -87,10 +88,9 @@ def payloads_of(dxbc_path): | |||
| 87 | for i, blob in enumerate(blobs)] | 88 | for i, blob in enumerate(blobs)] |
| 88 | 89 | ||
| 89 | 90 | ||
| 90 | def survey(dxbc_dir, disasm_fn=None, limit=None): | 91 | def load_index(dxbc_dir): |
| 91 | """The census over <dxbc>: counts by stage, hardware id, markers and VS entry VGPRs.""" | 92 | """(stage by stem, stems in index order) from <dxbc>/index.json.""" |
| 92 | index_path = os.path.join(dxbc_dir, "index.json") | 93 | with open(os.path.join(dxbc_dir, "index.json"), encoding="utf-8") as f: |
| 93 | with open(index_path, encoding="utf-8") as f: | ||
| 94 | index = json.load(f) | 94 | index = json.load(f) |
| 95 | if not isinstance(index, list) or not all(isinstance(e, dict) for e in index): | 95 | if not isinstance(index, list) or not all(isinstance(e, dict) for e in index): |
| 96 | raise ValueError("index.json is not a list of shader entries") | 96 | raise ValueError("index.json is not a list of shader entries") |
| @@ -102,6 +102,26 @@ def survey(dxbc_dir, disasm_fn=None, limit=None): | |||
| 102 | if stem not in stages: | 102 | if stem not in stages: |
| 103 | names.append(stem) | 103 | names.append(stem) |
| 104 | stages[stem] = e.get("stage") | 104 | stages[stem] = e.get("stage") |
| 105 | return stages, names | ||
| 106 | |||
| 107 | |||
| 108 | def input_paths(dxbc_dir): | ||
| 109 | """Every file the census may read: index.json, then each indexed container and its disasm/<stem>.s listing. | ||
| 110 | An index that cannot be read names no more; survey() reports it.""" | ||
| 111 | paths = [os.path.join(dxbc_dir, "index.json")] | ||
| 112 | try: | ||
| 113 | _stages, names = load_index(dxbc_dir) | ||
| 114 | except (OSError, ValueError): | ||
| 115 | return paths | ||
| 116 | for name in names: | ||
| 117 | paths.append(os.path.join(dxbc_dir, name + ".dxbc")) | ||
| 118 | paths.append(os.path.join(dxbc_dir, "disasm", name + ".s")) | ||
| 119 | return paths | ||
| 120 | |||
| 121 | |||
| 122 | def survey(dxbc_dir, disasm_fn=None, limit=None): | ||
| 123 | """The census over <dxbc>: counts by stage, hardware id, markers and VS entry VGPRs.""" | ||
| 124 | stages, names = load_index(dxbc_dir) | ||
| 105 | if limit is not None: | 125 | if limit is not None: |
| 106 | names = names[:limit] | 126 | names = names[:limit] |
| 107 | 127 | ||
| @@ -186,9 +206,15 @@ def main(argv=None): | |||
| 186 | ap.add_argument("--limit", type=int, help="stop after this many containers (index order)") | 206 | ap.add_argument("--limit", type=int, help="stop after this many containers (index order)") |
| 187 | a = ap.parse_args(argv) | 207 | a = ap.parse_args(argv) |
| 188 | index_path = os.path.join(a.dxbc, "index.json") | 208 | index_path = os.path.join(a.dxbc, "index.json") |
| 189 | if a.json and os.path.exists(a.json) and os.path.exists(index_path) and os.path.samefile(a.json, index_path): | 209 | if a.json: |
| 190 | print(f"vs_layout_census: error: --json would overwrite the input {index_path}", file=sys.stderr) | 210 | # Refuse before survey(): it reads the whole corpus and runs llvm-mc for every unlisted payload. |
| 191 | return 2 | 211 | if os.path.isdir(a.json): |
| 212 | print(f"vs_layout_census: error: --json {a.json} is a directory, not a JSON file", file=sys.stderr) | ||
| 213 | return 2 | ||
| 214 | for path in input_paths(a.dxbc): | ||
| 215 | if same_report_path(a.json, path): | ||
| 216 | print(f"vs_layout_census: error: --json would overwrite the input {path}", file=sys.stderr) | ||
| 217 | return 2 | ||
| 192 | try: | 218 | try: |
| 193 | r = survey(a.dxbc, disasm_fn=default_disasm, limit=a.limit) | 219 | r = survey(a.dxbc, disasm_fn=default_disasm, limit=a.limit) |
| 194 | except (OSError, ValueError) as e: | 220 | except (OSError, ValueError) as e: |