Skip to content

wave64_emulate_opt: a scalar branch from a folded EXECZ region to its join skips the rest of the region - #4574

Open
Bloh09 wants to merge 1 commit into
ItsNotRexed:mainfrom
Bloh09:fix/wave64-emulate-fold-exit-edge
Open

Bloh09 wants to merge 1 commit into
ItsNotRexed:mainfrom
Bloh09:fix/wave64-emulate-fold-exit-edge

Conversation

@Bloh09

@Bloh09 Bloh09 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Claimed in the coordination issue as: new SHADER item (claim comment)

What and why

Under --wave64-emulate, a folded lane-local s_cbranch_execz region could ignore a scalar branch that leaves the region early. Example:

v_cmp_lt_u32 vcc, 12, v3
s_and_saveexec_b64 s[8:9], vcc
s_cbranch_execz L
s_cmp_ge_u32 s11, 33        ; s11 = 5, so SCC = 0
s_cbranch_scc0 L            ; taken: the add must not run
v_add_nc_u32 v4, 21, v4
L: s_or_b64 exec, exec, s[8:9]

Native wave64 (structured and --dispatch-loop) leaves v4 alone on every lane, as the ISA says. The emulated translation added 21 on every lane that entered the region, with subgroup size 32 or 64.

Cause: find_local_exec_folds in tools/wave64_emulate_opt.py built the region's sub-CFG from the edges inside the region only. The inner block's edge to skip (the join) was dropped, so cfg_structure.structure saw a straight line and put the next block in with no %pc guard. emit_folded_region stored the right %pc for the branch and then ran the next block anyway.

Fix: edges to the join now go to an exit node sub_end in the sub-CFG, so later blocks of the region get their %pc guard. _drop_tree_block removes the exit node from the tree before _unwrap_known_pc_guards, so it emits nothing. Regions without such an exit edge get the same tree as before, and the region is still folded (the test checks for one switch case).

Found with a local differential: cf_diff-style wave64 programs (plus cross-lane leaves) translated as compute shaders, emulated vs native vs tools/cf_ref.py. I minimized it from one program out of about 1,800.

Tested

All on Linux x86_64, Python 3.13.5, on the CPU only. There is no GPU on this machine, so this is not GPU-verified.

AI-assisted.

Checklist

  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed.

@SweatierKey

Copy link
Copy Markdown
Contributor

Tested a54ea0ee on Linux (x86_64, Python 3.13.5, SPIRV-Tools on PATH, CPU/no-GPU): pass (code read + full test_wave64_emulate_opt.py suite).

What I ran:

  • git diff --check d0835dd9..HEAD: clean.
  • PYTHONPATH=tests/semantic python3 -m unittest -v tests/semantic/test_wave64_emulate_opt.py (with LEONIDA_REQUIRE_SPIRV_TOOLS=1): 23/23 OK (including the new test_folded_region_scalar_branch_to_join_skips_the_rest across all 4 s_cmp_*/s_cbranch_scc* cases × 64/128 threads, verifying 1 switch case and exact per-lane memory).

Code review:

  • Preserving outgoing edges to skip via a synthetic sink sub_end = len(order) in sub_succ before calling cfg_structure.structure(sub_succ), then stripping sub_end iteratively with _drop_tree_block, cleanly forces %pc guards on subsequent blocks inside the folded region so an early scalar branch to the join skips them instead of falling through.
  • Deduplicating successors with list(dict.fromkeys(...)) and updating docs/design.md alongside the regression test is tidy and self-contained.

@Kam471 Kam471 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ran this at a54ea0ee on Windows 11, RTX 5070 Ti.

  • tests/semantic/test_wave64_emulate_opt.py -> 23 tests, OK (5.7 s); git diff --check clean. The new test_folded_region_scalar_branch_to_join_skips_the_rest covers taken and not-taken scc0/scc1 at 64 and 128 threads and asserts the region is still folded.
  • GPU emulated run, LEONIDA_W64_EMULATE=1 run_gpu_tests.py --filter cs_w64x with this translator -> 19/19 passed, including cs_w64x_saveexec_b64, cs_w64x_mask_reuse(2), cs_w64x_sbarrier, cs_w64x_wg128_branches, cs_w64x_partial_scmp.

