Skip to content

Shaders: spin-wait loops stop after 4096 iterations; loop limit in release builds - #452

Closed
AntoninMichelq wants to merge 6 commits into
Marvisak:mainfrom
AntoninMichelq:up/spin-loop-limit
Closed

AntoninMichelq wants to merge 6 commits into
Marvisak:mainfrom
AntoninMichelq:up/spin-loop-limit

Conversation

@AntoninMichelq

Copy link
Copy Markdown

Requested by 4nto · project thread

Summary

Spin-wait loops now stop after 4096 iterations instead of 2^20. On an RX 7600, a loop limit of 4096 cut GPU time per world frame by a factor of 3 to 10.

Some compute loops only reread one address until another workgroup, queue or the command processor changes it (decoupled look-back, persistent-thread queues, locks). On the console the write comes within microseconds. On the host it may never come: the writer's view can be another host resource, a null view, or not yet mirrored, and the host compiler may hoist the load out of a loop that writes nothing. The loop then runs to the 2^20 limit in every lane, about a second per wave of uncached reads.

  1. VICTORY_SHADER_LOOP_LIMIT in release builds too. It was gated on the diagnostics feature. The shader cache already keys on it.
  2. Spin-wait loops get their own, lower limit. A new pass (emit/spin.rs) finds such loops in the IR. They stop at VICTORY_SHADER_SPIN_LIMIT (default 4096, never above the loop limit). Other loops keep the 2^20 limit.

What changed

  • emit/spin.rs (new): a loop is a spin wait when it has no stores, exports, LDS writes, barriers or messages; every memory read and atomic is at an address the loop does not change; and nothing loop-carried is made by arithmetic, only lane masks, compares and what was read.
  • emit/lower.rs: count_iteration uses the spin limit for those loop headers.
  • emit/mod.rs: spin_limit() and DEFAULT_SPIN_LIMIT; the loop limit is read in every build.
  • victory-gpu/src/shader_cache.rs: the cache key includes the spin limit.
  • README.md: the new variable.

Open PR #292 also reads VICTORY_SHADER_LOOP_LIMIT in release builds (the same as commit 1), and changes the loop counters to one shared budget per invocation. It has no spin-wait limit. The two touch the same counter code, so whichever lands second needs a small rebase.

How it was tested

  • cargo test -p victory-shader (Linux) passes: 62 tests, including new ones for a spin wait on a table buffer (spin limit), a loop that writes LDS (loop limit), the spin-loop finder and the limit parser.
  • cargo check --tests -p victory-shader -p victory-gpu and cargo check -p victory for x86_64-pc-windows-msvc (with CARGO_FEATURE_PURE=1) pass.
  • In the game on an RX 7600 (Windows 11), on an integration stack that includes these commits, with A/B diagnostic runs in the world:
    • With the loop limit at 4096 (VICTORY_SHADER_LOOP_LIMIT=4096), GPU time per frame went from 410 to 1,384 ms to a median of 127 ms.
    • That run lowered the limit for all loops. This PR keeps 2^20 for ordinary loops and gives 4096 only to spin waits.
    • No hang in 5 minutes.

Where 3D rendering stands on an RX 7600 (Windows 11)

  • In the world's first cutscene, props, characters, cables and vehicle tyres render (seen in a G-buffer view).
  • Ground, roads, buildings, textures, sky and lighting are still missing: the lighting output is black.
  • No GPU hang in the latest world runs of several minutes. About 10,000 draws per frame, at well under 1 fps.

These observations come from the integration stack (upstream main plus many open PRs), not from this branch alone.

🤖 Generated with Claude Code

https://claude.ai/code/session_01AZ9pSB4ZoXYUifuXg8gm66

@aycow

aycow commented Nov 24, 2026

Copy link
Copy Markdown

I found a fixed-address atomic case in 1fcaf13. In emit/spin.rs, MUBUF atomics can enter the read-only spin classification. An original synthetic GFX10 loop performs a returning buffer_atomic_add on a zeroed counter and exits when the old value reaches 32. With a general limit of 64 and a spin limit of 16, the original translation writes 16. Treating MUBUF atomics as effects in the existing store branch and excluding them from the read branch writes the CPU-reference value of 33.

I reproduced both outputs on AMD Radeon Graphics, an RTX 5070 Laptop GPU, and WARP with the D3D12 debug layer and full GPU-based validation active. All three reported zero validation warnings or errors. Could you cover this case in the classifier regression suite? I’ve kept the focused correction separate from the runtime census. This test checks observable atomic side effects and does not establish the cause of title polling.

