Skip to content

D3D12.X: a folded indirect dispatch of a split program runs all its groups - #1428

Open
lukastaro wants to merge 6 commits into
xcl-dev:mainfrom
lukastaro:d3d12x-fold-large-dispatches
Open

lukastaro wants to merge 6 commits into
xcl-dev:mainfrom
lukastaro:d3d12x-fold-large-dispatches

Conversation

@lukastaro

@lukastaro lukastaro commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Part of #505. A follow-up to the fold of dispatches past 65 535 groups in X, which reached main with the world-main integration branch (fe650b66, 82daf31d, with @theaustinayers' bound on the groups in 9cc53f15 and the indirect pass opt-in behind XCL_CLAMP_INDIRECT=1). This branch's earlier commits are all in main now; what is left are two places where a folded dispatch still did not run the groups the console runs.

What is in it (one commit on top of main, 7b842cc)

  • A split program's indirect dispatch (found by @thehollowedone in the review of c4252f1): a Dispatch-only ExecuteIndirect of a split compute program, once its indirect chain is ready, never reached the clamp pass. The chain's slicer took min(counts, 65 535), so of 72 512 × 1 × 1 the last 6 977 groups did not run, and whether they ran depended on whether the chain was built yet. With XCL_CLAMP_INDIRECT=1 the slicer (recomp/pso.rs) now takes the counts as the clamp pass does: folded into Y with the console's count written to the dispatch's IO_GROUP_LIMIT word, clamped, or none past the bound. It cuts the folded grid into its slabs (or the whole form's command). It runs after the bind, since it needs the io's address, and the binding is set again after it (dispatch_chain::execute_indirect, bind.rs). Without the switch nothing changes.
  • A fold with a wave-local remap in Y (HLSL path, recomp/emit.rs): a program the split wave64 form remaps in Y (for example 32 × 4 threads: two hardware groups a console group) took its fold row from the hardware's gid.y; the console's row is gid.y / ratio. Before, each console group of a folded dispatch ran with half its threads, and the second row's groups ran as others. A direct Dispatch reaches this: dispatch_chain::remapped_grid scales the folded grid's Y by the ratio and keeps the remapped program.
  • The fold rule is one HLSL function, recomp::FOLD_GROUPS_HLSL, which the clamp pass (clamp.rs) and the slicer both include.
  • Tests (GPU): split_indirect_slicer_folds_as_the_clamp_pass checks the slicer's commands and io word for folded, whole-form, within-limit, non-count (1.0f) and zero counts, and with the fold off; it fails on the previous slicer. gpu_folded_dispatch_with_a_remap_in_y_runs_each_console_group_once counts each console group's threads atomically (128); it gives 64 on the previous emitter.

The translated compute HLSL changes for programs remapped in Y, so their cached translations are made again once.

Tested

  • NVIDIA GeForce RTX 5060 Ti (driver 621.40), Intel Core i7-14700K, Windows 10 22H2 (19045), Rust 1.100.0, DXC 1.9 (XCL_DXC_DIR); tests in debug, smoke runs in release.
  • The fold tests: split_indirect_slicer_folds_as_the_clamp_pass, gpu_folded_dispatch_with_a_remap_in_y_runs_each_console_group_once, gpu_compute_folded_dispatch_runs_each_console_group_once, indirect_group_counts_are_folded_or_clamped_on_the_gpu, dispatch_thread_limits_seed_compute_exec_for_native_and_remapped_groups: 5 passed.
  • cargo test -p xcl --lib -- --test-threads=4 aborts with 0x80004005 on this machine, on main 86e86fc as on this branch, at the same place (list_x tests, then sparse tests when list_x is skipped; list_x alone passes 113 of 113 on both). Split that way: list_x 113 passed on both; the rest 1 794 passed and 0 failed on this branch before the abort, 1 795 passed and 0 failed on main. No failures are new.

Regression run

main:

xcl-smoke v1
commit: 86e86fcb33f94fa5d0c809d9b50af7b84bf49cce
gpu: NVIDIA GeForce RTX 5060 Ti
title: eccf25ce
seconds: 60
exit: 0x0
frames shown: 1553 (PresentX 1553)
presents per 2 s (last 3): 60 61 61
device removals: 0
crashes: 0
peak commit: 16212 MB

PR:

xcl-smoke v1
commit: 7b842ccec22282ad89eb7e5c3364c28d6fb36717
gpu: NVIDIA GeForce RTX 5060 Ti
title: eccf25ce
seconds: 60
exit: 0x0
frames shown: 1593 (PresentX 1593)
presents per 2 s (last 3): 60 60 61
device removals: 0
crashes: 0
peak commit: 16196 MB

The 60 s stay in the game's menus and loading screen. The PR's first run after the build had 1 289 frames and a peak commit of 26 982 MB (its shader caches were made new for the changed translator source); the block above is the run right after it, with no change in between.

Not tested

  • The slicer's fold in the retail game: XCL_CLAMP_INDIRECT is off by default on main, and the smoke runs stay before the world.
  • A ready split chain end to end with a folded count (slicer, pieces and whole form writing every group's output once): the test checks the slicer's commands and io word, and the pieces take their group ids as for a direct dispatch.
  • AMD and Intel GPUs.

AI use

  • Claude Code (Claude Opus 5.5): merged main, wrote the fix, the tests and this description; the runs above were made on the hardware named. The slicer change follows the candidate @thehollowedone posted in the review.

🤖 Generated with Claude Code

https://claude.ai/code/session_016SP4yAshKooAmiGUcvcSzU

@lukastaro
lukastaro marked this pull request as ready for review November 24, 2026 15:55
@Aniseto

Aniseto commented Nov 24, 2026 •

Copy link
Copy Markdown

Ran the two new tests at e29892e (re-run after the head moved again; earlier runs were a902d3e and cf6cc59): Environment: Windows 11 Pro build 26200 x64, NVIDIA GeForce RTX 5070 Ti (Blackwell, wave32 only, 16 GB) driver 32.0.16.2124, Intel Core i5-12400F, 64 GB RAM, rustc 1.100.0 (0ef1bc386 2026-11-09) MSVC 14.44.35207, DXC 1.9.2609.5, debug build. XCL_ADAPTER=nvidia cargo test -p xcl --lib gpu_compute_folded_dispatch 1 passed; 0 failed; 0 ignored (exit 0) XCL_ADAPTER=nvidia cargo test -p xcl --lib indirect_group_counts_are_folded 1 passed; 0 failed; 0 ignored (exit 0) Both still pass on the new head: gpu_compute_folded_dispatch_runs_each_console_group_once runs a real folded dispatch on the GPU here and each console group runs exactly once, and indirect_group_counts_are_folded_or_clamped_on_the_gpu passes too. Not tested: a title that actually issues more than 65 535 groups in X (no unpacked title here), RDNA2/RDNA4 and Intel GPUs, Wine, release profile, native wave64. AI-assisted (OpenCode), model: DeepSeek V4.1 Flash 1017 - built the PR's head commit from a clean tree and ran the tests on this machine; no local changes were made.
Update (25/11, after the head moved to 7dbd80c): re-ran the same two tests at the new head, which also unfolds a folded dispatch in the direct translators.

Environment unchanged: Windows 11 Pro build 26200 x64, NVIDIA GeForce RTX 5070 Ti (Blackwell, wave32 only, 16 GB) driver 32.0.16.2124, Intel Core i5-12400F, 64 GB RAM, rustc 1.100.0 MSVC 14.44.35207, DXC 1.9.2609.5, debug build.

XCL_ADAPTER=nvidia cargo test -p xcl --lib gpu_compute_folded_dispatch
1 passed; 0 failed; 0 ignored      (exit 0)

XCL_ADAPTER=nvidia cargo test -p xcl --lib indirect_group_counts_are_folded
1 passed; 0 failed; 0 ignored      (exit 0)

Both still pass on 7dbd80c. The PR is currently in conflict against main 1a0bbe3; this run is on the exact head commit in a detached worktree, not on a rebased tree.

Not tested (same gaps as above): a title that actually issues more than 65 535 groups in X, RDNA2/RDNA4 and Intel GPUs, Wine, release profile, native wave64.

AI-assisted (OpenCode), model: DeepSeek V4.1 Flash Free - checked out the new head in a detached worktree, rebuilt, ran the tests, and updated this report; the worktree was not modified; no game data was used.

@DarkPanda69

DarkPanda69 commented Nov 24, 2026 •

Copy link
Copy Markdown

Update for head 7dbd80c: same result. Applied on main 1a0bbe3, gpu_compute_folded_dispatch_runs_each_console_group_once passes on the RX 9070 XT (native wave64) and the RTX 3060. Whole gpu:: filter: RX 9070 XT 630 passed, 2 failed (the #2115 fuzz seeds, same on main); RTX 3060 632 passed, 0 failed.


AMD run, which this PR lists as not tested. Updated for head 280164a (earlier runs on a902d3e, cf6cc59 and e29892e, same result).

Tested: pass, head 280164a applied on main 689f2db, debug, Rust 1.100.0, Windows 11 Pro 26200, Ryzen 7 5800X, DXC 1.9.2602.17.
cargo test -p xcl --lib -- gpu::recomp --test-threads=4:

  • AMD RX 9070 XT (RDNA4), driver 32.0.32029.2010, native wave64: 262 passed, 0 failed, 18 ignored. gpu_compute_folded_dispatch_runs_each_console_group_once ok. The 6 SKIPPED lines (per-lane form refused for some f16/f32 programs) are the same on main.
  • NVIDIA RTX 3060, driver 32.0.16.1088: 262 passed, 0 failed, 18 ignored. Same test ok; the SKIPPED lines are the same as on main.

On a902d3e, cargo test -p xcl --lib -- d3d12x --test-threads=4 also passed on both (145 passed, 0 failed, 1 ignored); not rerun since.

Not tested: RDNA2; the upper-boundary case from the review above beyond the PR's own tests; the whole workspace suite; a title.

AI use: Claude Code (Claude Opus 5.5) ran the tests on this machine and wrote this report.

@nnonno91

Copy link
Copy Markdown

Indirect dispatch fold disagrees with the CPU at the upper boundary

On a902d3e3e02e497d8d30b37cdccd89ba9585feb1, the existing fold tests pass on my RTX 5090, including the 72,512-group case. I extended indirect_group_counts_are_folded_or_clamped_on_the_gpu to compare the GPU setup pass’s readback with bind::fold for three additional X counts, with Y and Z both set to 1. The test reads the generated counts without submitting them as a dispatch.

Requested X CPU output (X, Y, Z) GPU output (X, Y, Z)
4,294,836,225 (65,535²) (65535, 65535, 1) (65535, 65535, 1)
4,294,836,226 (65535, 1, 1) (65535, 65536, 1)
4,294,967,295 (u32::MAX) (65535, 1, 1) (65535, 0, 1)

The shader in clamp.rs can produce a row count above the D3D12 limit, and the addition in its ceiling division wraps for u32::MAX. In a temporary local test I computed the ceiling using division and remainder, and kept the existing clamp path when the row count exceeded 65,535. The extended test then passed, including agreement on the stored fold limit.

Tested

  • RTX 5090 (driver 617.42), Ryzen 7 9800X3D, Windows 11 25H2 (26200.9974), Rust 1.100.0 MSVC, DXC 1.8.2502.11.
  • cargo test --locked -p xcl --lib indirect_group_counts_are_folded_or_clamped_on_the_gpu -- --nocapture --test-threads=1 on the temporary fixture. The PR shader failed the two out-of-range comparisons. The local correction passed all six cases.

Not tested

  • Retail-title behavior with the local correction.

AI use

  • OpenAI Codex (GPT-6, exact model variant unavailable) ran the tests and drafted this report.

@oz-stanislav-zhukov

oz-stanislav-zhukov commented Nov 24, 2026 •

Copy link
Copy Markdown

Test report from the retail game, GTA VI 1.0.2.1. With this PR applied, the world-loading GPU hang did not show up in one run; before it, the hang happened in both runs I had on the same machine. Correction (edited): the PR's per-dispatch report lines never appeared in that run, so I can't attribute the missing hang to it. See below.

Tested at a902d3e, cherry-picked onto main b7aa9f3 together with other open PRs (local branch, commit 5ab018c): #751, #688, #1123, #488, #789 (ported by hand onto the current sparse.rs), #1195, #1323, and two local xg CopyFromSubresource fixes. The only conflict was with #1323 in bind.rs / mod.rs, where I kept both: fold first, then the culprit markers around the dispatch.

Hardware: NVIDIA GeForce RTX 5060 Ti 16 GB, driver 621.24, Agility SDK 1.620.2. CPU i7-14700KF, 64 GB RAM, Windows 10 22H2 (19045). Rust 1.88.0, release build with line tables. Game runs used XCL_DRED=1 XCL_PSO_WAIT_MS=50 XCL_ACTIVITY=1; the run with this PR also had XCL_GPU_CULPRIT=1.

Before (main 930e8b4 + parts of the same stack, without #1195/#1428/#1323; two runs):

  • DXGI_ERROR_DEVICE_HUNG (0x887A0006) at 112 s and 183 s.
  • The D3D12.X: the GPU-wait watchdog says where a chain of waits ends #1123 wait chain ended at a queue that was executing (q4 end=signal in the first run, q2 end=signal in the second).
  • DRED breadcrumbs: one list was partly done (13 of 22 operations), its current operation an ExecuteIndirect between dispatches and barriers. All other lists had 0 operations done. The page fault was at VA 0x0.

With this PR (one run):

  • indirect dispatches past 65535 groups a dimension are folded or clamped on the GPU logged at 96 s. That line only says the pass was set up.
  • Neither … indirect dispatches folded so far nor … had group counts clamped so far was ever logged. As far as clamp::report saw, no dispatch was folded or clamped in this run.
  • No device removal and no GPU wait chain line for the whole run.
  • The run then ended in the game's own code, not on the GPU:
    • 0x80000003 at game_scarlett_master.exe+0x4da6315 (called from +0x9dff91) at 132 s;
    • then 0xc0000005 reading 0xffffffffffffffff at +0x50705fc at 147 s.
  • Since nothing was folded or clamped, these crashes are probably not caused by this PR. The missing hang may be run-to-run variation or a result of the other changes. One run is not enough to say.

Update, a second run with this PR (same build, no DRED; XCL_GPU_CULPRIT=1 XCL_PSO_WAIT_MS=50):

  • 1 indirect dispatches folded so far (the latest of 72604 groups in X) at 142 s. That is the same size as the counts in the description (72 512 / 75 072).
  • No device removal and no GPU wait chain line afterwards.
  • The run ended at 157 s, again in the game's 0x80000003 at +0x4da6315.
    • That check translates a resource's virtual pointer (the 0x50000000/0x60000000 bases) through the resource's map. The pointer it got was 0xae99cec5ab88357b, which is garbage, so the resource's contents were not what the game expected.
    • In these runs 8–14 thousand dispatches and ~30 thousand draws were skipped while pipelines were rebuilt: this PR changes the compute prelude, so the whole compute translation cache is made again. Before the change, the count was 861. Missing work is a likely cause, but I haven't shown it.
  • So: the fold did happen on the GPU at the point where the hang used to be, and the hang was not seen. The later crash is not shown to be caused by this PR.

Unit tests: cargo test --release -p xcl --lib -- sparse late_release bind culprit clamp --test-threads=4: 41 passed, 0 failed, 1 ignored. Three GPU tests printed SKIPPED with "no GPU" / "no GPU or DXC" in this run, including clamp::tests::indirect_group_counts_are_folded_or_clamped_on_the_gpu, so that test was not covered here.

Not tested:

AI use: run, log analysis and this report by Claude Code (Claude Opus 5.5); posted at the request of the person running the tests.

gustavsi added a commit to gustavsi/xcl that referenced this pull request Nov 24, 2026
…#1395 in-place vtables

Integrates 16 upstream PRs (xcl-dev#1380, xcl-dev#1383, xcl-dev#1384, xcl-dev#1395, xcl-dev#1398, xcl-dev#1400,
xcl-dev#1404, xcl-dev#1405, xcl-dev#1419, xcl-dev#1420, xcl-dev#1421, xcl-dev#1423, xcl-dev#1424, xcl-dev#1427, xcl-dev#1428, xcl-dev#1429)
on top of the Linux/Proton fork, plus three Proton/vkd3d-proton fixes
caught during verification:
- Recompiler (xcl-dev#1428): flatten IO_GROUP_LIMIT early-return in compute
  shaders so vkd3d-proton v3.1 dxil-spirv accepts the emitted CFG.
- D3D12.X (xcl-dev#1395 + xcl-dev#867): skip UnadoptGuard on in-place-patched vtables
  and restore native vtables in runner::submit_list when a prior test
  adopted the singleton ID3D12Device.
- Tests: match Wine centered default in window_position_modes.

Verified under GE-Proton11-14 (RX 9060 XT / RADV):
- gpu_sparse_vram_descriptors_buffers_and_xmem + gpu_valu_float_and_int
  + window_position_modes: 3 passed, 0 failed
- Broad sweep (present, real, sparse, clamp, dstorage, gpu_valu,
  gpu_typed_buffer): 82 passed, 0 failed, 1 ignored, 0 skipped
- 2.5 min retail title run (XCL_MEM_LIMIT=12G): 3,000+ frames at 30.0
  fps, 6.0-6.1 GB flat committed RAM, 6.4 GB local VRAM, 0 DS failures.
gut0to

This comment was marked as duplicate.

@lukastaro
lukastaro force-pushed the d3d12x-fold-large-dispatches branch from a902d3e to cf6cc59 Compare November 24, 2026 16:54
@lukastaro

Copy link
Copy Markdown
Contributor Author

Thanks @nnonno91 and @gut0to, fixed in cf6cc59 (folded into the one commit): the GPU pass now computes the row count without the addition that wrapped, and folds only when it stays within 65 535, as bind::fold does on the CPU; otherwise it clamps. The test covers 65 535², 65 535² + 1 and u32::MAX and checks each case against bind::fold; it fails on the previous shader.

Thanks also @Aniseto and @DarkPanda69 for the NVIDIA / AMD test runs, and @oz-stanislav-zhukov for the run on the title. Smoke run and the whole suite are redone on the new head (numbers in the description).

AI use: Claude Code (Claude Opus 5.5) wrote this.

@DavidM1911

Copy link
Copy Markdown
Contributor

Verification on RTX 3060 Ti (Windows 11), branch merged with current main:

  • cargo test -p xcl --lib: all passed, 0 failed, ~21 ignored.

Thanks!

@lukastaro
lukastaro force-pushed the d3d12x-fold-large-dispatches branch from cf6cc59 to e29892e Compare November 24, 2026 17:32
gustavsi added a commit to gustavsi/xcl that referenced this pull request Nov 24, 2026
…direct DXIL)

Brings in upstream xcl-dev#680 (descriptor-heap memory windows without per-access
switches, with switch fallback) and xcl-dev#1426 (direct RDNA2 -> DXIL backend
behind XCL_DIRECT_DXIL=1 / XCL_DIRECT_DXIL=all, bypassing HLSL and DXC).
Retains xcl-dev#1398 no-GVN retry, xcl-dev#1410 wave64 logging, and xcl-dev#1428 folded X
dispatch group limit alongside xcl-dev#680 and xcl-dev#1426.
@lukastaro

Copy link
Copy Markdown
Contributor Author

Added "Part of #505" to the description, since this PR is about a stop at the world load (#1833) and has no goal:world-load label yet. On #675, @qcdaark found that the hang there is a different one (the fold path runs on that card, the hang stays), so this PR does not name #675 as fixed.

AI use: Claude Code (Claude Opus 5.5) wrote this.

The console runs up to 2^32 - 1 thread groups a dimension; D3D12 takes
65 535, and past that a dispatch is undefined. On an NVIDIA RTX 5060 Ti a
retail game's world loading hung the GPU (DXGI_ERROR_DEVICE_HUNG,
0x887A0006) about 100 s in, every run: the only unfinished work was an
ExecuteIndirect of one loop-free compute program (found with the dispatch
markers of xcl-dev#1323), and its arguments, written by an earlier dispatch, were
72 512 x 1 x 1 and 75 072 x 1 x 1 groups.

A dispatch of more than 65 535 groups in X with 1 in Y now runs as
65 535 x ceil(n / 65 535) groups. The console's count goes into a new io
word (IO_GROUP_LIMIT, in the trap-temp range like IO_UMA_BASE_HI; 0 when
not folded), and every translated compute program takes
gid.x + gid.y * 65 535 as its group in X when the word is set, its Y as 0,
and returns at once in the groups at or past the count. A dispatch that
cannot be folded (two dimensions past the limit) is clamped and logged.

- Dispatch and console-recorded dispatches: the counts are known on the CPU
  (bind::fold, also in console_list).
- ExecuteIndirect of one dispatch: the counts are only on the GPU. A
  one-thread pass (clamp.rs) reads them, writes the counts to dispatch into
  a slot of XCL's buffer and the console's count into the dispatch's io
  (folding only when the rows stay within 65 535, as bind::fold does),
  then the dispatch reads its arguments from the slot. bind_abi now returns
  what it bound so the binding can be set again after the pass.

The translated compute HLSL changes (a few lines in the prelude), so
cached translations and DXIL of compute programs are made again once.

New tests: a folded dispatch runs each console group once and none past
its count (GPU; fails without the change from group 65 535 on), the
indirect pass folds / clamps / leaves counts as they are (GPU), and the
folding rule (unit). runner::device() gives tests the runner's device: a
test making its own device first left the Agility SDK unappliable and the
GPU tests after it skipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ivall

ivall commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator

A gap I found while merging this for a test on AMD RDNA4: the fold is only undone on the HLSL path. IO_GROUP_LIMIT is read in gpu/recomp/emit.rs and nowhere under gpu/dxil (head 280164a); the direct translator takes the group id as the hardware gives it (gpu/dxil/kernel.rs, group_id). bind.rs and clamp.rs fold for every translated compute pipeline, so with XCL_DIRECT_DXIL=1 (and for the programs #2120 sends to the direct translator by default) a folded dispatch would run with the group ids of the folded grid instead of the console's. Before this change such a dispatch was clamped: groups were missing, but the ones that ran had the right ids.

What is needed: the same unfolding in the direct translator's group and thread ids, with a GPU test like gpu_compute_folded_dispatch on that path, or no fold for a pipeline built by it. This is from reading the code; I did not run a folded dispatch on the direct path.

It also conflicts in bind.rs with #2080 (two hunks, both easy).

Tested: 9633138 + #2245's test fix + #2180 + #2029 + #1782 + this, AMD RDNA4, Windows, DXC 1.8.2502.11, debug, cargo test --workspace --no-fail-fast -- --test-threads=4: 1250 passed, 3 failed, 46 ignored, 7 SKIPPED. The 3 failures are on main there too (fuzz_validate_and_gpu_1 and _3, #2115; gpu_image_get_resinfo_past_last_level). With XCL_DIRECT_DXIL=all, cargo test -p xcl --lib gpu::: 629 passed, the same 3 failed, 22 ignored.

AI use: Claude Code (Claude Opus 5.5) read the code, ran the tests and wrote this on the maintainer's behalf.

gustavsi added a commit to gustavsi/xcl that referenced this pull request Nov 25, 2026
gustavsi added a commit to gustavsi/xcl that referenced this pull request Nov 25, 2026
, xcl-dev#2333, and UnadoptGuard test submits

Assisted-by: Antigravity (Gemini 4 Neon)
gustavsi added a commit to gustavsi/xcl that referenced this pull request Nov 25, 2026
gustavsi added a commit to gustavsi/xcl that referenced this pull request Nov 25, 2026
, xcl-dev#2333, and UnadoptGuard test submits

Assisted-by: Antigravity (Gemini 4 Neon)
gustavsi added a commit to gustavsi/xcl that referenced this pull request Nov 26, 2026
…DispatchMesh & ExecuteIndirect)

Enables two-pass mesh execution for DispatchMesh and ExecuteIndirect
(superseding xcl-dev#724), paired with xcl-dev#541 (MS in AS slot). Reconciles
runner.rs, bind.rs, and console_list.rs with xcl-dev#2118, xcl-dev#2404, and xcl-dev#1428.

Assisted-by: Antigravity (Gemini 4 Neon)
@DavidM1911

Copy link
Copy Markdown
Contributor

Re-verification on RTX 3060 Ti (Windows 11): still a merge conflict with current main on the new head — needs another rebase before it can be tested.

@Prime1997 Prime1997 mentioned this pull request Nov 26, 2026
koboshchan pushed a commit to koboshchan/xcl that referenced this pull request Nov 26, 2026
…dev#1428)

Port xcl-dev#1428's >65,535 X->Y compute dispatch folding onto amd-dev and integrate it directly into bind.rs's guard_dispatch_args pass (avoiding a second indirect compute pass):

- Add IO_GROUP_LIMIT (slot 113) and FOLD_X (65,535) in gpu/recomp/mod.rs and unfold gid.x + gid.y * 65535 with early group exit past the count in HLSL (recomp/emit.rs), per-lane IR (recomp/lower.rs), and Direct DXIL (dxil/kernel.rs).
- Fold direct Dispatch and console_list dispatches via bind::fold(x, y, z) so 1D grids like 2560x1440 final gather's 115,200 groups run as 65,535 x 2 instead of being clamped to 65,535.
- Extend GUARD_ARGS_HLSL / guard_dispatch_args to fold >65,535 x 1 x z indirect dispatches and write IO_GROUP_LIMIT into a dedicated compute io buffer (u4), batching [UAV, transition] and [transition, UAV] into single ResourceBarrier calls.

Assisted-by: Antigravity (Gemini 4 Neon High)
main reworked the ABI binding (bind_abi_with_root_resolved, dispatch_chain,
IO_THREAD_LIMIT, the dispatch remap). The fold goes through the new shape:

- Dispatch / DispatchX: a grid past 65 535 in X with 1 in Y is folded where
  main skipped it; any other grid past the limit is still skipped. The count
  reaches the io through bind_compute_abi_resolved (prepared_abi_io).
- ExecuteIndirect: the clamp pass runs before the binding is set
  (bind_abi_prepared's `before`, with the io's GPU address), so no rebind is
  needed; only for Dispatch-only signatures. Bound / rebind are gone.
- Console list replay: a grid that cannot be folded is skipped instead of
  failing the replay.
- HLSL: xcl_gid holds the console's group ids (a remapped axis divided by its
  ratio), folded or not; the SGPRs and the thread limits read it.
- Direct DXIL: the fold gate leaves from the guarded prologue; the thread
  limits use the folded group in X.
- lower_dxil test: the first branch is now the group gate, the entry
  whole-wave branch the second.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016SP4yAshKooAmiGUcvcSzU
@lukastaro

Copy link
Copy Markdown
Contributor Author

Merged current main (b937fba) in c4252f1. main reworked the ABI binding, so the fold now goes through the new shape: Dispatch/DispatchX fold where main skipped the grid (other grids past 65 535 are still skipped), the indirect clamp pass runs before the binding is set (no rebind; Dispatch-only signatures only), and the HLSL/direct translators use the folded group ids for main's thread limits and the remap axis. Tests on an RTX 5060 Ti: the fold/clamp tests pass; the whole suite shows the same failures as main on this machine and no new ones. The description is updated.

AI use: Claude Code (Claude Opus 5.5) wrote the merge and this comment.

@thehollowedone

thehollowedone commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Review of head c4252f1: a ready split-compute pipeline appears to bypass the new fold for a Dispatch-only ExecuteIndirect.

bind.rs tries dispatch_chain::execute_indirect before the clamp/fold pass and returns on Ok(true). Once the indirect chain is ready, its slicer starts with min(args.Load3(0), 65535). For [72_512, 1, 1], both its piece commands and whole fallback therefore cover at most 65,535 groups; the last 6,977 do not execute. While that chain is unready, the same call falls through to this PR's fold path. This is a source-level finding; I have not reproduced the ready-chain case on the GPU.

The focused gpu_compute_folded_dispatch_runs_each_console_group_once and indirect_group_counts_are_folded_or_clamped_on_the_gpu tests each passed 1/1 on an RTX 3080 Ti (621.35), Windows 11 build 26300, with XCL_ADAPTER=3080, using cargo test --offline --locked -j 4 -p xcl --lib <test name> -- --test-threads=1. They test the translator and clamp pass separately, but do not take the ready-chain route above.

Could the split indirect path consume the same folded grid and original-count ABI value before slicing, or route an over-limit command through the folded whole path? A regression should make the indirect split variant ready, submit [72_512, 1, 1], and verify every output group through 72,511 exactly once. This matters before merge because the result currently depends on whether pipeline preparation has finished.

AI use: Codex (GPT-6.2 Sol) checked the routing and ran the focused GPU tests; Codex (GPT-6.2 Astra) independently traced the split path.

Local candidate follow-up. I made the slicer use the same GPU fold rule as the ordinary indirect path, write the original X count into this dispatch's IO, and partition the resulting physical grid for either its split pieces or whole fallback. The clamp opt-out retains valid split commands and forwards over-limit dimensions unchanged to the whole tail. The new GPU readback test failed on the unchanged head (0 passed, 1 failed: third slab empty for 72,512 × 1 × 1) and passed with the candidate. Six focused tests passed, 0 failed/ignored/skipped, including the existing translator, clamp, and scratch/lifetime controls.

With the three previously documented aborting UMA tests excluded, cargo test --offline --locked -j 4 --workspace --no-fail-fast -- --test-threads=4 plus the same three --skip filters gave 2,142 passed, 2 failed, 48 ignored, 25 GPU skip notices on the candidate; unchanged c4252f1 gave 2,140 passed, 3 failed, 48 ignored, 25 skip notices. Both failed direct_msaa_loads_precede_get_dimensions and console_mesh_caches_hlsl_compute_pass_in_memory_and_on_disk. The base alone also failed cross_queue_cycle_and_same_queue_fifo_do_not_deadlock in this run; I do not attribute that difference to the candidate. The new test accounts for one added pass. This is an uncommitted local patch. A single ready-chain-to-final-output test and a retail run remain untested.

Candidate diff (six files)
diff --git a/README.md b/README.md
index c0e02c27..80f5c70e 100644
--- a/README.md
+++ b/README.md
@@ -149,7 +149,7 @@ A gamepad is recommended ([Controls](#controls)). The game folder is never modif
 |---|---|---|---|
 | **Shader recompiler** | ✅ | RDNA2 → HLSL → DXIL: VS, PS, CS, mesh (NGG), GS; atomics, LDS, scratch, images, samplers incl. static ones, wave ops, ray-tracing instructions; structured control flow; parallel DXC, disk cache | 26 698 / 26 698 programs of the retail pack; 0 DXC errors on random samples; per-instruction GPU tests |
 | **Pipelines** | ✅ | PSOs from console shaders: VS+PS, CS, MS+PS, VS+GS+PS; root signature with the shaders' static samplers; non-blocking creation – a pipeline whose shaders are not compiled yet gets a stand-in at once and is built in the background | GPU tests drawing the game's own VS / PS pairs, also built in the background |
-| **D3D12.X compute** | ✅ | console device slots, console descriptor heaps (T# / V# / S#), buffers at their console addresses, compute command lists recorded in the console format and replayed (tables, barriers, clears, copies) | the game's BVH builder and FSR 4 record and run through XCL |
+| **D3D12.X compute** | ✅ | console device slots, console descriptor heaps (T# / V# / S#), buffers at their console addresses, compute command lists recorded in the console format and replayed (tables, barriers, clears, copies). Split pipelines can fold single-row indirect dispatches past 65,535 groups in X into multiple rows. | the game's BVH builder and FSR 4 record and run through XCL |
 | **D3D12.X graphics** | ✅ | device, resources and heaps (also placed in title memory), pipelines; the title's graphics command lists – draws, indirect draws, graphics root arguments, barriers, copies, clears – and command lists recorded by console code, replayed; `PresentX` and frame pacing into an XCL window | Minecraft Preview plays its worlds (millions of draws, none skipped); Fortnite and XDefiant draw their screens |
 | **Textures** | ✅ | GFX10 tiling (all 14 2D swizzle modes, the 6 3D thick modes, linear), mip chains with mip tail, arrays, cubes and 3D textures → PC textures; supported GPU-written title subresources copy back before their writer queue's title fence becomes visible | 912 / 912 entries detiled in the tested retail archive; GPU upload bit exact in test fixtures |
 | **Ray tracing** | ✅ | BLAS / TLAS built on the GPU by the game's own XboxBvhBuilder; RDNA2 BVH node format; BVH intersection instructions emulated in shaders | GPU traversal = brute force reference; the game's builder output checked on the GPU |
diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs
index 4052369c..4efaf8df 100644
--- a/crates/xcl/src/gpu/recomp/mod.rs
+++ b/crates/xcl/src/gpu/recomp/mod.rs
@@ -222,6 +222,19 @@ pub const IO_UMA_BASE_HI: usize = 112;
 pub const IO_GROUP_LIMIT: usize = 113;
 /// Groups a folded dispatch has in X.
 pub const FOLD_X: u32 = 65_535;
+
+/// GPU counterpart of `bind::fold` for both indirect argument writers.
+pub(crate) const INDIRECT_GROUPS_HLSL: &str = r#"
+uint3 indirect_groups(uint3 g, out uint folded) {
+    folded = 0;
+    uint rows = g.x / 65535u + (g.x % 65535u != 0u ? 1u : 0u);
+    if (g.x > 65535u && g.y == 1u && g.z <= 65535u && rows <= 65535u) {
+        folded = g.x;
+        return uint3(65535u, rows, g.z);
+    }
+    return min(g, 65535u);
+}
+"#;
 /// io slots of a `DispatchX` with thread dimensions (flag 0x20): the thread count of each axis
 /// when it is not a whole number of groups (0: the last group is whole), so the program can leave
 /// the lanes past it out of EXEC. Written by D3D12.X and read by both compute backends.
diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs
index 2200c612..2416d22c 100644
--- a/crates/xcl/src/gpu/recomp/pso.rs
+++ b/crates/xcl/src/gpu/recomp/pso.rs
@@ -1569,10 +1569,11 @@ pub(crate) fn dispatch_command_signature(dev: &ID3D12Device) -> Result<ID3D12Com
 }
 
 const INDIRECT_SLICER: &str = r#"
-#define RS "RootConstants(num32BitConstants=2, b0), SRV(t0), UAV(u0)"
-cbuffer C : register(b0) { uint rounds; uint most; };
+#define RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0), UAV(u1)"
+cbuffer C : register(b0) { uint rounds; uint most; uint limit_offset; uint clamp_groups; };
 ByteAddressBuffer args : register(t0);
 RWByteAddressBuffer cmds : register(u0);
+RWByteAddressBuffer io : register(u1);
 void put(uint r, uint3 n, uint3 o) {
     uint at = r * 256;
     cmds.Store4(at, uint4(n, 0));
@@ -1582,15 +1583,20 @@ void put(uint r, uint3 n, uint3 o) {
 [RootSignature(RS)]
 [numthreads(1, 1, 1)]
 void main() {
-    uint3 g = min(args.Load3(0), 65535);
+    uint folded;
+    uint3 original = args.Load3(0);
+    uint3 g = indirect_groups(original, folded);
+    // With the clamp disabled, the whole command forwards the guest's original dimensions.
+    bool passthrough = clamp_groups == 0 && any(g != original);
+    io.Store(limit_offset, clamp_groups != 0 ? folded : 0);
     uint3 s;
     s.x = min(g.x, max(most, 1));
     s.y = s.x == g.x ? min(g.y, max(most / max(g.x, 1), 1)) : 1;
     s.z = s.x == g.x && s.y == g.y ? min(g.z, max(most / max(g.x, 1) / max(g.y, 1), 1)) : 1;
-    uint3 c = (g + s - 1) / s;
+    uint3 c = (g + s - 1) / max(s, 1u);
     bool partial = any(g == 0) ? false : c.x > rounds || c.y > rounds / max(c.x, 1) || c.z > rounds / max(c.x * c.y, 1);
     uint r = 0;
-    if (!partial && all(g != 0))
+    if (!passthrough && !partial && all(g != 0))
         for (uint oz = 0; oz < g.z; oz += s.z)
             for (uint oy = 0; oy < g.y; oy += s.y)
                 for (uint ox = 0; ox < g.x; ox += s.x) {
@@ -1599,7 +1605,7 @@ void main() {
                 }
     for (; r < rounds; r++) put(r, 0, 0);
     uint at = rounds * 256;
-    cmds.Store3(at, partial ? g : 0);
+    cmds.Store3(at, passthrough ? original : (partial ? g : 0));
 }
 "#;
 
@@ -1613,7 +1619,8 @@ fn indirect_slicer(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12Pip
     if let Some((_, rs, pso)) = made.as_ref().filter(|m| m.0 == windows::core::Interface::as_raw(dev) as usize) {
         return Ok((rs.clone(), pso.clone()));
     }
-    let dxil = super::dxc::compile(INDIRECT_SLICER, "main", "cs_6_0", &[])?;
+    let source = format!("{}{INDIRECT_SLICER}", super::INDIRECT_GROUPS_HLSL);
+    let dxil = super::dxc::compile(&source, "main", "cs_6_0", &[])?;
     unsafe {
         let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).map_err(|e| format!("indirect slicer root signature: {e}"))?;
         let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&rs),
@@ -1642,22 +1649,26 @@ pub(crate) unsafe fn chain_commands_storage(dev: &ID3D12Device, bytes: u64) -> O
 }
 
 pub(crate) unsafe fn record_indirect_slicer(
-    list: &ID3D12GraphicsCommandList, args: u64, rounds: u32, most: u64, out: &ID3D12Resource,
+    list: &ID3D12GraphicsCommandList, args: u64, io: u64, clamp_groups: bool, rounds: u32, most: u64, out: &ID3D12Resource,
     mut bind_pipeline: impl FnMut(&ID3D12PipelineState),
 ) -> Result<(), String> {
     let mut dev = None;
     list.GetDevice(&mut dev).map_err(|e| e.to_string())?;
     let (rs, pso) = indirect_slicer(&dev.ok_or("device")?)?;
-    let constants = [rounds, most.min(u64::from(u32::MAX)) as u32];
+    let constants = [rounds, most.min(u64::from(u32::MAX)) as u32, (super::IO_GROUP_LIMIT * 4) as u32, u32::from(clamp_groups)];
     list.SetComputeRootSignature(&rs);
     bind_pipeline(&pso);
-    list.SetComputeRoot32BitConstants(0, 2, constants.as_ptr().cast(), 0);
+    list.SetComputeRoot32BitConstants(0, constants.len() as u32, constants.as_ptr().cast(), 0);
     list.SetComputeRootShaderResourceView(1, args);
     list.SetComputeRootUnorderedAccessView(2, out.GetGPUVirtualAddress());
+    list.SetComputeRootUnorderedAccessView(3, io);
     list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
         Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }) } }]);
     list.Dispatch(1, 1, 1);
-    list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
+    // The following whole shader or first piece reads the group limit from the separate IO UAV.
+    list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
+        Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }) } },
+        D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
         Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
             pResource: std::mem::transmute_copy(out), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
             StateBefore: D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs
index dd8d1c44..f452537c 100644
--- a/crates/xcl/src/hle/d3d12x/bind.rs
+++ b/crates/xcl/src/hle/d3d12x/bind.rs
@@ -741,7 +741,7 @@ unsafe fn execute_indirect_snapshot(
     if compute && max == 1 && count_buf == 0 && signature.dispatch_only().is_some() {
         let chained = indirect_address(args, args_off_title, args_off).map_or(Ok(false), |address| {
             super::real::dispatch_chain::execute_indirect(list, raw_pso, pso, with(this, |s| s.allocator), address,
-                |root| bind_abi_with_root_resolved(this, list, raw_pso, pso, false, root, [0; 3]).map(|_| ()))
+                |root, before| bind_abi_prepared(this, list, raw_pso, pso, false, root, [0; 3], 0, Some(before)).map(|_| ()))
         });
         match chained {
             Ok(true) => {
@@ -770,8 +770,9 @@ unsafe fn execute_indirect_snapshot(
                 (args, args_off) = (a, o);
                 clamped = true;
             }
+            Ok(())
         };
-        let before: Option<&mut dyn FnMut(u64)> =
+        let before: Option<&mut dyn FnMut(u64) -> Result<(), String>> =
             if compute && max == 1 && signature.dispatch_only().is_some() { Some(&mut clamp_first) } else { None };
         bind_abi_prepared(this, list, raw_pso, pso, gfx, 0, [0; 3], 0, before)
     };
@@ -1799,7 +1800,7 @@ unsafe fn bind_abi_with_root_resolved(
 #[allow(clippy::too_many_arguments)]
 unsafe fn bind_abi_prepared(
     this: *mut c_void, list: &ID3D12GraphicsCommandList, original: usize, pso: usize, gfx: bool,
-    root: usize, limits: [u32; 3], group_limit: u32, before: Option<&mut dyn FnMut(u64)>,
+    root: usize, limits: [u32; 3], group_limit: u32, before: Option<&mut dyn FnMut(u64) -> Result<(), String>>,
 ) -> Result<usize, String> {
     #[cfg(test)]
     {
@@ -1829,7 +1830,7 @@ unsafe fn bind_abi_prepared(
     std::ptr::write_bytes(res_at as *mut u8, 0, 256);
     let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first);
     if let Some(before) = before {
-        before(va(io_at));
+        before(va(io_at))?;
     }
     let rs = (root != 0).then_some(root)
         .or_else(|| super::real::pso_root_signature_exact(pso))
diff --git a/crates/xcl/src/hle/d3d12x/clamp.rs b/crates/xcl/src/hle/d3d12x/clamp.rs
index e1827d71..5a098778 100644
--- a/crates/xcl/src/hle/d3d12x/clamp.rs
+++ b/crates/xcl/src/hle/d3d12x/clamp.rs
@@ -38,18 +38,8 @@ RWByteAddressBuffer io : register(u2);
 [numthreads(1, 1, 1)]
 void main() {
     uint3 g = src.Load3(0);
-    uint3 c;
-    uint folded = 0u;
-    // rows of 65 535 groups (a ceiling without an addition that could wrap near 2^32)
-    uint rows = g.x / 65535u + (g.x % 65535u != 0u ? 1u : 0u);
-    if (g.x > 65535u && g.y == 1u && g.z <= 65535u && rows <= 65535u) {
-        // more groups in X than D3D12 takes: folded into Y, the program told the count
-        // (as `bind::fold` does on the CPU)
-        folded = g.x;
-        c = uint3(65535u, rows, g.z);
-    } else {
-        c = min(g, 65535u);
-    }
+    uint folded;
+    uint3 c = indirect_groups(g, folded);
     io.Store(0, folded);
     if (folded != 0u) {
         uint n;
@@ -99,7 +89,8 @@ unsafe fn make(list: &ID3D12GraphicsCommandList) -> Result<Clamp, String> {
     let mut dev: Option<ID3D12Device> = None;
     list.GetDevice(&mut dev).map_err(|e| e.to_string())?;
     let dev = dev.ok_or("no device")?;
-    let dxil = crate::gpu::recomp::dxc::compile(HLSL, "main", "cs_6_0", &[])?;
+    let source = format!("{}{HLSL}", crate::gpu::recomp::INDIRECT_GROUPS_HLSL);
+    let dxil = crate::gpu::recomp::dxc::compile(&source, "main", "cs_6_0", &[])?;
     let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).map_err(|e| format!("root signature: {e}"))?;
     let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC {
         pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())),
@@ -244,6 +235,64 @@ mod tests {
         (buf, p as *mut u32)
     }
 
+    #[test]
+    fn split_indirect_slicer_preserves_folded_groups_and_io() {
+        use crate::gpu::recomp::{pso, runner, IO_GROUP_LIMIT};
+        unsafe {
+            let (Ok(dev), Ok(_)) = (runner::device(), crate::gpu::recomp::dxc::location()) else {
+                return runner::skip_test("no GPU or DXC");
+            };
+            let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE;
+            let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap();
+            let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
+            let (args, ap) = visible(&dev, 256);
+            let (io, ip) = visible(&dev, 1024);
+            let rounds = 4;
+            let tail = pso::chain_tail_offset(rounds);
+            let (commands, cp) = visible(&dev, tail + 12);
+            for (k, (grid, most, clamp, whole)) in [
+                ([72_512, 1, 1], 40_000u64, true, false), // four slabs across two folded rows
+                ([65_536, 1, 2], 1, true, true),
+                ([65_535, 2, 1], 65_535, true, false),    // native Y, no fold
+                ([65_535 * 65_535, 1, 1], 1, true, true),
+                ([u32::MAX, 1, 1], 1, true, true),
+                ([0, 1, 1], 1, true, false),
+                ([72_512, 1, 1], 40_000, false, true),
+                ([3, 2, 1], 2, false, false),
+            ].into_iter().enumerate() {
+                std::ptr::copy_nonoverlapping(grid.as_ptr(), ap, 3);
+                *ip.add(IO_GROUP_LIMIT) = 0xBAAD;
+                let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap();
+                let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap();
+                pso::record_indirect_slicer(&list, args.GetGPUVirtualAddress(), io.GetGPUVirtualAddress(), clamp, rounds, most, &commands,
+                    |pipeline| list.SetPipelineState(pipeline)).unwrap();
+                pso::restore_indirect_commands(&list, &commands);
+                list.Close().unwrap();
+                queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]);
+                let value = k as u64 + 1;
+                queue.Signal(&fence, value).unwrap();
+                let start = std::time::Instant::now();
+                while fence.GetCompletedValue() < value {
+                    assert!(start.elapsed().as_secs() < 10, "slicer did not finish");
+                    std::thread::yield_now();
+                }
+                let (limit, physical) = if clamp {
+                    super::super::bind::fold(grid).unwrap_or((0, grid.map(|n| n.min(65_535))))
+                } else { (0, grid) };
+                let slabs = if whole { Vec::new() } else { pso::dispatch_slabs(physical, most) };
+                for r in 0..rounds as usize {
+                    let (origin, size) = slabs.get(r).copied().unwrap_or_default();
+                    let at = cp.add(r * pso::CHAIN_COMMAND_BYTES as usize / 4);
+                    assert_eq!(std::slice::from_raw_parts(at, 3), size, "slab size {r}, {grid:?}");
+                    assert_eq!(std::slice::from_raw_parts(at.add(4), 3), origin, "slab origin {r}, {grid:?}");
+                    assert_eq!(std::slice::from_raw_parts(at.add(pso::CHAIN_DISPATCH_AT as usize / 4), 3), size);
+                }
+                assert_eq!(std::slice::from_raw_parts(cp.add(tail as usize / 4), 3), if whole { physical } else { [0; 3] });
+                assert_eq!(*ip.add(IO_GROUP_LIMIT), limit, "ABI group limit for {grid:?}");
+            }
+        }
+    }
+
     /// The pass writes the counts D3D12 takes into its slot: 72 512 × 1 × 1 folded into
     /// 65 535 × 2 × 1 with 72 512 in io; 70 000 × 2 × 1 clamped with 0 in io; 300 × 4 × 2 as
     /// it was.
diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs
index 690f9e7d..55cba7b9 100644
--- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs
+++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs
@@ -594,7 +594,7 @@ fn indirect_readiness(
 /// the slicer writes either bounded piece commands or the whole-form command, never a partial chain.
 pub(in crate::hle::d3d12x) unsafe fn execute_indirect(
     list: &ID3D12GraphicsCommandList, original: usize, pso: usize, allocator: usize, args: u64,
-    bind: impl FnOnce(usize) -> Result<(), String>,
+    bind: impl FnOnce(usize, &mut dyn FnMut(u64) -> Result<(), String>) -> Result<(), String>,
 ) -> Result<bool, String> {
     let Some(chain) = CHAINS.lock().unwrap().get(&pso).cloned() else { return Ok(false) };
     note_indirect_use(&chain);
@@ -629,11 +629,16 @@ pub(in crate::hle::d3d12x) unsafe fn execute_indirect(
         &chain.builder.device, list.as_raw() as usize, allocator, command_bytes,
     ).ok_or("no command buffer for split ExecuteIndirect")?;
     let first = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("first compute piece")?.clone();
-    pso::record_indirect_slicer(
-        list, args, rounds, (scratch.bytes / group).max(1), &commands.buffer,
-        |slicer| super::bind_pipeline_exact(list.as_raw(), original, slicer.as_raw() as usize),
-    )?;
-    let bound = bind(indirect.signature.as_raw() as usize);
+    let mut sliced = false;
+    let bound = bind(indirect.signature.as_raw() as usize, &mut |io| {
+        pso::record_indirect_slicer(
+            list, args, io, super::super::clamp::enabled(), rounds, (scratch.bytes / group).max(1), &commands.buffer,
+            |slicer| super::bind_pipeline_exact(list.as_raw(), original, slicer.as_raw() as usize),
+        )?;
+        sliced = true;
+        Ok(())
+    });
+    if !sliced { return bound.map(|_| false); }
     if bound.is_ok() {
         super::bind_pipeline_exact(list.as_raw(), original, indirect.whole.as_raw() as usize);
         list.ExecuteIndirect(&signature, 1, &commands.buffer,
@@ -855,9 +860,14 @@ mod tests {
             let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap();
             let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap();
             let (raw_list, allocator) = (list.as_raw() as usize, alloc.as_raw() as usize);
-            super::super::super::alloc_pool::created_on(raw_list, allocator, ty.0);
+            super::super::adopt(list.as_raw(), super::super::Kind::CommandList);
+            super::super::super::list_x::on_create(list.as_raw(), allocator, 0, ty);
             let args = pso::chain_commands_buffer(&dev, 1).unwrap();
-            assert_eq!(execute_indirect(&list, key, key, allocator, args.GetGPUVirtualAddress(), |_| Err("bind failed".into())), Err("bind failed".into()));
+            let io = pso::chain_commands_buffer(&dev, 2).unwrap();
+            assert_eq!(execute_indirect(&list, key, key, allocator, args.GetGPUVirtualAddress(), |_, before| {
+                before(io.GetGPUVirtualAddress())?;
+                Err("bind failed".into())
+            }), Err("bind failed".into()));
             let recorded = RECORDINGS.lock().unwrap().get(&allocator).unwrap()[0]._indirect_commands.clone().unwrap();
             let reused = commands_for(&dev, raw_list, allocator, pso::chain_tail_offset(1) + 12).unwrap();
             assert!(Arc::ptr_eq(&recorded, &reused));

lukastaro and others added 2 commits November 30, 2026 22:36
main has this branch's fold already: it came in with the world-main
integration branch (fe650b6, 82daf31, with theaustinayers' bound on the
groups in 9cc53f1 and the indirect pass opt-in behind XCL_CLAMP_INDIRECT=1).
Every conflict takes main's side; the branch's own changes after that are
the follow-up fixes in the next commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016SP4yAshKooAmiGUcvcSzU
…roups

Two places where a dispatch past 65 535 groups in X still did not run the
groups the console runs:

- A split compute program's Dispatch-only ExecuteIndirect, once its
  indirect chain is ready, never reached the clamp pass: the chain's slicer
  took min(counts, 65 535), so of 72 512 x 1 x 1 the last 6 977 groups did
  not run, and whether they ran depended on whether the chain was built yet
  (found by thehollowedone in the review of xcl-dev#1428). With the indirect fold
  on (XCL_CLAMP_INDIRECT=1) the slicer now takes the counts as the clamp
  pass does - folded into Y with the console's count written to the
  dispatch's IO_GROUP_LIMIT word, clamped, or none past the bound - and
  cuts the folded grid into its slabs. It runs after the bind (it needs the
  io's address), which is set again after it. Without the switch nothing
  changes.
- The HLSL path: a program the split wave64 form remaps in Y (32 x 4
  threads: two hardware groups a console group) took its fold row from the
  hardware's gid.y; the console's row is gid.y / ratio. Before, each console
  group of a folded dispatch ran with half its threads and the second row's
  groups ran as others.

The fold rule itself is one HLSL function, recomp::FOLD_GROUPS_HLSL, which
the clamp pass and the slicer both include.

Tests: split_indirect_slicer_folds_as_the_clamp_pass (GPU: the slicer's
commands and io word for folded, whole-form, within-limit, non-count and
zero counts, and with the fold off; fails on the previous slicer),
gpu_folded_dispatch_with_a_remap_in_y_runs_each_console_group_once (GPU:
an atomic count of each console group's threads, 128; 64 on the previous
emitter).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016SP4yAshKooAmiGUcvcSzU
@github-actions github-actions Bot added area:d3d12 D3D12.X runtime, command lists, resources, sparse memory area:recompiler RDNA2 decoder, HLSL/direct-DXIL recompiler, wave64/wave32 area:tests Unit, integration, e2e tests, or testtitle gpu:nvidia Code is specific to NVIDIA / wave32 GPUs (scope tag; see needs:nvidia-test) labels Nov 30, 2026
@lukastaro lukastaro changed the title D3D12.X: dispatches of more than 65 535 groups in X are folded into Y D3D12.X: a folded indirect dispatch of a split program runs all its groups Nov 30, 2026
@lukastaro

Copy link
Copy Markdown
Contributor Author

@thehollowedone thanks, you were right: a ready split chain bypassed the fold. 7b842cc makes the slicer take the counts as the clamp pass does (with XCL_CLAMP_INDIRECT=1): folded into Y with the console's count in the dispatch's io, clamped, or none past the bound, and the folded grid cut into its slabs. It follows your candidate, with the fold rule shared as one HLSL function and the slicer recorded after the bind (it needs the io's address), the binding set again after it. split_indirect_slicer_folds_as_the_clamp_pass fails on the previous slicer. The same commit fixes a fold with a wave-local remap in Y on the HLSL path. Since the fold itself is in main through world-main, this PR is now that follow-up; the description is updated.

AI use: Claude Code (Claude Opus 5.5) wrote the change and this comment.

@thehollowedone

thehollowedone commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

merge-check
base: d0832e6
head: 7b842cc
merge: clean
build: cargo build --workspace -> not run after the focused failure
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> not run after the focused failure; SKIPPED: 0 in the focused runs. cargo test --offline --locked -p xcl --lib split_indirect_slicer_folds_as_the_clamp_pass --target-dir ..\target -- --nocapture --test-threads=1: stock test 1 passed; with the boundary case added to the unchanged PR logic, 0 passed and 1 failed; with the local candidate below, 1 passed, 0 failed, 0 ignored.
review: The ready-chain slicer receives indirect_guard::max_groups() without the extra FOLD_X row that both the ordinary clamp and bind::fold_counts_within allow. At the default 4,194,304-group limit, [4,194,304, 1, 1] is valid. Its folded grid is [65,535, 65, 1]; the extra hardware groups in the last row are masked by IO_GROUP_LIMIT. The unchanged PR head instead wrote [0, 0, 0] to the whole-form command. The focused GPU assertion failed on that exact difference. The candidate passes the same boundary and keeps the test tied to the bound the ready-chain caller actually supplies. I read the complete eight-file diff. Full suite, paired smoke, and a title dispatch at this boundary remain untested.
performance: No frame-time or world-load measurement. The change is in the opt-in indirect fold path; it restores valid groups currently dropped at the boundary.
verdict: not yet: the ready split-chain path drops a valid folded dispatch at the configured group limit.
hardware / tool and model: NVIDIA RTX 3080 Ti (621.40), Ryzen 7 9800X3D, Windows build 26300, rustc 1.99.1, DXC 1.8.2502.11 / OpenAI Codex (GPT-6.2 Sol) ran the GPU checks and prepared the candidate; OpenAI Codex (GPT-6.2 Astra) independently traced the boundary.

Candidate diff against PR head
diff --git a/crates/xcl/src/hle/d3d12x/clamp.rs b/crates/xcl/src/hle/d3d12x/clamp.rs
index 7b45e30f..1358e03b 100644
--- a/crates/xcl/src/hle/d3d12x/clamp.rs
+++ b/crates/xcl/src/hle/d3d12x/clamp.rs
@@ -310,11 +310,13 @@ mod tests {
             let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE;
             let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap();
             let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
-            let bound = super::super::indirect_guard::max_groups();
+            let guard_bound = super::super::indirect_guard::max_groups();
+            let bound = super::super::real::dispatch_chain::indirect_fold_bound();
             let rounds = 4u32;
             let tail = pso::chain_tail_offset(rounds) as usize / 4;
             for (k, (args, most, fold)) in [
                 ([72_512u32, 1, 1], 40_000u64, true), // four slabs over the two folded rows
+                ([guard_bound, 1, 1], 65_535, true),    // the allowed final group's padded fold row
                 ([72_512, 1, 1], 1, true),            // more slabs than rounds: the whole form
                 ([65_535, 2, 1], 65_535, true),       // within D3D12's limits: as it is
                 ([0x3F80_0000, 1, 1], 1, true),       // not counts (1.0f): no groups
diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs
index 763b0370..80e17be2 100644
--- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs
+++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs
@@ -582,6 +582,11 @@ pub(in crate::hle::d3d12x) enum Indirect {
     Whole,
 }

+/// The slicer's group ceiling includes the padded last row of a folded dispatch.
+pub(in crate::hle::d3d12x) fn indirect_fold_bound() -> u32 {
+    super::super::indirect_guard::max_groups().saturating_add(crate::gpu::recomp::FOLD_X)
+}
+
 /// Run one Dispatch-only indirect command through an existing split chain: the pieces a direct
 /// dispatch runs, each round's root constants and groups from the slicer's commands
 /// (`pso::chain_command_signature`), so it waits for no other build. The slicer writes either
@@ -632,7 +637,7 @@ pub(in crate::hle::d3d12x) unsafe fn execute_indirect(
         // the command buffer's state cycle stays whole)
         match bind(chain.builder.signature.as_raw() as usize) {
             Ok(io) => {
-                slice(Some((io + 4 * crate::gpu::recomp::IO_GROUP_LIMIT as u64, super::super::indirect_guard::max_groups())))?;
+                slice(Some((io + 4 * crate::gpu::recomp::IO_GROUP_LIMIT as u64, indirect_fold_bound())))?;
                 rebind();
                 Ok(())
             }

Follow-up on the same head: the ready-chain branch returns before indirect_guard::check. With the default 4,194,304-group limit, [65,535, 64, 1] is within the bound but [65,535, 65, 1] is not. I ran a temporary synthetic GPU slicer diagnostic with both inputs on the unchanged PR head: 0 passed, 1 failed, 0 ignored. For the latter, the slicer emitted [65,535, 65, 1] in the whole-form command, whereas the ordinary guard's source condition rejects that product. This inspected generated commands; it did not dispatch 4.26 million groups.

Test scope correction: that diagnostic calls the slicer directly. It would still fail after the guard is correctly added in the caller, so the diagnostic is not an acceptance regression for this fix. The earlier padded-fold candidate also does not address this gap.

A complete fix should run the guard after the split path's last Whole fallback and before it binds the chain ABI. Feed the checked output's GPU address plus slot offset to the slicer. The slicer reads through an SRV, so transition that buffer from UAV to NON_PIXEL_SHADER_RESOURCE for the read, then to COMMON afterward even if slicer setup fails. Preserve the original address when the guard is off and the ordinary guard path when the chain falls back to Whole; do not check a command twice. An end-to-end regression should enter bind::execute_indirect with an isolated low group limit, check accepted and rejected counts with fold on and off, and inspect the resulting commands or readback. I have not run that integration regression.

@github-actions github-actions Bot added needs-1st-check Passes gates; needs first independent merge-check (#3041) needs:nvidia-test Needs a test report or merge-check on an NVIDIA GPU and removed needs-1st-check Passes gates; needs first independent merge-check (#3041) needs:nvidia-test Needs a test report or merge-check on an NVIDIA GPU labels Nov 30, 2026
@Foniass

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Triage (#1607) – head 7b842cc

No open or merged PR does this. #2404 (split program ExecuteIndirect) is a different change: its slicer still uses min(args, 65535) and never folds.
No problems found in the diff. Two separate fixes are in one PR: the gid.y / ratio row for a folded dispatch with a Y remap (emit.rs), and folding in the indirect slicer (pso.rs, clamp.rs, dispatch_chain.rs). Each has its own test, but they could be reviewed as two PRs.
Recommendation: keep open.

AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.

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

Labels

area:d3d12 D3D12.X runtime, command lists, resources, sparse memory area:recompiler RDNA2 decoder, HLSL/direct-DXIL recompiler, wave64/wave32 area:tests Unit, integration, e2e tests, or testtitle goal:world-load Bears on the retail title getting past world loading gpu:nvidia Code is specific to NVIDIA / wave32 GPUs (scope tag; see needs:nvidia-test)

Projects

None yet

Development

Successfully merging this pull request may close these issues.