diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 0ff733113..68699f779 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -190,6 +190,7 @@ jobs: tests/startup_host_cpu_check.py \ tests/startup_gfx2hlsl_cvt_alu_check.py \ tests/startup_gfx2hlsl_capture_check.py \ + tests/startup_gfx2hlsl_watch_check.py \ tests/startup_translator_check.py \ tests/startup_gfx2hlsl_smem_offset_check.py \ tests/startup_gfx2hlsl_scalar_m0_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 66e72acb3..6eb3f7937 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -152,6 +152,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_image_2d_array_check.py ./out/pe-env/bin/python -B tests/startup_host_cpu_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_capture_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_watch_check.py ./out/pe-env/bin/python -B tests/startup_translator_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_smem_offset_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_m0_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index c16091ee4..ece5a4435 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2032,6 +2032,10 @@ if(EXISTS "${INTAKE_PYTHON}") # gfx2hlsl refuses a binary32 or integer vector operation with a source too few or too many. add_test(NAME startup_gfx2hlsl_operand_count COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_operand_count_check.py") + # gfx2hlsl.py --watch consumes only ready requests and does not retry an unchanged failure. + add_test(NAME startup_gfx2hlsl_watch COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_watch_check.py") + set_tests_properties(startup_gfx2hlsl_watch PROPERTIES TIMEOUT 120) # VOP1/VOP2 sub-dword addressing (SDWA) in the translator (#1141), checked against the pixel AOT # lowering of the same selections. add_test(NAME startup_gfx2hlsl_sdwa COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 2d2a8b237..179638d6b 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -395,7 +395,7 @@ Then: ```powershell .\tools\startup\run.ps1 -Exe \.exe -DataDir <package root> -LogDir out\startup\run1 ` - -Seconds 180 -Render -FakeUser -GpuMirror -ContinueAsserts 1000 -InputScript "4@70" + -Seconds 180 -Render -Translate -FakeUser -GpuMirror -ContinueAsserts 1000 -InputScript "4@70" ``` `run.ps1` copies the stand-ins next to the executable and starts `tools/startup/debug_launch.py`. @@ -437,6 +437,36 @@ It writes: | `<log>/events.txt` | module loads and every exception with its time | | `<log>/stderr.txt` | the stand-ins' logs (`x2w-d3d12`, `x2w-dstorage`, `x2w-xmem`, `x2w-runtime`, ...) | | `<log>/files.txt` | every file the process opened | +| `<log>/translate.txt` | with `-Translate`: one line per shader request translated during the run | + +### Translating shaders during a run + +With `-Render -Translate`, `run.ps1` starts `tools/startup/gfx2hlsl.py --watch <shader cache>` beside +the debugger and stops it, with its worker processes, when the debugger returns (`-Translate` +without `-Render` is ignored with a warning). The watcher repeats the `--pending` scan every +2 seconds (`--watch <dir> <seconds>` sets another interval), so a pipeline the title creates during +the run is translated within seconds, and the runtime picks it up on a later draw instead of on the +next run. The cache persists: a later run reads every published `<key>.txt` and translates only new +requests. The watcher's first pass retries every earlier failure once, so a translator update reaches +requests that failed in an earlier run; after that, a request whose `<key>.fail` is newer than its +ready marker is not retried during the run (the runtime writes each request once and never rewrites +it). The one-shot `--pending` scan retries every failure. An unexpected translator error is written +to `<key>.fail` as `translator error: ...` instead of stopping the scan. A worker killed from outside +(for example out of memory) ends that watcher pass only; its requests are retried on the next pass. +FXC is located as described for `X2W_SHADER_CACHE` under [Switches](#switches). A scan with more than +one pending request translates them in parallel processes, one per logical processor (at most 61 on +Windows, the `ProcessPoolExecutor` limit) unless `X2W_TRANSLATE_JOBS` sets the count; each request +writes only its own files. On a 16-thread host, +3,513 requests (132 translated, 3,381 refused) took 56.9 s with one process and 7.8 s in parallel, +with byte-identical results. + +Check with `python3 -B tests/startup_gfx2hlsl_watch_check.py` (ctest `startup_gfx2hlsl_watch`): a +request without its ready marker is not consumed, the watcher retries an earlier failure once and +then leaves failures alone, it translates a request written while it runs, four parallel workers +print the same results and write the same failures as one, an unexpected translator error becomes +`<key>.fail`, and an invalid `X2W_TRANSLATE_JOBS` falls back to the processor count. +`startup_run_ps1` checks that `-Translate` starts the watcher on the cache and stops it together +with a child process. `run.ps1` prints the first five lines of `<log>.out` and exits with the debugger's exit code: 2 when the process could not be created, 0 when the debugger finished its report, whatever the process @@ -599,7 +629,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_XMEM_GPU_MIRROR=1` | pairs a no-access graphics reservation with the read-write reservation of the same size made just before it, and maps every physical page into both (same section) | | `X2W_D3D12_PERMISSIVE=1` | wraps the device: recording command lists, console present, view tracking | | `X2W_D3D12_RENDER=1` | draws through translated pipelines from `X2W_SHADER_CACHE` and forwards [single-record indirect Dispatch](experiments.md#gpu-written-indirect-dispatch-arguments), [DrawIndexed](experiments.md#gpu-written-indirect-indexed-draw-arguments), [Draw](experiments.md#gpu-written-indirect-draw-arguments), and [DispatchMesh](experiments.md#gpu-written-indirect-mesh-dispatch-arguments) for supported desktop pipelines and tracked placed buffers | -| `X2W_SHADER_CACHE=<dir>` | translation cache: the runtime writes source requests `req_<key>.{a,b,root}` and, when needed, RTV variants `req_<key>.rtv`. Run `tools/startup/gfx2hlsl.py --pending <dir>` while the process is running. Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\<version>\x64`, else `PATH`. When none exists it writes `<key>.fail` naming `X2W_FXC` and no manifest; `X2W_FXC=` (empty) skips compilation and publishes the manifest alone. | +| `X2W_SHADER_CACHE=<dir>` | translation cache: the runtime writes source requests `req_<key>.{a,b,root}` and, when needed, RTV variants `req_<key>.rtv`. Run `tools/startup/gfx2hlsl.py --pending <dir>` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\<version>\x64`, else `PATH`. When none exists it writes `<key>.fail` naming `X2W_FXC` and no manifest; `X2W_FXC=` (empty) skips compilation and publishes the manifest alone. | | `X2W_DRAW_NULL_IDENTITY=1` | null descriptors read as identity values instead of zero | | `X2W_D3D12_DUMP_SURFACE=<bmp>` | writes the last presented surface | | `X2W_DRAW_DUMP_FRAME=<n>`, `X2W_DRAW_DUMP_DIR` | Full-resolution RGB snapshots of single-sample RGBA8/BGRA8 UNORM or sRGB targets after translated draws. A later present writes completed queue-fenced copies. At most 48 copies are pending or written; a copy whose fence reports device removal (`UINT64_MAX`) is released unwritten and frees its slot (`src/startup_stubs/draw_dump_tracking.h`, `ctest --preset dev --no-tests=error -R '^startup_dump_fence_(removed_control_)?warp$' -V`; the control must fail). | diff --git a/tests/startup_gfx2hlsl_watch_check.py b/tests/startup_gfx2hlsl_watch_check.py new file mode 100644 index 000000000..2aea5a772 --- /dev/null +++ b/tests/startup_gfx2hlsl_watch_check.py @@ -0,0 +1,171 @@ +"""gfx2hlsl.py pending scan and --watch on synthetic request files (pure Python, no Windows, no GPU). + +A request is consumed only once its ready marker (.a or .rtv) exists and it has no published .txt. +After the watcher's first pass, a request whose .fail is newer than its marker is not retried; the +first pass and the one-shot --pending scan retry it. The --watch process must retry an earlier +failure once, translate a new request while it runs and not rewrite a failure on later passes. A +--pending scan with four parallel workers must print the same results and write the same failures +as one worker, an unexpected translator error must become <key>.fail, a broken process pool must +end one watcher pass and not the watcher, and an invalid X2W_TRANSLATE_JOBS must fall back to the +processor count. +""" +import os +import re +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / 'tools' / 'startup')) +import gfx2hlsl # noqa: E402 + +failures = [] + + +def expect(label, got, want): + if got != want: + failures.append('%s: got %s, want %s' % (label, got, want)) + + +def touch(path, data=b'', mtime=None): + path.write_bytes(data) + if mtime is not None: + os.utime(path, (mtime, mtime)) + + +def scan(directory, skip_failed): + return gfx2hlsl.pending_keys(str(directory), skip_failed) + + +def pending_run(directory, jobs): + env = dict(os.environ, X2W_TRANSLATE_JOBS=str(jobs)) + out = subprocess.run([sys.executable, '-B', str(ROOT / 'tools' / 'startup' / 'gfx2hlsl.py'), '--pending', str(directory)], + capture_output=True, text=True, timeout=120, env=env) + def local(text): # the temporary directory differs between runs; keep the file name only + return re.sub(r"'[^']*?(req_[0-9a-f]{16}\.\w+)'", r"'\1'", text) + fails = {p.name: local(p.read_text()) for p in Path(directory).glob('*.fail')} + return out.returncode, sorted(local(line) for line in out.stdout.splitlines()), fails + + +with tempfile.TemporaryDirectory() as tmp: + d = Path(tmp) + now = time.time() + # 1: complete request; 2: already published; 3: no ready marker yet (negative control); + # 4: failed after its marker was written; 5: marker rewritten after the failure; 6: RTV variant. + for key in (1, 2, 4, 5): + for ext in ('.b', '.root'): + touch(d / ('req_%016x%s' % (key, ext))) + touch(d / ('req_%016x.a' % 1)) + touch(d / ('req_%016x.a' % 2)) + touch(d / ('%016x.txt' % 2)) + touch(d / ('req_%016x.b' % 3)) + touch(d / ('req_%016x.root' % 3)) + touch(d / ('req_%016x.a' % 4), mtime=now - 10) + touch(d / ('%016x.fail' % 4), mtime=now - 5) + touch(d / ('%016x.fail' % 5), mtime=now - 10) + touch(d / ('req_%016x.a' % 5), mtime=now - 5) + touch(d / ('req_%016x.rtv' % 6)) + expect('watch pass', scan(d, True), [1, 5, 6]) + expect('one-shot pass', scan(d, False), [1, 4, 5, 6]) + +# Parallel --pending must give the same results as one worker. Sixteen RTV variants each name a +# different missing base request, so each failure names its own base and a result reported against +# the wrong key is visible. With four workers each batch holds one request. +bases = {} +with tempfile.TemporaryDirectory() as one, tempfile.TemporaryDirectory() as many: + for n in range(16): + request = b'rtv1 %d 28' % (0x7000 + n) + bases[gfx2hlsl.fnv(request)] = 0x7000 + n + for d in (one, many): + touch(Path(d) / ('req_%016x.rtv' % gfx2hlsl.fnv(request)), request) + serial, parallel = pending_run(one, 1), pending_run(many, 4) + expect('parallel --pending output and failures', parallel, serial) + expect('every request answered', len(serial[1]), 16) + for line in parallel[1]: + key = int(line[:16], 16) + expect('result for %016x names its own base' % key, 'req_%016x.a' % bases.get(key, -1) in line, True) + +# An unexpected translator error becomes <key>.fail instead of ending the scan. +with tempfile.TemporaryDirectory() as tmp: + d = Path(tmp) + touch(d / ('req_%016x.rtv' % 9)) + real = gfx2hlsl.translate_request + gfx2hlsl.translate_request = lambda out_dir, key: 1 / 0 + try: + gfx2hlsl.translate_pending(str(d), jobs=1) + except ZeroDivisionError: + failures.append('a translator error escaped translate_pending') + finally: + gfx2hlsl.translate_request = real + fail = d / ('%016x.fail' % 9) + expect('translator error recorded', fail.read_text().startswith('translator error: ZeroDivisionError') if fail.exists() else None, True) + +# A broken process pool (a worker killed from outside) ends one pass, not the watcher. +from concurrent.futures.process import BrokenProcessPool # noqa: E402 + + +def broken(out_dir, skip_failed=False): + raise BrokenProcessPool('a worker was terminated abruptly') + + +real = gfx2hlsl.translate_pending +gfx2hlsl.translate_pending = broken +try: + expect('broken pool: pass reported as incomplete', gfx2hlsl.watch_pass('.', True), False) +except BrokenProcessPool: + failures.append('a broken process pool escaped watch_pass') +finally: + gfx2hlsl.translate_pending = real +with tempfile.TemporaryDirectory() as tmp: + expect('normal pass reported as complete', gfx2hlsl.watch_pass(tmp, True), True) + +# An invalid job count falls back to the processor count instead of raising. +saved = os.environ.get('X2W_TRANSLATE_JOBS') +for value in ('', 'abc', '-3'): + os.environ['X2W_TRANSLATE_JOBS'] = value + expect('X2W_TRANSLATE_JOBS=%r' % value, gfx2hlsl.translation_jobs() >= 1, True) +os.environ['X2W_TRANSLATE_JOBS'] = '2' +expect('X2W_TRANSLATE_JOBS=2', gfx2hlsl.translation_jobs(), 2) +if saved is None: + del os.environ['X2W_TRANSLATE_JOBS'] +else: + os.environ['X2W_TRANSLATE_JOBS'] = saved + +with tempfile.TemporaryDirectory() as tmp: + d = Path(tmp) + # A failure from an earlier run, newer than its marker: the watcher's first pass retries it once. + now = time.time() + touch(d / ('req_%016x.rtv' % 8), b'not an rtv request either', mtime=now - 20) + touch(d / ('%016x.fail' % 8), b'stale reason\n', mtime=now - 10) + watch = subprocess.Popen([sys.executable, '-B', str(ROOT / 'tools' / 'startup' / 'gfx2hlsl.py'), + '--watch', str(d), '0.1'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + try: + time.sleep(0.5) + # Written while the watcher runs; an invalid RTV request fails without a GPU or compiler. + touch(d / ('req_%016x.rtv' % 7), b'not an rtv request') + fail = d / ('%016x.fail' % 7) + deadline = time.time() + 20 + while not fail.exists() and time.time() < deadline and watch.poll() is None: + time.sleep(0.1) + expect('watcher wrote a failure for the new request', fail.exists(), True) + first = fail.stat().st_mtime_ns if fail.exists() else None + time.sleep(1.0) + expect('failure left unchanged by later passes', fail.stat().st_mtime_ns if fail.exists() else None, first) + old = (d / ('%016x.fail' % 8)).read_text().strip() + expect('earlier failure retried once at start', old, 'invalid RTV variant request') + expect('watcher still running', watch.poll(), None) + finally: + watch.kill() + out, err = watch.communicate(timeout=20) + lines = sorted(line for line in out.splitlines() if line.strip()) + expect('watcher output (each request translated once)', [line[:16] for line in lines], ['%016x' % 7, '%016x' % 8]) + if err.strip(): + failures.append('watcher stderr: %r' % err.strip()[-500:]) + +for item in failures: + print('FAIL', item) +if failures: + sys.exit(1) +print('startup_gfx2hlsl_watch_check passed') diff --git a/tests/startup_run_ps1_check.py b/tests/startup_run_ps1_check.py index fe2ec68db..904b79917 100644 --- a/tests/startup_run_ps1_check.py +++ b/tests/startup_run_ps1_check.py @@ -25,13 +25,34 @@ STUB = """\ import json import sys +import time from pathlib import Path Path(__file__).with_name("argv.json").write_text(json.dumps(sys.argv[1:]), encoding="utf-8") +# Under -Translate, wait until the watcher stub has started so run.ps1 cannot stop it before then. +deadline = time.time() + 30 +while Path(__file__).with_name("translate.flag").exists() and not Path(__file__).with_name("watch.json").exists() \\ + and time.time() < deadline: + time.sleep(0.05) for n in range(1, 8): print("stub debugger line", n) sys.exit({code}) """ +# Stands in for tools/startup/gfx2hlsl.py under -Translate: starts a child process, as the parallel +# workers are, records its own and the child's process ids and its arguments, then waits to be stopped. +WATCH_STUB = """\ +import json +import os +import subprocess +import sys +import time +from pathlib import Path + +child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"]) +Path(__file__).with_name("watch.json").write_text(json.dumps([os.getpid(), child.pid] + sys.argv[1:]), encoding="utf-8") +time.sleep(120) +""" +STOP = "taskkill.exe /T /F /PID $translator.Id" CAPTURE = re.compile(r"\$(\w+)\s*=\s*\$LASTEXITCODE", re.I) EXIT = re.compile(r"exit\s+\$(\w+)", re.I) HEAD = 'Get-Content "$LogDir.out" -TotalCount 5' @@ -43,13 +64,20 @@ def decode(raw): return raw.decode("utf-16" if wide else "utf-8-sig", errors="replace") -def run_case(shell, script, code, work): +def alive(pid): + out = subprocess.run(["tasklist", "/FI", f"PID eq {pid}", "/FO", "CSV", "/NH"], + capture_output=True, text=True, errors="replace") + return f'"{pid}"' in out.stdout + + +def run_case(shell, script, code, work, translate=False): """Run one copy of the script on a stub that exits with `code`; return what is wrong.""" root = Path(tempfile.mkdtemp(dir=work)) startup = root / "tools" / "startup" startup.mkdir(parents=True) (startup / "run.ps1").write_bytes(script.encode("utf-8")) (startup / "debug_launch.py").write_text(STUB.format(code=code), encoding="utf-8") + (startup / "gfx2hlsl.py").write_text(WATCH_STUB, encoding="utf-8") (root / "bld").mkdir() for dll in DLLS: # the stand-ins the script copies next to the executable (root / "bld" / f"{dll}.dll").write_bytes(b"") @@ -64,6 +92,9 @@ def run_case(shell, script, code, work): command = [shell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(startup / "run.ps1"), "-Exe", str(exe), "-DataDir", str(data), "-LogDir", str(log), "-BuildDir", "bld", "-Seconds", "9", "-MemoryGiB", "3", "-ContinueAsserts", "4"] + if translate: + command += ["-Render", "-Translate", "-ShaderCache", "cache"] + (startup / "translate.flag").write_bytes(b"") try: out = subprocess.run(command, cwd=root, env=env, capture_output=True, text=True, errors="replace", timeout=120) @@ -87,6 +118,18 @@ def run_case(shell, script, code, work): got = json.loads(record.read_text(encoding="utf-8")) if record.is_file() else None if got != want: found.append(f"stub exit {code}: the debugger received {got}, expected {want}") + watch = startup / "watch.json" + if translate: + started = json.loads(watch.read_text(encoding="utf-8")) if watch.is_file() else None + if not started or started[2:] != ["--watch", str(root / "cache")]: + found.append(f"-Translate: the translator received {started}, expected --watch {root / 'cache'}") + else: + for pid, what in ((started[0], "translator"), (started[1], "translator's child process")): + if alive(pid): + subprocess.run(["taskkill", "/T", "/PID", str(pid), "/F"], capture_output=True) + found.append(f"-Translate: the {what} was still running after run.ps1 exited") + elif watch.is_file(): + found.append(f"stub exit {code}: the translator started without -Translate") return found @@ -95,8 +138,8 @@ def run_problems(shell, script, work, first_only): for code in (2, 0, 7): # 2 is the debugger's "CreateProcess failed"; 7 rules out a fixed code found += run_case(shell, script, code, work) if found and first_only: - break - return found + return found + return found + run_case(shell, script, 7, work, translate=True) def text_problems(script): @@ -171,7 +214,13 @@ def main(): failures += [f"{name}: {item}" for item in bad] if bad: continue - for label, mutant in mutants_of(script).items(): + mutants = mutants_of(script) + if shells: # only an executed run can see the translator outlive the script + stopless = "\n".join(line for line in script.splitlines() if STOP not in line) + "\n" + mutants["translator left running"] = None if stopless == script else stopless + parent_only = script.replace(STOP, "Stop-Process -Id $translator.Id -Force") + mutants["translator's workers left running"] = None if parent_only == script else parent_only + for label, mutant in mutants.items(): if mutant is None or not check(mutant, True): failures.append(f"{name}: mutant '{label}' was not detected") for item in failures: diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 20cb8444d..06449f09c 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -9,6 +9,7 @@ import re import struct import sys +import time sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) import disasm_rdna2 as D # noqa: E402 @@ -1995,7 +1996,72 @@ def main(): for ext, blob in (('.a', a), ('.b', b), ('.root', root)): open(os.path.join(out_dir, 'req_%016x%s' % (key, ext)), 'wb').write(blob) print('pso %x -> request %016x' % (w & 0xffffff, key)) - # translate every request that has no result yet + if sys.argv[1] == '--watch': + # --watch <dir> [seconds]: translate requests as a running title writes them, until stopped + interval = float(sys.argv[3]) if len(sys.argv) > 3 else 2.0 + # The first pass retries earlier failures once (the runtime never rewrites a request, so a + # translator fix would otherwise not reach them); later passes skip failures already written. + skip_failed = False + while True: + if watch_pass(out_dir, skip_failed): + skip_failed = True + time.sleep(interval) + translate_pending(out_dir) + + +def watch_pass(out_dir, skip_failed): + """One --watch pass. A worker killed from outside (out of memory) breaks the pool; the pass is + reported and its requests are retried on the next pass instead of ending the watcher.""" + from concurrent.futures.process import BrokenProcessPool + try: + translate_pending(out_dir, skip_failed=skip_failed) + return True + except BrokenProcessPool as error: + print('translation pass interrupted, retrying: %s' % error, file=sys.stderr, flush=True) + return False + + +def translate_one(out_dir, key): + """translate_request, with an unexpected translator error recorded as <key>.fail instead of raised.""" + try: + return translate_request(out_dir, key) + except Exception as error: # noqa: BLE001 - one bad request must not stop a scan or the watcher + reason = 'translator error: %s: %s' % (type(error).__name__, error) + with open(os.path.join(out_dir, '%016x.fail' % key), 'w') as fail: + fail.write(reason + '\n') + return reason + + +def translation_jobs(): + try: + jobs = int(os.environ.get('X2W_TRANSLATE_JOBS') or 0) + except ValueError: + jobs = 0 + jobs = jobs if jobs > 0 else os.cpu_count() or 1 + return min(jobs, 61) if os.name == 'nt' else jobs # ProcessPoolExecutor refuses more than 61 on Windows + + +def translate_pending(out_dir, skip_failed=False, jobs=None): + """Translate every request that has no result yet. The runtime writes .a and .rtv last, as ready markers. + + Requests are independent (each writes only its own <key>.* files), so several run in parallel + processes; X2W_TRANSLATE_JOBS (default: the processor count, at most 61 on Windows) sets how many. + """ + keys = pending_keys(out_dir, skip_failed) + jobs = min(jobs or translation_jobs(), len(keys)) + if jobs < 2: + for key in keys: + print('%016x: %s' % (key, translate_one(out_dir, key)), flush=True) + return + from concurrent.futures import ProcessPoolExecutor + chunk = max(1, len(keys) // (jobs * 4)) # small batches keep every worker busy + with ProcessPoolExecutor(max_workers=jobs) as pool: + for key, result in zip(keys, pool.map(translate_one, [out_dir] * len(keys), keys, chunksize=chunk)): + print('%016x: %s' % (key, result), flush=True) + + +def pending_keys(out_dir, skip_failed): + keys = [] for name in sorted(os.listdir(out_dir)): m = re.fullmatch(r'req_([0-9a-f]{16})\.(?:a|rtv)', name) if not m: @@ -2003,7 +2069,12 @@ def main(): key = int(m.group(1), 16) if os.path.exists(os.path.join(out_dir, '%016x.txt' % key)): continue - print('%016x: %s' % (key, translate_request(out_dir, key))) + fail = os.path.join(out_dir, '%016x.fail' % key) + # A repeated pass retries a failure only once its request is rewritten. + if skip_failed and os.path.exists(fail) and os.path.getmtime(fail) >= os.path.getmtime(os.path.join(out_dir, name)): + continue + keys.append(key) + return keys if __name__ == '__main__': diff --git a/tools/startup/run.ps1 b/tools/startup/run.ps1 index beda10d23..302b92e4c 100644 --- a/tools/startup/run.ps1 +++ b/tools/startup/run.ps1 @@ -26,6 +26,7 @@ param( [switch]$FakeUser, # answer the user API for one local user [switch]$GpuMirror, # map CPU-view pages into the paired GPU-view reservation [switch]$HostCpu, # rewrite instructions the host processor lacks (X2W_HOST_CPU) + [switch]$Translate, # with -Render: translate new shader requests during the run (gfx2hlsl.py --watch) [switch]$StartupBelow40 # place the 0x283 large-page startup blocks below 2^40 (X2W_XMEM_STARTUP_BELOW_40) ) $ErrorActionPreference = "Stop" @@ -56,8 +57,20 @@ if ($Render) { New-Item -ItemType Directory -Force $LogDir | Out-Null $python = Join-Path $repo "out\pe-env\Scripts\python.exe" if (-not (Test-Path -LiteralPath $python)) { $python = "python" } -& $python -B (Join-Path $PSScriptRoot "debug_launch.py") $Exe $DataDir $LogDir --timeout $Seconds --memory-gib $MemoryGiB ` - --trace-files 1 --continue-asserts $ContinueAsserts *> "$LogDir.out" -$debuggerExit = $LASTEXITCODE +$translator = $null +if ($Translate -and -not $Render) { Write-Warning "-Translate needs -Render (no shader cache without it); ignored" } +if ($Translate -and $Render) { + $translator = Start-Process -FilePath $python -PassThru -NoNewWindow ` + -ArgumentList "-B", "`"$(Join-Path $PSScriptRoot 'gfx2hlsl.py')`"", "--watch", "`"$env:X2W_SHADER_CACHE`"" ` + -RedirectStandardOutput (Join-Path $LogDir "translate.txt") -RedirectStandardError (Join-Path $LogDir "translate_err.txt") +} +try { + & $python -B (Join-Path $PSScriptRoot "debug_launch.py") $Exe $DataDir $LogDir --timeout $Seconds --memory-gib $MemoryGiB ` + --trace-files 1 --continue-asserts $ContinueAsserts *> "$LogDir.out" + $debuggerExit = $LASTEXITCODE +} finally { + # /T: the watcher's parallel workers (and their fxc.exe) are separate processes + if ($translator) { & taskkill.exe /T /F /PID $translator.Id 2>&1 | Out-Null } +} Get-Content "$LogDir.out" -TotalCount 5 exit $debuggerExit