Skip to content

D3D12-SHADER-DOUBLE-BUFFERED-EXCHANGE: double-buffer wave64 exchange banks to halve loop barriers - #2688

Open
bobcatchris wants to merge 4 commits into
ProjectLeonida:mainfrom
bobcatchris:feat/d3d12-shader-double-buffered-exchange
Open

bobcatchris wants to merge 4 commits into
ProjectLeonida:mainfrom
bobcatchris:feat/d3d12-shader-double-buffered-exchange

Conversation

@bobcatchris

Copy link
Copy Markdown
Contributor

Claimed in #2570 as D3D12-SHADER-DOUBLE-BUFFERED-EXCHANGE (#issuecomment-7267219686).

What and why

Addresses the open shader-performance item in d3d12/docs/findings.md:

"What is left, by size: exchanges inside loops (two barriers each: about 110 of the 134 barriers of the 8 x 8 material program 1f1fbd86759b3da2 are in loops)"
"What would make it cheap: one barrier per exchange (two dwords used by turns)"

Previously, exchange_many() in d3d12/crates/leonida-shader/src/emit/lower.rs emitted two group_sync barriers for every exchange inside a cyclic IR block (one after storing into the shared pair, and a second after loading so the next exchange would not overwrite a slow reader).

This change allocates a second shared exchange bank (2 * waves extra LDS dwords when exchange_sites() > 0 and LDS has room) and threads a per-thread 1-bit bank parity SSA value (i32 in {0, 1}) across reachable IR blocks:

  • Exchange k stores into bank k & 1, executes one group_sync, loads both halves from bank k & 1, and flips bank ^= 1.
  • Because all threads passed the barrier of exchange k - 1 after finishing their reads of bank (k - 2) & 1 == k & 1, storing to bank k & 1 is race-free without a post-load barrier.
  • Trivial bank phis in shaders with no shared-bank exchanges are eliminated by opt.rs (FOLD | DEAD).
  • Cleanly falls back to the 2-barrier single-bank path when LEONIDA_EXCHANGE_SITES=0 or LDS has no room for the second bank.

Verification (Red -> Green)

Hardware / OS: native Windows 11 Pro (10.0.26200) + AMD Radeon RX 7900 XTX (gfx1100, driver 32.0.32029.2010), pinned toolchain rustc 1.98.1.

  • Red (before fix): exchanges_in_a_loop_meet_once_with_double_buffered_banks emitted 3 barriers both with LEONIDA_EXCHANGE_SITES=24 and 0 (3 vs 3).
  • Green (after fix, on main 40e7fe69d):
    • Loop exchange drops from 3 barriers to 2 (1 barrier per loop exchange instead of 2), DXIL validates via dxil.dll, and live GPU dispatch on RX 7900 XTX matches the exact 8-iteration wave OR sum bit-for-bit.
    • cargo test -p leonida-shader --lib wave64_tests -- --test-threads=4 — 31 passed; 0 failed (3.87s).
    • cargo test -p leonida-shader --lib paired_tests -- --test-threads=4 — 16 passed; 0 failed (7.30s).
    • python -I scripts/check_no_game_data.py on both touched files — PASS.

AI-assisted: Antigravity (Gemini 4 Neon)

@ecox982745

Copy link
Copy Markdown
Contributor

Independent RTX 4090 exchange verification. Native Windows 11, NVIDIA 616.64, MSVC, Rust 1.98.1, and SDK 26100 DXIL validation.

  • 52e1a0cf2 merged cleanly onto 182d0c174 (tree 083796dbb). The exact wave64_tests and paired_tests filters passed 31/31 and 16/16 respectively.
  • Adding d3d12-shader: Wave64 loop convergence, lane provenance, and wide/sub-dword paired LDS (D3D12-SHADER-PAIRED-WAVE64-EXACTNESS) #2662 at ab78da371 merged cleanly (tree 864726660). The same exact filters passed 31/31 and 22/22.
  • A local strict rerun of the new eight-iteration fixture required each arm to create its hardware pipeline and run dispatch. DXGI resolved the device to the RTX 4090 on both trees. The unoptimized arm emitted 3 group barriers, and the double-buffered arm emitted 2, with readback 952 in both arms. The wider test totals mix CPU checks and GPU work.

Synthetic input only. AI-assisted with OpenAI Codex (GPT-6.2 Sol).