@upipibi upipibi mentioned this pull request Nov 24, 2026
@aycow

aycow commented Nov 24, 2026

Copy link
Copy Markdown

For the next #452 revision, I can rerun the synthetic atomic test on AMD, NVIDIA and WARP. I’d keep paired assertions in the classifier test: a fixed-address load/compare loop still uses the spin budget, while a returning buffer_atomic_add loop with the same fixed address uses the general budget and produces 33 increments at limits 64/16. Any non-returning buffer atomic is also an observable write. The original fixture and the small classifier change are available if useful for your branch.

@LoukaAyariPignel

Copy link
Copy Markdown

I merged current main into this branch to clear the conflict: fix-452 on my fork, merge commit b533e24. The only conflict was in the imports of the emit::lower test module (this PR's Lowered/RootParam/UsedResource against half_shift from main). I took the union of both. On Windows, cargo test -p victory-shader, clippy -D warnings and fmt --check pass, and it still merges cleanly with today's main.

@Nixitov

Nixitov commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Data point for the spin-wait limit, measured on the machine where the world hang is worst here: the spin limit alone does not stop this title's 10-second host submissions, the general loop limit does.

Setup: Windows 11 Pro 26200.9974, RTX 5070, driver 617.14, release build, this PR merged onto a stack of the shader PRs (#298, #585, #383, #259, #302, #307, #539, #571, #569) and the GPU PRs (#493, #483, #581, #595), 110 s in the world each, same scene (first mission intro). VICTORY_SHADER_LOOP_LIMIT set per run (this PR makes it work in release builds, which is what made the measurement possible — thank you for that).

loop limit slow submissions longest submission GPU time per frame
2^20 (default) 9 10,637 ms 24-457 ms
2^16 11 1,089 ms 54-162 ms
2^14 3 371 ms 42-50 ms

The submissions that take 10 s are not spin waits: with the spin pass in, they are still 10 s, and they stop being a problem only when the general count comes down. Under 2^16 the frame rate is unchanged (2.6-4.4 fps, same draws/frame), so shortening those loops costs nothing visible here.

That matters beyond frame time: a submission over the host's ~2 s watchdog removes the device, and twice today a 10 s one took the whole desktop down with it (the machine had to be restarted). At 2^14 the longest submission is 371 ms and a 110 s world run has no removal.

Integration notes for landing it on current main (all small, on emit/lower.rs):

No game files; only timings and counts.

AI-assisted (DeepSeek V4.1 Flash coding agent).

@AntoninMichelq

Copy link
Copy Markdown
Author

Thanks a lot for these measurements, the 2^20 / 2^16 / 2^14 comparison on the RTX 5070 makes the case clearly.

The default general loop limit is now 2^14 (16,384) in cd6a864. The doc comment on LOOP_LIMIT gives the reason (the ~2 s host watchdog, your numbers) and the trade-off: a legitimate loop of more than 16,384 iterations per lane is cut short, so its result is wrong there.
VICTORY_SHADER_LOOP_LIMIT still overrides it in every build, including release, so a higher value can check whether a wrong result comes from the limit. The spin-wait limit stays at 4096 and never above the loop limit, and the shader cache still keys on both.
Current main (ffe310e) is merged in, no rebase (6c23321). In that main, Lower does not have resolved_reads, pure_spill_writes or guard_slots yet, and Parts has no host_waves, so those notes did not apply this time. The conflicts were in the test-only fields of Lowered and in the test helpers (main's lower_wave split and the new resource::track argument). I'll apply your notes when those PRs land.
cargo test -p victory-shader passes on Linux: 102 tests (1 ignored). cargo check --tests for x86_64-pc-windows-msvc passes for victory-shader, victory-gpu and victory.

@PastiiJay

Copy link
Copy Markdown

Data point for cd6a864 on RDNA4 (RX 9070 XT 16 GB), driver 32.0.32029.2010, Ryzen 7 9800X3D, 32 GB, Windows 11. Diag build, VICTORY_D3D12_DRED=1, no pad connected. Local merge of main@ffe310e + this PR + #431 + #67 (#568 did not merge cleanly on top, left out).

Build World frame time End of run
ffe310e plain ~3.7 s/frame device removed ~3 s after world entry (~63 s), DRED: no page fault, every breadcrumb done==count
ffe310e + #452 (cd6a864) + #431 + #67 0.58–0.97 s/frame, up to 4,472 draws/frame ~100 s in world (160 s total), then page fault at 0x1a939c000, list 21 stopped at 4/11

On this card the earlier removal looks like the 2 s TDR: with the loop limits from this PR every world frame stays under it, audio stays in sync, and the run only ends on a separate page fault. Same result on 3 earlier runs without this PR (always ~60 s). Happy to rerun another revision or limit value and post the numbers (on RDNA4 only).

@Machad3x

Copy link
Copy Markdown

Result on an NVIDIA RTX 3080 Ti (32-lane waves, Windows 11), fork github.com/Machad3x/VIctory branch claude/gta6-shader-translation-crashes-705550 (main + #302 #489 #294 #578 #650 #233 #709 #585 #309 #587 #452): wave64 mesh programs are NOT what hangs the GPU. With #578's mesh refusal switched off (a diagnostics-only switch on the fork, VICTORY_ALLOW_WAVE64_MESH=1): without #452 a world frame costs 4.3 s of GPU and the device is removed (even with #587); with VICTORY_SHADER_LOOP_LIMIT=64 the same run stays up (3731 draws per frame, about 90 ms of GPU per frame, no removal, no slow list); with #452 and its defaults (spin limit 4096, no manual limit) the run stays up for 5 minutes, 3900 draws per frame, 441 ms of GPU per frame. So the TDR was loops running to the 2^20 limit, as #452 measured on an RX 7600, and #578's mesh refusal looks unnecessary once #452 is in; only the frame CPU time (about 600 MB of copies per frame) remains very high. Not yet checked: whether the picture is right (the world was still mostly dark on the RX 7600 per #452).

@catminou4 catminou4 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.

Two coordinated changes, both well-reasoned:

1. General loop limit 2^20 → 2^14. The justification is measured, not guessed: world runs on an RTX 5070 had submissions up to 10.6 s hitting the ~2 s TDR watchdog (device removal, twice taking the desktop down); 2^14 keeps the longest submission at 371 ms with the same frame rate. The README documents the env var's new default and the diagnostic value of raising it. The // shortcut: comment honestly states the trade-off (a legitimate longer loop is cut short).

2. Spin-wait detection (spin.rs, 4096-iteration limit). The analysis is conservative in the right direction: a loop counts only if it has reads, no Effect accesses (stores/exports/LDS writes/barriers/messages), every memory address invariant, and no loop-carried arithmetic (a counter means real work). The alias resolution for trivial phis and the invariant memoization are careful. The two new lowering tests pin both directions: a table-buffer spin wait gets the spin limit (spin_loops == 1), the same loop with an LDS write inside keeps the general limit (== 0).

The shader-cache build hash now mixes in the spin limit alongside the loop limit, so changing VICTORY_SHADER_SPIN_LIMIT correctly invalidates cached translations — that part is in victory-gpu (Windows-only, not compiled here), but it's a two-line hash input and reads correctly.

Verified locally: test-merge with current main (ffe310e) clean; cargo test -p victory-shader --locked (macOS arm64, rustc 1.98.1) → 102 passed / 0 failed / 1 ignored. The spin-vs-loop runtime behavior (a spin wait actually stopping at 4096 on hardware) is Windows-gated like the rest of valu_tests, so it needs the Windows lane — but the detection logic and its tests are platform-independent and green here.

This was referenced Nov 24, 2026

Marvisak commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

Merge candidate. Recommending a look, not approving.

  • The branch now merges cleanly into main (940d32f). It makes VICTORY_SHADER_LOOP_LIMIT work in release builds, lowers the default general loop limit from 2^20 to 2^14 (emit/lower.rs LOOP_LIMIT), and gives loops that only reread a fixed address (emit/spin.rs spin_loops) a separate 4096 limit (spin_limit, capped at the loop limit), used in count_iteration. Both limits feed the shader cache key (shader_cache.rs key) and the pre-built pipeline list tag (pipeline/library.rs tag), with tests for each.
  • The classifier is conservative by my reading: stores, exports, LDS/GDS writes, barriers, messages, buffer/image/SMEM atomics and any FLAT access other than global_load_* make a loop non-spin; reads must use loop-invariant addresses; loop-carried values may only be masks, compares, copies or loaded values. The returning buffer_atomic_add case raised in the comments is handled in 0b2e932 (MUBUF atomics are Access::Effect).
  • Trade-off for the maintainer to accept: with the 2^14 default, a legitimate loop of more than 16,384 iterations per lane is cut short and gives a wrong result. The evidence for it is the hardware runs posted here (RTX 5070, RX 9070 XT, RTX 3070/3080 Ti/5060, submissions dropping under the ~2 s TDR), and the override still raises it.
  • Overlap: Shaders: translated loops are left after 2^14 iterations (was 2^20) #1819 makes only the 2^14 change; this PR covers it. Shader: lower WQM QuadAny, clamp LDS accesses, and guard loop budgets & barriers #292 also touches the loop counters and loop_limit(), so whichever lands second needs a rebase.
  • Small nit: the module doc of spin.rs and the Access::Read doc still say "(or an atomic)", which no longer matches the code.

CI: check passing.


Generated by Claude Code

claude and others added 6 commits November 24, 2026 22:33
A world frame spends 650-930 ms of GPU time per host submission on an
RX 7600, mostly in compute pipelines. Translated loops stop at 2^20
iterations per lane; a loop that waits on memory the host never updates
runs that long in every lane. A lower limit shows whether such loops are
the cost, and the user runs release builds: the switch is no longer
gated on the diagnostics feature. The shader cache already keys on the
limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AZ9pSB4ZoXYUifuXg8gm66
A loop that only rereads one address until another workgroup, queue or
the command processor changes it (decoupled look-back, persistent-thread
queues, locks) waits microseconds on the console. On the host the write
may never come: the writer's view can be another host resource, null or
not yet mirrored, and the host compiler may hoist a load out of a loop
that writes nothing (bufferLoad is readonly). The loop then runs to the
2^20 limit in every lane: about a second per wave of uncached reads,
the order of the 650-930 ms world submissions spend on an RX 7600.

Such loops are found in the IR (emit/spin.rs): no stores, exports, LDS
writes, barriers or messages; every memory read and atomic at an
address the loop does not change; and nothing loop-carried made by
arithmetic, only lane masks, compares and what was read. They stop at
VICTORY_SHADER_SPIN_LIMIT (default 4096, never above the loop limit);
the shader cache keys on it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AZ9pSB4ZoXYUifuXg8gm66
The host GPU watchdog removes the device once a submission runs for
about 2 s. Measured on an RTX 5070 over 110 s world runs: with 2^20,
9 slow submissions, the longest 10.6 s (24-457 ms of GPU time per
frame), device removed, twice with the desktop; with 2^16, the longest
1.1 s; with 2^14, the longest 371 ms (42-50 ms per frame), no device
removal, same frame rate. Those were not spin waits, so only the
general limit shortens them.

A legitimate loop of more than 16,384 iterations per lane is now cut
short and gives a wrong result there; VICTORY_SHADER_LOOP_LIMIT still
raises the limit in every build to check. The spin limit (4096) stays
at most the loop limit, and the shader cache keys on both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AZ9pSB4ZoXYUifuXg8gm66
Gate the Windows-only test imports and make the limit check a const
assertion, so cargo clippy -D warnings passes on CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AZ9pSB4ZoXYUifuXg8gm66
A returning buffer or image atomic was taken as a read, so a loop that
counts with one at a fixed address got the spin limit and stopped early
(upstream PR 452 review: 16 instead of 33 with limits 64/16). Atomics
now count as effects, like stores; tests cover both kinds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AZ9pSB4ZoXYUifuXg8gm66
The list's tag covers the translation as the shader cache keys it, but only
its loop limit: after a run with another VICTORY_SHADER_SPIN_LIMIT the list
still held, though the pipelines it names are not the ones that run makes.

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

Copy link
Copy Markdown

I rebased this onto current main (940d32f), in case it helps with the triage's "needs rebase": rebase/452 on my fork. It has your five commits with their author kept (the old merge of main is dropped), and one commit of mine. Take whatever is useful.

Conflicts. The four files triage lists are all "keep both" or the same edit against newer text. In shader_cache.rs, main's key() now hashes named parts, so the spin limit became a fourth argument, and the_key_covers_translator_encoding_and_settings covers it.

One conflict git does not show. Since this branched, main's pipeline/library.rs got a tag for the pre-built pipeline list. It is meant to cover the translation as the shader cache keys it, but it has only loop_limit(). After a run with another VICTORY_SHADER_SPIN_LIMIT the list would still hold, though the pipelines it names are not the ones that run makes. 723bacc adds the spin limit to the tag, with a test that fails without it.

Checked on Linux (Wine 11.22, vkd3d-proton, RTX 5080):

  • cargo test --workspace: 696 passed, 13 failed. main gives 688 passed and the same 13 failures there; the 8 more are this PR's tests and the one above.
  • cargo clippy --workspace --all-targets -- -D warnings, with and without --all-features, for the MSVC and GNU Windows targets: clean.

Not checked: a Windows run of the tests, and the title.


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

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.