find_local_exec_folds now gives a sub_end exit node to edges into skip and drops that empty guard from the tree, so the blocks after an in-region scalar exit keep their %pc guard. With the old edge dropped, the test's four taken cases ran the rest of the region. No blocking issue; still not GPU-verified specifically for the exit sequence, as the row says.

@Atomic258

Copy link
Copy Markdown
Contributor

Tested head a54ea0eebf1ad46c021a7b919963944b52e7d2fe on Linux, Python 3.10.12, standard library only, hand-written asm fixtures (no game files, no GPU).

  • python -I tests/semantic/test_wave64_emulate_opt.py on the PR head: Ran 23 tests — OK
  • Negative control, same test against main's tools/wave64_emulate_opt.py: FAILED (failures=4) — the folded-EXECZ-region branch skip is exercised by the new tests.

The scalar-branch join handling in the wave64 emulator matches the description. AI-assisted (Devin).

@justr4mzi

Copy link
Copy Markdown
Contributor

Verified a54ea0ee on Windows 11 25H2 + AMD Radeon RX 6700 XT (gfx1031, Adrenalin 26.11.2, Vulkan 1.4.315, SPIRV-Tools v2026.4, llvm-mc 21.1.8).

GPU, semantic & negative-control checks

  • LEONIDA_W64_EMULATE=1 + LEONIDA_VK_VALIDATION=1 python -I scripts/run_gpu_tests.py --filter cs_w64 --require-pass: 21 shaders translated & spirv-val validated, 21/21 passed, 0 validation errors on AMD Radeon RX 6700 XT.
  • python -I tests/semantic/test_wave64_emulate_opt.py -v: 23/23 OK (5.886 s; via unittest discover: 23/23 OK, 6.207 s).
  • Negative control (HEAD~1 tools/wave64_emulate_opt.py with the new test): FAILED (failures=4 subtests), e.g. AssertionError: 122 != 1 : lane 3 (threads=64 and threads=128).
  • All 7 tests/test_docs_*.py suites: 7/7 passed; py_compile (tools/wave64_emulate_opt.py, tests/semantic/test_wave64_emulate_opt.py), scripts/check_no_game_data.py, and git diff --check clean (rc=0).
  • Audited find_local_exec_folds() / _drop_tree_block() in tools/wave64_emulate_opt.py: region construction guarantees external successors go to skip, matching sub_out_pcs's existing idx_of.get(..., sub_end) mapping and stripping sub_end cleanly before _unwrap_known_pc_guards.

AI-assisted (Gemini, Antigravity).

@whattheflop whattheflop left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI-assisted Windows CPU check at a54ea0ee, uv CPython 3.12.13. The exact scalar-exit case matched all 768 lane words across the eight taken and fallthrough variants at 64 and 128 threads. All eight retained one dispatch switch case and passed Vulkan 1.2 spirv-val.

I inspected the generated modules before attempting the exact case on Radeon. The existing wave64 scheduler emits overlapping non-atomic workgroup stores in its initial clear and round reset. Those code paths predate this PR, and #4247 (SHADER-708) already addresses them. I submitted no GPU dispatches for these fixtures. This is CPU confirmation of the branch fix, with hardware verification of the exact sequence pending that scheduler change.

@Flyander Flyander left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the control-flow exit handling and its regression cases; I found no additional correctness issue in this pass.

@whattheflop whattheflop left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up to the CPU-only review. Scratch 619d84ef combines a54ea0ee with #4247 5f16276d on d0835dd9. On Windows Radeon iGPU (25.10.30.02), all eight exact early-exit variants completed with 768/768 lane words matching and zero GPU-assisted validation errors or race reports. This covers the 64- and 128-thread emulated case with #4247. Details in #166. AI-assisted.

@wavehs

wavehs commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Verdict: approve (nits only).