…oop barriers (D3D12-SHADER-DOUBLE-BUFFERED-EXCHANGE)

Addresses the d3d12/docs/findings.md item ("exchanges inside loops (two
barriers each: about 110 of the 134 barriers of the 8 x 8 material
program 1f1fbd86759b3da2 are in loops)" / "What would make it cheap:
one barrier per exchange (two dwords used by turns)").

When exchange_sites() > 0 and LDS has room for a second shared bank
(2 * waves extra dwords), allocate two alternating shared exchange banks
and thread a per-thread 1-bit bank parity SSA value (i32 in {0, 1})
across IR blocks. Every shared-bank exchange (including inside loops)
alternates banks with one group_sync after its stores and flips
bank ^= 1, eliminating the second post-load barrier while keeping bank
reads and next-iteration stores strictly separated by the preceding
barrier.

Falls back cleanly to the 2-barrier single-bank path when
LEONIDA_EXCHANGE_SITES=0 or when LDS is too full for the second bank.

AI-assisted: Antigravity (Gemini 4 Neon)
@KelboLive

Copy link
Copy Markdown

Independent check on Windows (not the author), at 2ef9796f0.

  • cargo test --locked --jobs 8 -p leonida-shader --lib -- --test-threads=8: 386 passed, 0 failed, 4 ignored in 251.6 s.

Environment: Ryzen 9 7950X3D, Windows 11 Pro 10.0.26200.9711, Rust 1.98.1 pinned.

The behavioural claims (fewer loop barriers / same exchange results) are covered by the crate's own paired/wave64 tests; I did not measure the performance change on a GPU.

AI-assisted: yes (opencode).

@merzleckeier

Copy link
Copy Markdown
Contributor

Test-only merge overlap with #2685

MEASURED. This head (2ef9796f0) and #2685 (903e3731e) each merge cleanly into main 08e42a516. Combining the two resulting trees with git merge-tree --write-tree conflicts only in d3d12/crates/leonida-shader/src/emit/wave64_tests.rs. Both patches append a different test at the same location. Keep one_d_wave64_group_skips_entry_ticket_barrier_and_keeps_thread_ids and exchanges_in_a_loop_meet_once_with_double_buffered_banks as separate functions. lower.rs merges automatically.

This checks the merge hunks. The combined shader behavior needs a separate test run. AI-assisted: Codex (GPT-6.2 Sol).

@ecox982745

Copy link
Copy Markdown
Contributor

