diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index f6e0789ef1..a48b2971f0 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -230,6 +230,7 @@ jobs: tests/startup_gfx2hlsl_bit_alu_check.py \ tests/startup_gfx2hlsl_mad_check.py \ tests/startup_gfx2hlsl_compute_check.py \ + tests/startup_compute_translate_check.py \ tests/startup_gfx2hlsl_swap_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ tests/startup_gfx2hlsl_vopc_sdwa_check.py \ diff --git a/AGENTS.md b/AGENTS.md index b2ed67c857..6b6b210ca9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -150,6 +150,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_operand_count_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mad_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_check.py +./out/pe-env/bin/python -B tests/startup_compute_translate_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py ./out/pe-env/bin/python -B tests/startup_image_2d_array_check.py ./out/pe-env/bin/python -B tests/startup_image_sample_a16_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 7078fc9610..c6904167c1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2811,6 +2811,22 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_request_check.py" "$" disabled) set_tests_properties(startup_compute_request_warp startup_compute_request_disabled_control PROPERTIES TIMEOUT 60) set_tests_properties(startup_compute_request_disabled_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: no compute request") + # Slot 67 request translation: request checks, then stand-in request -> --pending -> DXC -> dispatch; the + # wrong-group control must mismatch. + add_test(NAME startup_compute_translate_requests COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_translate_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_translate_e2e_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_translate_check.py" e2e "$" + "${DXC_EXECUTABLE}" "$" ${adapter}) + add_test(NAME startup_compute_translate_e2e_wrong_group_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_translate_check.py" e2e "$" + "${DXC_EXECUTABLE}" "$" ${adapter} wrong-group) + set_tests_properties(startup_compute_translate_e2e_${adapter} startup_compute_translate_e2e_wrong_group_${adapter} + PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + set_tests_properties(startup_compute_translate_e2e_wrong_group_${adapter} PROPERTIES + PASS_REGULAR_EXPRESSION "control wrong-group: rejected at word=[0-9]+ ") + endforeach() foreach(backend IN ITEMS warp hardware) add_test(NAME startup_stream_draw_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_draw_check.py" diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index a34410adee..103e84bda7 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -642,10 +642,10 @@ costs no file access, and the writes take their own lock, not the draw lock. `not written`, with the reason when refused, up to 12 lines per run. The render totals line ends with `compute requests published (already present , failed , pointer-like blob qwords )`. -**Offline.** `gfx2hlsl.py --pending` and `--watch` take `.c67` as a ready marker. With no compute stage yet, -they record `compute stage not supported` in `.fail`. The request stays in the cache, and a later -`--pending` retries it. `--refusals` reports compute requests in a separate section, so its graphics counts -do not change, and `triage_run.py` puts their `.fail` reasons in a `compute:` class. +**Offline.** `gfx2hlsl.py --pending` and `--watch` take `.c67` as a ready marker and translate the request +(see [Compute pipeline translation](#compute-pipeline-translation)). A refused request stays in the cache, and +a later `--pending` retries it. `--refusals` reports compute requests in a separate section, so its graphics +counts do not change, and `triage_run.py` puts their `.fail` reasons in a `compute:` class. **Local observation** (a local build of this change ported to an older base; one title, local files only, not in the repository): @@ -667,6 +667,59 @@ after building `startup_stream_consumer`. On WARP: - A request whose first four parts already exist is completed without rewriting them. - The control runs without render mode and must print `FAIL: no compute request`. +### Compute pipeline translation + +`gfx2hlsl.py --pending` and `--watch` translate a `.c67` request with the compute stage instead of recording +`compute stage not supported`. The request is checked first, and it is refused into `.fail` (with no +cache path in the text) when: +- a part is missing; +- `.desc` is not 96 bytes; +- a part's length disagrees with its size word in `.desc` (code word 6, data word 8, state blocks words 2 and 4); +- the files do not hash to the key in their name; +- the code is empty, is not whole dwords, or has no `s_endpgm`. + +The translation is `ComputePipeline(code, root, COMPUTE_PGM_RSRC2, group size)`. Both register values come +from state block A, which must be 28 bytes. The stage writes `.cs.hlsl`, then `.cs.cso` (DXC +`cs_6_0`), then the `stage cs` manifest `.txt` last; a stage refusal goes to `.fail` with the +stage's own reason. A request is done once `.txt` and `.cs.cso` exist. `X2W_FXC=` (empty) +publishes the manifest alone, as for graphics. `.cs.cso` has the same form as the slot 62 results of +#1441 in the same directory. The keys come from different hashes, so the names clash only on a 64-bit +collision. The stand-in does not load the result yet and still creates a placeholder. + +The state-block reading is a **hypothesis** from a local observation of 2,689 requests (an earlier local build +of the request change; one title, local files only): +- dword 3 holds the thread-group size X in its low 16 bits and Y in its high 16 bits, and the low 16 bits of + dword 4 hold Z. All 2,689 sizes are within the `numthreads` limits, with 43 distinct sizes. +- dword 6 has the `COMPUTE_PGM_RSRC2` layout. Bits 31:24 are zero, and the thread-ID component count never + exceeds what the group size needs; it covers a Y size above 1 in 2,671 of 2,689. `TG_SIZE_EN` is set in 91, + which the stage refuses. + +The stand-in does not decode these values. + +Census: one title, local files only. +- Requests: 2,689, published by a local build of the request change that was ported to an older base. +- Re-keying: the requests were re-keyed offline with this `compute_key`. The files are unchanged; only their + names change. +- Result: 8 of 2,689 translate and compile, and `--pending` took 11 s. No request is refused by the request + checks above. +- First refusal per request: + - `buffer_load_format` from the descriptor format: 1,280; + - scalar writes under `s_cbranch_execz`: 541; + - `s_load` with a register offset through the resource heap: 158; + - `image_store`: 110; + - `TG_SIZE_EN`: 91. + +Run `python -B tests/startup_compute_translate_check.py` (ctest `startup_compute_translate_requests`, pure +Python) to check the refusals above and the case A manifest. `startup_compute_translate_e2e_` +goes end to end on the GPU: +1. the stand-in publishes case A of `startup_gfx2hlsl_compute_check.py`; +2. `--pending` translates it and DXC compiles it; +3. `offscreen_check` dispatches `.cs.cso` and compares all 320 words. + +Its `wrong_group` control swaps the group size in the state block and must mismatch. This proves that the +request, translation, bytecode and dispatch fit together. It does not prove the state-block reading, because +the fixture builds the block at the offsets the translator reads. + `run.ps1` prints the first five lines of `.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 did. Check with `python3 -B tests/startup_run_ps1_check.py` (ctest `startup_run_ps1`): on Windows it diff --git a/tests/startup_compute_request_check.py b/tests/startup_compute_request_check.py index 4c7af91fc4..0ac0417c2e 100644 --- a/tests/startup_compute_request_check.py +++ b/tests/startup_compute_request_check.py @@ -15,7 +15,7 @@ their limits publish; valid -> refused -> valid publishes exactly the two valid keys; - parts left by an interrupted earlier write (no .c67) are kept and the next creation completes the request; - a data qword that names committed memory is counted and still published; -- gfx2hlsl.py --pending records "compute stage not supported" in .fail, and --refusals reports compute +- gfx2hlsl.py --pending records the compute stage's refusal of the 24-byte state block A in .fail, and --refusals reports compute requests in their own section. "disabled" is the negative control: without X2W_D3D12_RENDER=1 nothing is published, and the check must print "FAIL: no compute request". @@ -168,19 +168,19 @@ def check(directory, consumer, disabled): out = subprocess.run([sys.executable, "-B", gfx2hlsl.__file__, "--pending", cache], check=True, capture_output=True, text=True).stdout - assert f"{key:016x}: unsupported: compute stage not supported" in out, out - assert (cache / ("%016x.fail" % key)).read_text() == "compute stage not supported\n" + assert f"{key:016x}: unsupported: compute state block A is 24 bytes, not 28" in out, out + assert (cache / ("%016x.fail" % key)).read_text() == "compute state block A is 24 bytes, not 28\n" assert not (cache / ("%016x.txt" % key)).exists() assert all((cache / file).read_bytes() == data for file, data in files.items()), "the offline pass changed the request" report = gfx2hlsl.refusals_report(cache) assert report["per_request"]["examined"] == 0, report["per_request"] assert report["compute"] == dict(examined=3, no_refusal=0, reasons=[ - dict(reason="compute stage not supported", containing=3, first=3)]), report["compute"] + dict(reason="compute state block A is 24 bytes, not 28", containing=3, first=3)]), report["compute"] check_boundaries(directory, consumer) print(f"startup_compute_request: PASS on WARP (request {key:016x}: exact files, length-framed runtime key, " "published once across two creations and two processes, refusals and limits, interrupted write completed, " - "offline 'compute stage not supported' recorded)") + "offline refusal recorded)") return 0 diff --git a/tests/startup_compute_request_offline_check.py b/tests/startup_compute_request_offline_check.py index 74d88340d9..9375228bca 100644 --- a/tests/startup_compute_request_offline_check.py +++ b/tests/startup_compute_request_offline_check.py @@ -4,7 +4,7 @@ each part preceded by its u64 length, in the order code, data, root, desc, state A, state B) and a literal. - A cache directory with one synthetic request (req_.{desc,sa,sb,data,root,c67}) is found by request_keys(compute=True) and pending_keys, but not by the graphics request_keys; gfx2hlsl.py --pending - records "compute stage not supported" in .fail and writes no manifest; --refusals --json reports it in + records the compute stage's refusal of its 24-byte state block A in .fail and writes no manifest; --refusals --json reports it in the compute section only. """ import json @@ -18,6 +18,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools' / 'startup')) import gfx2hlsl as G # noqa: E402 +REASON = 'compute state block A is 24 bytes, not 28' # the compute stage refuses the synthetic block CODE = struct.pack('<2I', 0x7e020280, 0xbf810000) DATA = struct.pack('<2Q', 0xfedcba9876543210, 0xffff00001111008c) ROOT = b'RTS0 synthetic root' @@ -51,14 +52,14 @@ def main(): assert G.pending_keys(str(cache), skip_failed=False) == [key] out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', str(cache)], check=True, capture_output=True, text=True, env=dict(os.environ, X2W_TRANSLATE_JOBS='1')).stdout - assert out == '%016x: unsupported: compute stage not supported\n' % key, out - assert (cache / ('%016x.fail' % key)).read_text() == 'compute stage not supported\n' + assert out == '%016x: unsupported: %s\n' % (key, REASON), out + assert (cache / ('%016x.fail' % key)).read_text() == REASON + '\n' assert not (cache / ('%016x.txt' % key)).exists() report = json.loads(subprocess.run([sys.executable, '-B', G.__file__, '--refusals', str(cache), '--json'], check=True, capture_output=True, text=True).stdout) assert report['per_request']['examined'] == 0, report['per_request'] assert report['compute'] == dict(examined=1, no_refusal=0, reasons=[ - dict(reason='compute stage not supported', containing=1, first=1)]), report['compute'] + dict(reason=REASON, containing=1, first=1)]), report['compute'] print('compute request offline: key vector, request_keys/pending_keys, --pending record and --refusals ' 'compute section pass') diff --git a/tests/startup_compute_translate_check.py b/tests/startup_compute_translate_check.py new file mode 100644 index 0000000000..43646a125b --- /dev/null +++ b/tests/startup_compute_translate_check.py @@ -0,0 +1,151 @@ +"""Translation of device slot 67 compute requests by gfx2hlsl.py --pending (the compute stage of #2182). + +usage: startup_compute_translate_check.py request checks, pure Python + startup_compute_translate_check.py e2e [wrong-group] + +Request checks: cache files are written here with gfx2hlsl.compute_key. Case A of +startup_gfx2hlsl_compute_check.py, with a 28-byte state block A carrying its group size and COMPUTE_PGM_RSRC2, +translates (manifest only, X2W_FXC empty) to a `stage cs` manifest. Each malformed request is refused into +.fail with no manifest: code of 0 bytes or not whole dwords, code without s_endpgm, a part whose length +disagrees with the size words in .desc, files that do not hash to the key in their name, a state block A that +is not 28 bytes, and a missing part (the .fail text names no path). + +e2e: the stand-in publishes case A, gfx2hlsl.py --pending translates it with DXC, and offscreen_check dispatches +the published .cs.cso and compares all 320 words with that test's expectation. This proves the plumbing +is self-consistent (request files, translation, compiled bytecode, dispatch); it does not prove the state-block +mapping, because the fixture builds the block at the offsets the translator reads. "wrong-group" swaps the +group size in the state block (3x2x4 for 2x3x4); the readback must then mismatch. +""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +import startup_gfx2hlsl_compute_check as C +from startup_compute_request_check import DATA, STATE_B, prepare, run +from startup_stream_check import gfx2hlsl as G + + +def state_a(group, rsrc2): + # The observed offsets: dword 3 = X | Y << 16, dword 4 = Z, dword 6 = COMPUTE_PGM_RSRC2. + return struct.pack('<7I', 0, 0, 0, group[0] | group[1] << 16, group[2], 0, rsrc2) + + +def write_request(cache, code, state, data=DATA, root=None, desc_sizes=None): + root = C.root_blob() if root is None else root + sizes = desc_sizes or (len(state), len(STATE_B), len(code), len(data)) + desc = struct.pack('<12Q', 0, 0, sizes[0], 0, sizes[1], 0, sizes[2], 0, sizes[3], 0, 0, 11) + key = G.compute_key(code, data, root, desc, state, STATE_B) + for ext, part in (('.desc', desc), ('.sa', state), ('.sb', STATE_B), ('.data', data), ('.root', root), ('.c67', code)): + (cache / ('req_%016x%s' % (key, ext))).write_bytes(part) + return key + + +def check_requests(directory): + _, words, rsrc2, group, _ = C.CASES['A'] + good = state_a(group, rsrc2) + cache = directory / 'cache' + cache.mkdir() + env = dict(os.environ, X2W_FXC='') + key = write_request(cache, words, good) + assert G.translate_request(str(cache), key) == 'ok' if os.environ.update(env) is None else False + manifest = (cache / ('%016x.txt' % key)).read_text() + assert manifest.startswith('x2w-manifest 2\nstage cs\ngroup 2 3 4\n'), manifest + assert '[numthreads(2, 3, 4)]' in (cache / ('%016x.cs.hlsl' % key)).read_text() + + end = words.rindex(struct.pack('> 16, words[4] & 0xffff) + + +def load_compute_request(out_dir, key, refusals=None): + """The ComputePipeline of a slot 67 request, after checking the files against .desc and the key.""" + name = os.path.join(out_dir, 'req_%016x' % key) + try: + parts = {ext: open(name + ext, 'rb').read() for ext in ('.c67', '.data', '.root', '.desc', '.sa', '.sb')} + except OSError: + raise Unsupported('unreadable shader request') from None # the error text would name the cache path + desc = parts['.desc'] + if len(desc) != 96: + raise Unsupported('compute description is %d bytes, not 96' % len(desc)) + words = struct.unpack('<12Q', desc) + for ext, word in (('.c67', 6), ('.data', 8), ('.sa', 2), ('.sb', 4)): + if len(parts[ext]) != words[word]: + raise Unsupported('compute request %s is %d bytes, the description says %d' % (ext, len(parts[ext]), words[word])) + if compute_key(parts['.c67'], parts['.data'], parts['.root'], desc, parts['.sa'], parts['.sb']) != key: + raise Unsupported('compute request files do not match the key in their name') + code = parts['.c67'] + if not code or len(code) % 4: + raise Unsupported('compute code of %d bytes is not whole dwords' % len(code)) + if S_ENDPGM not in struct.unpack('<%dI' % (len(code) // 4), code): + raise Unsupported('compute code without s_endpgm') + rsrc2, group = compute_entry(parts['.sa']) + return ComputePipeline(code, parts['.root'], rsrc2, group, refusals=refusals) def compute_refusals(out_dir, key): - """Refusal sites of one slot 67 compute request. No compute stage yet: every request waits in the cache.""" - return [(COMPUTE_UNSUPPORTED, 'pipeline')] + """Refusal sites of one slot 67 compute request, without publishing a translation.""" + refusals, op = [], 'request loading' + try: + pipe = load_compute_request(out_dir, key, refusals) + op = 'hlsl_cs' + pipe.hlsl_cs() + op = 'manifest' + pipe.manifest() + except Unsupported as reason: + refusals.append((str(reason), 'pipeline')) + except Exception as error: # noqa: BLE001 - one request must not end the census + refusals.append((handler_error(op, error, refusals), 'pipeline')) + return refusals def translate_compute(out_dir, key): - """Record why a slot 67 compute request is not translated, the way a refused graphics request is.""" - open(os.path.join(out_dir, '%016x.fail' % key), 'w').write(COMPUTE_UNSUPPORTED + '\n') - return 'unsupported: %s' % COMPUTE_UNSUPPORTED + """Writes .cs.hlsl, then .cs.cso (DXC cs_6_0) and .txt last, or .fail with the reason. + X2W_FXC set to the empty string publishes the manifest alone, as for graphics.""" + name = os.path.join(out_dir, '%016x' % key) + with suppress(FileNotFoundError): + os.remove(name + '.txt') # the result is unpublished until validation and compilation finish + try: + pipe = load_compute_request(out_dir, key) + hlsl, manifest = pipe.hlsl_cs(), pipe.manifest() + except Unsupported as reason: + open(name + '.fail', 'w').write(str(reason) + '\n') + return 'unsupported: %s' % reason + open(name + '.cs.hlsl', 'w').write(hlsl) + if os.environ.get('X2W_FXC') != '': + compiler = find_dxc() + if compiler is None: + message = 'dxc not found (X2W_DXC=%s): a compute stage needs shader model 6.0' % os.environ.get('X2W_DXC', '') + open(name + '.fail', 'w').write(message + '\n') + return message + import subprocess + with tempfile.TemporaryDirectory(prefix='.dxc-', dir=out_dir) as staging: + bytecode = os.path.join(staging, 'cs.cso') + r = subprocess.run([compiler, '-Gis', '-T', 'cs_6_0', '-E', 'main', '-Fo', bytecode, name + '.cs.hlsl'], + capture_output=True, text=True) + if r.returncode or not has_bytecode(bytecode): + # DXC names the source path; keep only the diagnostic after it. + lines = [re.sub(r'^.*?\.cs\.hlsl(:\d+:\d+)?:\s*', '', line) for line in r.stderr.strip().splitlines()] + detail = lines[0] if lines else ('?' if r.returncode else 'no bytecode produced') + open(name + '.fail', 'w').write('dxc cs: %s\n' % detail[:500]) + return 'dxc cs failed: %s' % detail[:500] + os.replace(bytecode, name + '.cs.cso') + temporary = '%s.txt.%d.tmp' % (name, os.getpid()) + with open(temporary, 'w') as result: + result.write(manifest) + os.replace(temporary, name + '.txt') + with suppress(FileNotFoundError): + os.remove(name + '.fail') + return 'ok' DEFAULT_FXC = r'C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x64\fxc.exe' @@ -3636,10 +3716,9 @@ def pending_keys(out_dir, skip_failed): continue key = int(m.group(1), 16) result = os.path.join(out_dir, '%016x' % key) + stages = ('.cs.cso',) if m.group(2) == 'c67' else ('.vs.cso', '.ps.cso') # A published manifest with bytecode (or manifest-only mode) is done; otherwise resume (#2008). - if os.path.isfile(result + '.txt') and ( - manifest_only or (has_bytecode(result + '.vs.cso') and has_bytecode(result + '.ps.cso')) - ): + if os.path.isfile(result + '.txt') and (manifest_only or all(has_bytecode(result + s) for s in stages)): continue fail = os.path.join(out_dir, '%016x.fail' % key) # A repeated pass retries a failure only once its request is rewritten.