The change is correct and the new test is a real regression test. Two checks I ran myself, in a clean worktree at a54ea0ee:

  • Negative control: the PR's test applied to 03b09a08 (prrev/4574^) fails 4 subtests, exactly the taken-branch cases, e.g. AssertionError: 122 != 1 : lane 3.
  • Head: pytest tests/semantic/test_wave64_emulate_opt.py → 23 passed, 18 subtests; with test_wave64_halves.py and test_translate.py → 677 passed, 4 skipped.

Why one exit node is exact rather than approximate: the region closure in find_local_exec_folds (tools/wave64_emulate_opt.py:820-836) keeps region closed under successors except skip, and the single-entry check forbids an external edge back to b, so the only edge out of the region is to skip. Mapping that to a single sub_end cannot merge two different real destinations, and sub_out_pcs already used the same sub_end. An extra sink also cannot make structure() fail, so no fold is lost.

Extra evidence: a loop inside the region with an early exit to the join fails on 03b09a08 (112 != 12 : lane 0) and passes with the fix, i.e. the fix covers shapes the added test does not.

Nits:

  1. The description has no SHADER-NNN item ID, only the claim link to the closed Coordinating who works on what (23) (moved to #4571) #4421; worth adding it once the coordinator assigns one in Coordinating who works on what (24) (moved to #4683) #4571.
  2. tests/semantic/test_wave64_emulate_opt.py:879 builds the program as an instruction list instead of an .asm fixture under tests/semantic/fixtures/disasm (AGENTS.md). It is consistent with the neighbouring fold tests, so fine to leave.
  3. _drop_tree_block relies on structure() emitting a sink as ("guard", b, [("block", b)]) or ("block", b). That is exhaustive today (tools/cfg_structure.py:150-175), and if it ever changes the failure is an IndexError in emit_folded_region (tools/rdna2spirv.py:13966) rather than silently wrong code, so no change is needed — just worth knowing. A one-line assertion that sub_end is gone after the drop would make it explicit.

AI-assisted review.

@Bloh09

Bloh09 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks all for the testing and reviews at a54ea0ee.

@SweatierKey, @Atomic258, @justr4mzi, @Kam471, @whattheflop: thank you for the Linux, Windows CPU and GPU runs and the negative controls. @whattheflop, the combined run with #4247 on Radeon is very helpful for the exact exit sequence, since that is the part I could not verify here (no GPU on this machine).

@Flyander, thanks for the approval.

@wavehs, thanks for the careful review and the extra loop-with-early-exit case:

  1. I will add the SHADER-NNN ID to the description as soon as the coordinator assigns one in Coordinating who works on what (24) (moved to #4683) #4571.
  2. Agreed, I kept the program inline to match the neighbouring fold tests. Happy to move it to an .asm fixture if a maintainer prefers.
  3. Good point about _drop_tree_block depending on the structure() sink shape. I am leaving the head at a54ea0ee for now so the reports above still match it, but I can add the one-line assertion that sub_end is gone after the drop if a maintainer would like it in this PR.

AI-assisted.

@Bloh09
Bloh09 force-pushed the fix/wave64-emulate-fold-exit-edge branch from a54ea0e to 28b20ea Compare November 23, 2026 04:04
@Bloh09

Bloh09 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main at 3eb4410 to clear a docs/design.md conflict (my new row sits next to the Workgroup memory limit row, which main had just edited). New head 28b20ea, code and test unchanged.

Rechecked on Linux x86_64, CPU only (no GPU on this machine): compileall clean, tests/semantic/test_wave64_emulate_opt.py 23 passed, make_game.py --help OK. tests/semantic -k "wave64 or w64": 369 passed, 3 failed, all in test_loop_ballot_barrier.py, which fails the same way (5 failed, 15 passed) on main without this change (owned by #3995).

@Kev-Ball

Copy link
Copy Markdown

Verified the folded-region regression itself on the GPU at 28b20eab (RTX 3080 Ti, 32-lane subgroups, NVIDIA 620.73.04, CachyOS Linux). All eight dispatches passed: SCC0/SCC1, taken/fallthrough, 64/128 threads. All 768 lane outputs matched the fixture's oracle and each translated region retained its single switch case.

Negative control: restored just tools/wave64_emulate_opt.py from the rebase base 3eb4410b and repeated the same compute dispatches. All four taken-branch cases failed, first mismatch lane 3: got 122, expected 1. All four fallthrough cases still passed. This isolates the fix on two physical 32-lane subgroups per emulated wave.

Method: used the test's unmodified _translate_encoded(..., emulate=True), instruction sequences, group sizes and assertions in test_folded_region_scalar_branch_to_join_skips_the_rest. For the workgroup execution helper I assembled and validated for Vulkan 1.2, then dispatched with vk_compute_test <spv> 1 dump, VKC_OUT_WORDS=<thread count>, and VKC_DUMP for per-lane uint32 readback. AI-assisted, synthetic fixture only.

@Bloh09

Bloh09 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @Kev-Ball, that is really useful. I could only test on CPU here, so a run on real 32-lane hardware with a negative control that fails on exactly the taken-branch cases is the check I was missing. Much appreciated.

@kapitche

Copy link
Copy Markdown
Contributor

Tested 28b20ea merged with main 98fa503 on Linux (Python 3.12.16): pass - tests/semantic/test_wave64_emulate_opt.py 23 OK, tests/test_docs_*.py (10 files) OK; negative control: upstream/main tools/wave64_emulate_opt.py with the new test: 4 failures (the four taken-branch subtests: 2 cmp/branch pairs x 64 and 128 threads, as the docs row says); the not-taken cases pass on main as expected. I read the sub-CFG exit-node change and the new design.md row and found no issue. Not GPU-verified, as the PR states.

@Bloh09

Bloh09 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @kapitche for running the suite and the negative control against main, and for reading the exit-node change. Glad the four taken-branch subtests fail on main and pass here as the docs row describes.

@memorypressure

Copy link
Copy Markdown

Verified merged with current main: the CPU coverage genuinely pins the fix — the new folded-region test passes with your optimizer and fails 122 != 1 lane 3 in all four taken-branch subcases with main's (re-run here), and the rest of the neighbourhood is green (emulate_opt 23, translate 596 in the venv, cfg_structure 18,228 graphs, docs guards). Two review notes rather than blockers: the contract row is updated but no standalone semantic .asm fixture accompanies the rule change — please add one per the translator-rule convention; and the row's phrase against the native wave64 translation oversells the new test, which compares emulated output to expected values, not to a native run. No CI checks were reported. AI-assisted: yes. Tested on Linux (RTX 5080 host, CPU-only run).

…ign.md row says what the test compares against
@Bloh09
Bloh09 force-pushed the fix/wave64-emulate-fold-exit-edge branch from 28b20ea to 30fd24a Compare November 23, 2026 16:05
@Bloh09

Bloh09 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Rebased on main. The fix itself already landed with the 4c17a68 merge, so the branch now only adds tests/semantic/fixtures/wave64_fold_scc_exit.asm (run by test_folded_region_scalar_exit_fixture, fails without the fix) and rewords the design.md row: expected values, not a native run. Tests green.

@Urban225

Copy link
Copy Markdown
Contributor

Tested 30fd24a on AMD Radeon RX 7900 XTX (RDNA3, subgroup 32..64), AMD proprietary 26.10.1, Windows 11, MSVC 19.44: no regression against main (7e4992d) on the same machine.

main 7e4992d this PR
run_gpu_tests.py, native wave64 222/239, 16 skipped, 1 fail identical
run_gpu_tests.py, LEONIDA_W64_EMULATE=1 222/239, 16 skipped, 1 fail identical
ctest 264/269 identical, the same 5 failures

The failures are the same on main, so none is from this PR: ms_wave_info_s3 in both GPU runs, and vk_queue_query_sync, d3d12_vulkan_device, d3d12_texture_tiles, d3d12_indirect_dispatch_count (#6162), d3d12_pipeline_library_host in ctest.

This is a regression check on AMD at 32-wide and 64-wide; I did not check whether any GPU fixture reaches the folded-EXECZ case this PR fixes.

AI-assisted (Claude wrote the test script and read the logs); the runs are from my machine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.