Native Windows follow-up to the combined Wine test. I merged 2ef9796f0 (#2688) and 903e3731e (#2685) with 1d4949d58, which includes #2710. The only conflict was the test-file overlap noted above. Keeping both tests gives tree 00d85c8d8. No production source was changed during conflict resolution.

MSVC Rust 1.98.1 release, Windows 11, NVIDIA 616.64. I made the two fixtures require Windows SDK 26100 DXIL validation, native hardware PSO creation and dispatch. DXGI confirmed the RTX 4090 for every case. Results held in three fresh runs per fixture:

Fixture Emitted group barriers GPU readback
Eight-iteration loop, single / double bank 2 / 1 952 in both modes
1-D Wave64, halves / paired 1 / 0 All 128 words 1..128 in both modes

All 11 stock emit::wave::tests passed, including the merged #2710 regression. Synthetic inputs only. AI-assisted with OpenAI Codex (GPT-6.2 Sol).

Co-authored-by: Cursor <cursoragent@cursor.com>
@bobcatchris

Copy link
Copy Markdown
Contributor Author

Merged main (#2685 landed in wave64_tests.rs); kept both tests, no production change. cargo test -p leonida-shader --release emit:: after the merge: 269 passed, 0 failed, 5 ignored.

AI-assisted: Claude Sonnet 5.5

@lixonik

lixonik commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Independent game-run A/B test with a freshly rebuilt shader cache on Windows 10 + NVIDIA RTX 5070 12 GB (driver 621.40) + Ryzen 9 5950X (MEASURED, PROVISIONAL (n=2 balanced BAAB pairs: B1/A1, A2/B2), Series X dynamic 1080-1440p -NoFrameGen, same save restored before every run, d3d12/target/diag built with diagnostics,dlss,mimalloc).

Verdict: same in play frame rate on this CPU-bound PC (gpu_wait 0.1-0.2 ms), better on cold NVIDIA PSO compile time, and clean shader/runtime parity (0 translation regressions, 0 runtime errors, 0 device losses).

  • Full shader cache rebuild parity (MEASURED, fresh isolated cache dir for D3D12-SHADER-DOUBLE-BUFFERED-EXCHANGE: double-buffer wave64 exchange banks to halve loop barriers #2688):
    • main (a596adfac): 25,687 shaders translated, 202 untranslated (133 s); cold warm --used: 3,209 pipelines compiled in 371 s (0 failures; per-PSO median 669.0 ms, p90 6050.4 ms, p99 18343.8 ms, max 26496 ms, sum 6922 s).
    • #2688 (d0a9bb041): 25,687 shaders translated, 202 untranslated (133 s); cold warm --used: 3,231 pipelines compiled in 328 s (0 failures; per-PSO median 514.7 ms, p90 4951.9 ms, p99 17508.2 ms, max 24996 ms, sum 6182 s) -- ~12% faster wall time / ~23% lower median driver PSO compile time with 22 more pipelines.
  • In-world BAAB (Series X, -NoFrameGen, CPU-bound on RTX 5070):
    • Mean A (main): 51.3 ms (49.1 / 53.5 ms), mean GPU busy 68.3% (71.5% / 65.0%), gpu_wait 0.1 / 0.2 ms.
    • Mean B (#2688): 52.0 ms (54.4 / 49.6 ms), mean GPU busy 69.5% (67.0% / 72.0%), gpu_wait 0.1 / 0.2 ms.
    • Because RTX 5070 is CPU-bound here (gpu_wait 0.1-0.2 ms), GPU shader frame-time gains are hidden behind CPU preparation (~33-35 ms) and the two arms are within run-to-run spread (~4 ms). A GPU-bound card/resolution is still needed to isolate pure GPU frame-time speedup, while full shader corpus translation, PSO compilation, and play stability on RTX 5070 (621.40) are verified clean.
RUN 2688-B1 | 2026-12-01 UTC | lixonik | AI-assisted: Antigravity
BASE:        a596adfac + #2688 (d0a9bb041) | shaders: freshly rebuilt isolated cache (25,687 translated, 202 untranslated)
MACHINE:     NVIDIA GeForce RTX 5070, 12 GB, desktop | 621.40 | Windows 10 Pro 22H2 (build 19045) | 64 GiB RAM | Ryzen 9 5950X
RECIPE:      documented (scripts/play-d3d12.ps1 -NoFrameGen, Series X default 1080-1440p) + DEVIATIONS: LEONIDA_KEYS_FILE (menu enter only) | precompile: yes (warm from #2688 rebuild, 3 s)
OS/DRIVER:   TdrDelay=default (Windows 10 D3D12 Agility SDK)
TARGET:      world frame time, GPU busy %, and stability with rebuilt #2688 shader cache | PREDICTED (written before the run): zero regressions; GPU frame-time impact may be masked if CPU-bound
MEASURED:    play (16 world samples, max 5,618 draws): median 18.5 fps (p10 11.8, p90 24.3), 54.4 ms/frame (preparing 33.5 ms, copies 13.8 ms / 51.9 MB, textures 1.4 ms, gpu_wait 0.1 ms, copy_back 7.3 ms, 3033 draws); buckets: 1000-2999 17.2 fps (8), 3000-4999 18.6 fps (4), 5000-6999 19.4 fps (4); GPU busy median 67.0% (idle 17.50 ms, n=78); 0 errors | duration 209.6 s (75 s in world)
END:         time limit (75 s in world)
CACHES:      warm: isolated #2688 shader cache + NVIDIA DXCache (same save restored before start) | RUN 1 of 2 (BAAB order)
INSTRUMENTS: standard diag log, d3d12_run_fps.py
VERDICT:     prediction held (CPU-bound, 0 errors)
RUN 2688-A1 | 2026-12-01 UTC | lixonik | AI-assisted: Antigravity
BASE:        a596adfac (main) | shaders: main cache (25,687 translated, 202 untranslated)
MACHINE:     NVIDIA GeForce RTX 5070, 12 GB, desktop | 621.40 | Windows 10 Pro 22H2 (build 19045) | 64 GiB RAM | Ryzen 9 5950X
RECIPE:      documented (scripts/play-d3d12.ps1 -NoFrameGen, Series X default 1080-1440p) + DEVIATIONS: LEONIDA_KEYS_FILE (menu enter only) | precompile: yes (warm, 6 s)
OS/DRIVER:   TdrDelay=default (Windows 10 D3D12 Agility SDK)
TARGET:      world frame time & GPU busy % control | PREDICTED (written before the run): ~48-55 ms CPU-bound
MEASURED:    play (17 world samples, max 5,682 draws): median 20.4 fps (p10 14.3, p90 25.2), 49.1 ms/frame (preparing 33.0 ms, copies 14.1 ms / 46.8 MB, textures 1.1 ms, gpu_wait 0.1 ms, copy_back 7.4 ms, 3317 draws); buckets: 1000-2999 19.1 fps (7), 3000-4999 19.6 fps (4), 5000-6999 23.5 fps (6); GPU busy median 71.5% (idle 15.65 ms, n=82); 0 errors | duration 207.2 s (75 s in world)
END:         time limit (75 s in world)
CACHES:      warm: main shader cache + NVIDIA DXCache (same save restored before start) | RUN 1 of 2 (BAAB order)
INSTRUMENTS: standard diag log, d3d12_run_fps.py
VERDICT:     prediction held
RUN 2688-A2 | 2026-12-01 UTC | lixonik | AI-assisted: Antigravity
BASE:        a596adfac (main) | shaders: main cache (same)
MACHINE:     NVIDIA GeForce RTX 5070, 12 GB, desktop | 621.40 | Windows 10 Pro 22H2 (build 19045) | 64 GiB RAM | Ryzen 9 5950X
RECIPE:      documented (scripts/play-d3d12.ps1 -NoFrameGen, Series X default 1080-1440p) + DEVIATIONS: LEONIDA_KEYS_FILE (menu enter only) | precompile: yes (warm, 6 s)
OS/DRIVER:   TdrDelay=default (Windows 10 D3D12 Agility SDK)
TARGET:      world frame time & GPU busy % control (reverse pair) | PREDICTED (written before the run): ~48-55 ms CPU-bound
MEASURED:    play (16 world samples, max 5,778 draws): median 18.8 fps (p10 12.2, p90 24.2), 53.5 ms/frame (preparing 33.5 ms, copies 14.7 ms / 47.6 MB, textures 1.2 ms, gpu_wait 0.2 ms, copy_back 6.5 ms, 2952 draws); buckets: 1000-2999 18.1 fps (8), 3000-4999 19.1 fps (4), 5000-6999 19.2 fps (4); GPU busy median 65.0% (idle 17.60 ms, n=79); 0 errors | duration 203.1 s (75 s in world)
END:         time limit (75 s in world)
CACHES:      warm: main shader cache + NVIDIA DXCache (same save restored before start) | RUN 2 of 2 (BAAB order)
INSTRUMENTS: standard diag log, d3d12_run_fps.py
VERDICT:     prediction held
RUN 2688-B2 | 2026-12-01 UTC | lixonik | AI-assisted: Antigravity
BASE:        a596adfac + #2688 (d0a9bb041) | shaders: freshly rebuilt isolated cache (same)
MACHINE:     NVIDIA GeForce RTX 5070, 12 GB, desktop | 621.40 | Windows 10 Pro 22H2 (build 19045) | 64 GiB RAM | Ryzen 9 5950X
RECIPE:      documented (scripts/play-d3d12.ps1 -NoFrameGen, Series X default 1080-1440p) + DEVIATIONS: LEONIDA_KEYS_FILE (menu enter only) | precompile: yes (warm, 6 s)
OS/DRIVER:   TdrDelay=default (Windows 10 D3D12 Agility SDK)
TARGET:      world frame time & GPU busy % (reverse pair) | PREDICTED (written before the run): parity within run-to-run spread, 0 errors
MEASURED:    play (17 world samples, max 5,777 draws): median 20.2 fps (p10 14.0, p90 24.5), 49.6 ms/frame (preparing 34.7 ms, copies 13.5 ms / 46.4 MB, textures 1.2 ms, gpu_wait 0.2 ms, copy_back 7.9 ms, 3366 draws); buckets: 1000-2999 19.4 fps (7, +7% vs A2), 3000-4999 18.6 fps (4), 5000-6999 24.1 fps (6); GPU busy median 72.0% (idle 14.40 ms, n=81); 0 errors | duration 210.7 s (75 s in world)
END:         time limit (75 s in world)
CACHES:      warm: isolated #2688 shader cache + NVIDIA DXCache (same save restored before start) | RUN 2 of 2 (BAAB order)
INSTRUMENTS: standard diag log, d3d12_run_fps.py
VERDICT:     prediction held (BAAB parity: A 49.1/53.5 ms vs B 54.4/49.6 ms; 0 regressions)

AI-assisted: Antigravity.

@aslan2142 aslan2142 left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nice barrier reduction for cyclic/shared wave64 exchanges, and the end-of-lower() bank_in phi wiring handles late ballot_of/wave_any emissions on self.tail[b] cleanly.

One correctness edge case to guard before merging:

  • d3d12/crates/leonida-shader/src/emit/lower.rs (exchange_many, lines 6018-6060 in the diff): when self.double_bank.is_some() and ir resolves to None, execution falls back to the single-bank path targeting bank 0 (store(0); group_sync; load(0); group_sync). That fallback can be reached if at == self.s.entry (e.g., ballot_of or wave_any for entry EXEC with def_block == None) after IR block 0 already emitted a double-bank exchange on bank 0 (which intentionally omits the trailing group_sync) and then split self.s.entry (self.tail[0] != Some(self.s.entry)), e.g., with LEONIDA_EXCHANGE_SITES=1 or >24 exchanges before a guarded memory op in block 0. Because the fallback writes bank 0 immediately after the preceding bank-0 load with no intervening barrier, the two halves can race on bank 0.

Adding if self.double_bank.is_some() { self.group_sync(at); } before the single-bank fallback loop (or ensuring every fallback under double_bank fences first) closes this race cleanly. Please also update the branch so the new d3d12 (windows-latest) CI workflow runs.

(AI-assisted review.)

@merzleckeier

Copy link
Copy Markdown
Contributor

Independent offscreen A/B check of d0a9bb041 on 21e6bbf4b. I made the existing eight-iteration exchange test require DXIL validation, PSO creation, and GPU readback in both settings. On the base, exchange sites 0 and 24 both emitted two group barriers. With the PR, they emitted two and one respectively. Both settings returned the expected 952 on AMD Raphael (RADV 26.3.1) and RTX 4070 SUPER (NVIDIA 620.73.4), under Wine and vkd3d-proton 3.1.0.

This covers the single exchange in the checked-in loop fixture. The multi-site case raised in the other review and in-game frame time remain open.

AI-assisted with OpenAI Codex.

@merzleckeier

Copy link
Copy Markdown
Contributor

Follow-up with two distinct exchanges per loop iteration on d0a9bb041 merged onto 6c7f6b60c. The synthetic fixture runs two cross-half reductions with different inputs in each of eight iterations. I built the same fixture with the base emitter and with the PR emitter and forced host-wave32 lowering. For exchange-site budgets 0 / 1 / 24, the base emitted 4 / 4 / 4 group barriers and the PR emitted 4 / 2 / 2. Each variant passed DXIL validation and returned the expected 1968 from a real dispatch via Wine/vkd3d-proton on AMD RADV and RTX 4070 SUPER. This covers two cyclic exchange sites. The split-entry fallback from the review still needs its own fixture.

AI-assisted with OpenAI Codex.

@bobcatchris

Copy link
Copy Markdown
Contributor Author

@aslan2142 Addressed in 7efcddb21 (merged main first, no rebase/force-push, so the d3d12 (windows-latest) CI workflow runs):

  • Added if self.double_bank.is_some() && !mine.is_empty() { self.group_sync(at); } before the single-bank fallback in exchange_many (lower.rs).
  • Added regression test double_bank_single_bank_fallback_fences_before_reusing_bank_zero in wave64_tests.rs (confirmed red without the guard: off=6, on=4; green with it: off=6, on=5).
  • Verified locally on Windows (Rust 1.98.1): cargo test --locked -p leonida-shader --lib wave64_tests (33 passed, 0 failed) and python -I scripts/check_no_game_data.py (clean).

AI-assisted: Gemini 4 Neon (including an independent read-only reviewer pass).

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.

6 participants