Skip to content

fix(shader): let early-exited lanes leave a later loop at its first exit test (VICTORY_LOOP_ENTRY_EXIT, off by default) - #610

Open
cirddan wants to merge 6 commits into
pragyaangaur:mainfrom
cirddan:pr/loop-entry-exit
Open

cirddan wants to merge 6 commits into
pragyaangaur:mainfrom
cirddan:pr/loop-entry-exit

Conversation

@cirddan

@cirddan cirddan commented Nov 27, 2026

Copy link
Copy Markdown

Summary

In a wave64 compute program predicated for 32-lane halves (#440), lanes that took an early exit keep running with their block predicate false. On the console they run no pass of a later loop (the loop's mask starts as EXEC), but in the translation they follow the loop's own exit test, which the structurisation simplified for lanes in EXEC. A stale counter that never meets the test spins them until LOOP_LIMIT (16384, #123), and one such lane holds its whole 32-lane host wave.

GTA VI's strand hair visibility pass CS_VisHair (b6df66af105d8b2d) hits this: its pixel loop exits on fcmp oge 0, v15 only, and lanes dropped by the stochastic test keep v15 in [0, 1).

With VICTORY_LOOP_ENTRY_EXIT=1 (off by default, part of the shader cache key), a loop's exit test becomes exit || !active (as a select) or stay && active, active being the predicate the test runs under, only where that changes nothing but how long those lanes run (lower/entry_exit.rs):

  • every block of the loop runs under that same predicate (no linearised, skip, diamond or lockstep region);
  • no lane operation in the loop (barrier, wave or quad op, implicit-derivative sampling: Sample, SampleBias, SampleCmp, CalculateLOD, Deriv*), except the 64-bit atomics' guarded lock and umax reduction, which involve only the guard's lanes;
  • no s_barrier, scalar memory write, message or v_writelane in the loop, and no scalar it writes is read after it.

Results

Apple M5 (10-core GPU), 16 GB, macOS 27.2, D3DMetal 4.0b3, Series S profile, native 1280x720 (VICTORY_UPSCALER=6 VICTORY_RENDER_SCALE=1.0), 40 world frames, warm shader cache, on top of d1609d9:

without with VICTORY_LOOP_ENTRY_EXIT=1
frame (median) 0.559 s 0.369 s
on the GPU (median) 0.400 s 0.113 s
preparing (median) 0.133 s 0.157 s

With VICTORY_GPU_TIMING=1 and a per-list ranking, the hair list group goes from ~241 ms to ~4 ms per frame. Captures of the same scenes show the hair, faces and the rest unchanged.

Verification

  • Offline over the game's 19,139 cached shader containers: refusals identical with the switch off and on (72), 0 panics; with it off every translation hashes the same as plain d1609d9; with it on 58 translations change, all wave64 compute predicated for halves.
  • New fixture of the shape in halves_tests (early exit, then readfirstlane, then an EXEC-mask loop with a positive dead-lane counter): matches the console on the GPU with and without the switch; 32,768 groups take 3 ms with it and 120 ms without.
  • Unit tests in entry_exit.rs (fixture decode, loop membership, refusals for a scalar read after the loop, s_barrier, v_writelane, implicit-LOD sampling inside the loop).
  • cargo test -p victory-shader --lib: 273 passed. Wine halves: 60 passed. the_loop_entry_exit_switch_keys_the_cache passes.

Not covered: other GPUs and Series X; default stays off until others confirm.

🤖 Generated with Claude Code

…xit test (VICTORY_LOOP_ENTRY_EXIT=1, off by default)

In a wave64 program predicated for 32-lane halves, lanes that took an
early exit (s_cbranch_execz to s_endpgm, predicated in lower/predicate.rs)
run on with their block predicate false. The console runs no pass of a
later loop for them (its mask starts as EXEC), but here they followed the
loop's own exit test, which the structurisation simplified for lanes in
EXEC. A stale counter that never meets the test spins them to LOOP_LIMIT
(16384) and holds their whole host wave: CS_VisHair (b6df66af105d8b2d)
exits on `fcmp oge 0, v15` only, and lanes the stochastic test dropped
keep v15 in [0,1), about 0.3 s a frame.

With emit::Options::loop_entry_exit (VICTORY_LOOP_ENTRY_EXIT=1, in the
shader cache key) a loop exit test becomes `exit || !active` (a select,
not an xor of a compare) or `stay && active`, active being the predicate
the test runs under, only where that changes nothing but how long those
lanes run (lower/entry_exit.rs): every block of the loop runs under that
same predicate (no linearised, skip, diamond or lockstep region), no lane
operation (barrier, wave or quad op, or one taking implicit derivatives
from the quad: Sample, SampleBias, SampleCmp, CalculateLOD, Deriv*) is
written in it outside the 64-bit atomics' guarded lock and umax
reduction (which involve only the guard's lanes, others offering umax's
identity), no s_barrier, scalar memory write, message or v_writelane,
and no scalar the loop writes is read after it.

For b6df66af105d8b2d the one change is the pixel loop's exit, `select
%2950, (fcmp oge 0, %3599), true`, in both the plain and the umax forms.
The fixture of its shape (halves_tests) matches the console on the GPU
with and without the switch and runs 32768 groups in 3 ms instead of 120.

An implicit-LOD image_sample in the loop refuses the rewrite (a fixture
spoiler): lanes leaving early would drop out of their quad's derivatives,
which in halves they otherwise feed with their preserved, console-equal
coordinates. Over the game's 19,139 cached containers: refusals are the
same with the switch off and on (72), with it off every translation
hashes as before, and with it on 58 translations change.

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

Copy link
Copy Markdown
Contributor

Measured in game on an M5 Pro (48 GB, CrossOver 26.3). Base: d1609d9 + #589 #593 #605 #606 #608 #592 #595 + #594 #604 #607 #609 #613 + this PR. It's the same exe in both rows, run once without the switch and once with VICTORY_LOOP_ENTRY_EXIT=1. Silent scripted opening into the cell, 420 s, warm caches, VICTORY_GPU_TIMING unset. The numbers are from the host's 5-second report lines, counting world lines only (over 500 draws a frame):

Report lines Median frame Prep GPU Draws a frame Lines over 500 ms
switch off 57 388 ms 136 ms 204 ms 4,855 7
VICTORY_LOOP_ENTRY_EXIT=1 62 318 ms 149 ms 125 ms 5,012 0
  • b6df66af105d8b2d translates and is bound from world entry in both.
  • The picture looks the same. Median luma of the world captures is 53.6 off and 54.3 on, and the hair looks the same in matching captures.
  • Two earlier runs with the switch on gave the same GPU line: 114 ms, and 125 ms in a run where the host pipeline library had to be rebuilt.
  • No hangs, ended submissions or unhandled exceptions in any of them.

@4TheDoctor This fits your suspicion about the GPU level. Here the switch takes about 80 ms of GPU time off every world frame, and no report line went over 500 ms with it on (7 without).

Prepared with Claude Code.

@hackgods

Copy link
Copy Markdown
Contributor

Thanks. We found the same thing independently while profiling an offline replay of one prison-cell
frame on an M5 Pro (20-core GPU, D3DMetal 4.0b3), and I had written the same rewrite before this PR
appeared. With your switch on, its translation of b6df66af105d8b2d is byte-identical to mine
(select %2950, (fcmp oge 0, %3599), true at the pixel loop's exit, nothing else).

Exactness. I read entry_exit.rs and believe the rewrite is exact as written:

  • The lanes it sends out are the ones with the loop's predicate false. Every block of the loop runs
    under that same predicate (plain, block_active[x] == Some(active)), so each vector write those
    lanes make keeps the old value and each side effect is guarded. One pass or 2^14 passes leave their
    VGPRs the same.
  • With no lane operation in the loop (outside the guarded lock/umax, which only involve the guard's
    lanes), no lane of the wave or group can see whether they are still there.
  • With no scalar the loop writes read after it, the only state that differs after an early exit (the
    scalars an inactive lane computed unguarded) is dead.
  • It also removes a hazard on main. Such lanes now leave the program from the loop limit's ret, so
    they miss any group barrier after the loop, for example a read across the halves. With the rewrite
    they leave through the loop's own exit and reach that barrier. The rewrite only adds exits, so it
    cannot make a loop run longer or hang.

Survey (19,106 containers of 1.0.2.1, Wine's options, 8 threads):

  • With the switch on, 58 translations change, refusals stay 68 = 68, and none is newly refused.
  • dx.op.barrier counts are equal in all 58. The other op counts are equal too; only the exit
    condition gains an and/select.
  • With the switch off, every translation equals d1609d9 (the 47 programs both variants change are
    byte-identical to main with the switch off).
  • I also built a variant of your note_loop_exit that takes any branch out of the innermost loop,
    not just one whose staying side is the header or a jump-only latch. It changes the same 58
    programs, so no loop in this title needs another shape.
  • My own broader variant rewrote 10 programs your rules refuse:
    • 4d4d59cdf9392889 and 585ecfc8622dffca have a lane operation in the loop.
    • 5d3fa5f1ee755e44, 6c4c4ff7283f90b3, 7842e2ce8ccd9280, 8e9fa5ede09d77c5, ba423f650a4e8c2f,
      bf0e8d5ee5ae755c, d72397c79be4bd1a and f64bac83df2ea939 have a scalar written in the loop and
      read after it.
    • I agree these should stay refused.
  • It also skipped 11 programs whose loop exit is on a scalar, which yours rewrites. Yours is the one
    to take.

Replay A/B (one cell frame recorded in the game, interleaved loops, median of 9):

main VICTORY_LOOP_ENTRY_EXIT=1
b6df66af105d8b2d alone, swapped in: submission 2 (115 dispatches) 87.18 ms 7.55 ms
the same, whole frame (clamps kept) 385.0 ms 304.2 ms (−80.8 ms, −21%)
reference: pre-#522 per-host-wave translation of it 7.61 ms
reference: the shader left out 7.63 ms
all 13 programs of this frame the switch changes, whole frame (clamps kept) 513.3 ms 392.0 ms (−121 ms)
— of it, submission 2 / submission 8 97.4 / 41.2 ms 9.6 / 21.8 ms
the same, clamps left out (off/on/off/on runs of one load, median of 7 each) 194.8, 229.5 ms 90.6, 113.8 ms
— of it, submission 2 / submission 8 89.7–91.4 / 30.9–34.4 ms 9.3–10.3 / 10.3–11.6 ms

The 13-program runs shared the machine with other jobs (loops vary ±25%), but submissions 2 and 8
move the same way in every run. Submission 8 is 63381c3250b287fa, which took 30 ms alone in the
main-translation detail run; your switch takes about 20 ms off it. Main measured 89.3 ms for submission 2
in an earlier run of the same capture. The pictures stay within
the replay's own loop-to-loop noise (81–85 dB against the presented frame, at most 1 level).
Native 64-bit atomics (locks off) gave 87.6 ms and VICTORY_ATOMIC_UMAX=1 gave 92.1 ms, so the
locks were never the cost. 4320 host waves × 2^14 passes ≈ 71 M passes in about 82 ms is about 140
cycles a pass, which is the predicated pixel loop.

Test suggestion. The fixture covers 64 threads and nothing after the loop. I ran an extra test on
your branch under Wine (M5 Pro, D3DMetal), early_exited_lanes_leave_a_while_loop_before_a_barrier_on_every_gpu:

  • The loop is while-shaped: the test comes after the body, so the exit test is at the header. The body
    is a 2,048-op dependent chain, and lanes 40-63 of each wave leave first with their counter at 0.
  • In groups of 64 and 128, every thread gets the console's results.
  • With the switch the dispatch takes 2.3 / 2.0 ms, against 2.1 / 2.4 ms for the same program where no
    lane leaves. Without the switch it takes 160 ms.
  • The barrier variant reads across the halves after the loop. My first version read a per-lane value
    there, which is refused on main too ("a first-lane read of a value that may differ between 32-lane
    halves"), so it is not about this PR. The corrected version, which reads the pass count, still needs
    a GPU run.
  • Your own halves tests and fixture pass on the same machine: 32,768 groups in 2.97 ms with the
    switch, 61.4 ms without.

I can push the test to a branch if you want it.

Default. I'd argue for on, with =0 as the opt-out. The rewrite changes only how long lanes
with a false predicate run, under conditions that make their extra passes unobservable. There is
nothing per GPU left to confirm beyond the Wine halves tests, and off costs ~80 ms in every cell frame
on an M5 Pro.

Relation to #591 (lockstep while loops). #591 also runs this loop in lockstep (loop_active
starts from the same predicate, group_any_true at the latch, 2 group barriers a pass). In the replay
that gave ~8 ms. Your plain excludes lockstep loops, so if both land b6df66af takes #591's form
and yours covers the other 57 programs. They do not conflict.

hackgods added a commit to hackgods/VIctory-macOS that referenced this pull request Nov 27, 2026
…xture upstream

pragyaangaur#610 deliberately skips lockstep loops. With pragyaangaur#591 also merged, its
fixture loop is taken by pragyaangaur#591's lockstep form (FlatExit::LockstepExit),
so the entry-exit rewrite counts 0 there and the test asserts that. A
fixture pragyaangaur#591 does not match is needed to cover the rewrite again.

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

Copy link
Copy Markdown
Owner

I merged main into this branch (conflicts in lower.rs and halves_tests.rs, kept both sides) and fixed the new Parts initializers in memory_tests.rs. It builds and clippy is clean, but one new test now fails with main's changes: emit::lower::entry_exit::tests::the_loop_exit_is_rewritten_only_with_the_switch_and_where_exact finds 0 rewrites where it expects 1 with the switch on (entry_exit.rs:548). It passed before #591 (lockstep while-loops), #595, #600 and #605 landed, so one of them probably changes how this fixture's loop is lowered. Could you check which one and adjust the rewrite or the test? I will merge it once the test passes.

@Zeyphers

Copy link
Copy Markdown
Contributor

Tried this on top of current main (06a9ea2) plus #593 and #605, on an M1 Max (32 GB, macOS 15.7.3).

The merge needs the usual both-sides fix in halves_tests.rs, but after that the_loop_exit_is_rewritten_only_with_the_switch_and_where_exact fails: with the switch on, rewritten(&plain, true) gives 0 instead of 1. My guess is that #591 (now on main) runs the fixture's while-shaped divergent loop in lockstep, which is one of the regions this PR leaves alone, so the exit test is never rewritten.

If that's right, #591 may already stop the CS_VisHair lanes from spinning. On main I see about 545 ms/frame once warm, against 828 ms on d1609d9 + #589/#591 (PR branch)/#586 with the same switches. Some of that gain comes from #591 holding back the BVH builder, so I can't separate the two. Worth a rebase and a check that CS_VisHair still hits the spin on main.

@pragyaangaur

Copy link
Copy Markdown
Owner

A note after reading the lowering code: note_loop_exit is called from the structured per-lane path in lower.rs (around line 11282). #591 (lockstep while-loops in halves) now takes loops of this shape through lower/predicate.rs instead, so the fixture never reaches note_loop_exit, which is why the test finds 0 rewrites. Could you check whether the strand-hair loop (CS_VisHair, #131) still needs this switch with #591 on main? If it does not, the PR can be closed. If it does, the rewrite has to be hooked into the lockstep path too.

@hackgods

Copy link
Copy Markdown
Contributor

Cause: #591. Since 06a9ea2, predicate.rs runs the fixture's while-shaped divergent loop in
lockstep (match_lockstep_while_loop), and plain skips lockstep loops by design. So
note_loop_exit never sees that exit. On the merged head (ce53982), reverting only 06a9ea2 makes
all 5 entry_exit tests pass again. #595, #600 and #605 are not involved.

CS_VisHair (b6df66af105d8b2d) no longer needs #610 on main.

What #610 still changes on current main (19,106 containers of 1.0.2.1, Wine's options):

Fixture fix. I kept the existing fixture, which now asserts 0 rewrites because #591 takes its
loop. The new nested_fixture puts the same loop inside an outer loop of the same kind, as in
63381c3250b287fa: 2 rewrites with the switch, 0 without, 0 with each spoiler. The GPU test uses the
nested form. It is commit 585ed58, on top of ce53982, on hackgods/VIctory-macOS branch
fix/610-fixture-after-591. The core of it:

 pub(in crate::emit) fn fixture(spoiler: Spoiler) -> Vec<u32> {
+    fixture_shaped(spoiler, false)
+}
+/// [`fixture`]'s loop inside an outer loop of the same kind ... as in `63381c3250b287fa`.
+pub(in crate::emit) fn nested_fixture(spoiler: Spoiler) -> Vec<u32> {
+    fixture_shaped(spoiler, true)
+}
+fn fixture_shaped(spoiler: Spoiler, nested: bool) -> Vec<u32> {
 ...
         0xBE98_047E, // s_mov_b64 s[24:25], exec
+    ]);
+    let outer = w.len() + 2;
+    if nested {
+        w.extend([
+            0xBEA4_047E, // s_mov_b64 s[36:37], exec
+            0xBF82_0001, // s_branch outer body
+            0x87FE_2426, // outer latch: s_and_b64 exec, s[38:39], s[36:37]
+            0xBEA6_047E, // outer body: s_mov_b64 s[38:39], exec
+            0xBEAC_047E, // s_mov_b64 s[44:45], exec
+        ]);
+    }
+    w.extend([
         0xBE94_047E, // s_mov_b64 s[20:21], exec
 ...
     w.push(0xBF85_0000 | (back as u32 & 0xFFFF)); // s_cbranch_scc1 latch
+    if nested {
+        w.extend([
+            0xBEFE_042C, // s_mov_b64 exec, s[44:45]
+            0x7C2C_1E80, // v_cmpx_ge_f32 0, v15
+            0x8AA4_7E24, // s_andn2_b64 s[36:37], s[36:37], exec
+        ]);
+        let back = outer as i32 - (w.len() as i32 + 1);
+        w.push(0xBF85_0000 | (back as u32 & 0xFFFF)); // s_cbranch_scc1 outer latch
+    }
 ...
     fn the_loop_exit_is_rewritten_only_with_the_switch_and_where_exact() {
-        let plain = fixture(Spoiler::None);
+        assert_eq!(rewritten(&fixture(Spoiler::None), true), 0);
+        let plain = nested_fixture(Spoiler::None);
         assert_eq!(rewritten(&plain, false), 0);
-        assert_eq!(rewritten(&plain, true), 1);
-        assert_eq!(rewritten(&fixture(Spoiler::ScalarAfter), true), 0);
+        assert_eq!(rewritten(&plain, true), 2);
+        assert_eq!(rewritten(&nested_fixture(Spoiler::ScalarAfter), true), 0);
 (likewise NeighbourInside and SampleInside on nested_fixture)
 // halves_tests.rs, early_exited_lanes_leave_a_later_loop_as_the_console_on_every_gpu:
-    let words = fixture(Spoiler::None);
+    let words = nested_fixture(Spoiler::None);
-    assert_eq!((on.loop_entry_exits, off.loop_entry_exits), (1, 0));
+    assert_eq!((on.loop_entry_exits, off.loop_entry_exits), (2, 0));

The commit also adds the_nested_fixture_is_what_its_comments_say, which checks the decoded words and
branch targets.

Results on that branch:

  • cargo test -p victory-shader --lib: 283 passed.
  • clippy (x86_64-pc-windows-gnullvm, --all-targets, -D warnings): clean.
  • Wine halves_tests (M5 Pro, D3DMetal): 86 passed. The GPU test matches the console with and
    without the switch; 32,768 groups take 16.0 ms with it and 72.3 ms without.

Recommendation. There's no need to move the rewrite. The loops #591 takes are already handled:
their lockstep vote starts from the early exit's predicate, so lanes that left never count as
staying. The loops still on the per-lane path are where note_loop_exit sits.

Keep #610 with the fixture fix and the switch off by default:

If you'd rather close it, the cost today is unknown but bounded to those 68 programs (16 in the cell
frame). An in-game A/B with VICTORY_LOOP_ENTRY_EXIT=0/1 on current main would settle whether it is
worth a default-on.

@buddybot89

Copy link
Copy Markdown

Ran this PR's tests on an M2 Ultra (64 GB, macOS 26.7.1, D3DMetal 4.0b3) at the current head ce53982. Two of them fail, and the cause is the last merge of main, not the GPU:

  • emit::lower::entry_exit::tests::the_loop_exit_is_rewritten_only_with_the_switch_and_where_exact fails at entry_exit.rs:548 (rewritten(&plain, true) is 0, not 1). This also fails in a native cargo test -p victory-shader --lib entry_exit on macOS, so it doesn't depend on the host.
  • emit::halves_tests::early_exited_lanes_leave_a_later_loop_as_the_console_on_every_gpu fails at halves_tests.rs:4115 with (0, 0) against (1, 0), for the same reason.

At 8fecb78 (before the 1f560a6 merge of main) the five entry_exit tests pass. After the merge, the fixture's loop is lowered in lockstep. A probe at the end of lowering shows lockstep_headers=1 in_lockstep_loop=2 lockstep_exits=1 counters=0. The conditional-branch path that calls note_loop_exit is never reached for it, so no candidate is noted. The likely cause is #591 (06a9ea2, "run while-shaped divergent loops in lockstep in halves"), which came in with that merge.

Both in-game measurements above were taken on d1609d9, which doesn't have #591. It may be worth checking whether CS_VisHair's loop now takes the lockstep path on main, and if so, whether that already avoids the spin or whether the rewrite needs to apply inside lockstep loops too.

Everything else passed: victory-shader --lib 537 passed / 2 failed (the two above) / 5 ignored. halves: 96 passed / 1 failed. the_loop_entry_exit_switch_keys_the_cache passed.

@nickorlabs

Copy link
Copy Markdown
Contributor

Open PR; please review when time permits. I’m not seeing a merge conflict yet.

@nickorlabs

Copy link
Copy Markdown
Contributor

Requesting changes: update the fixture and merge to current main. The CI failure is exactly the fixture no longer accounting for #591's lockstep path. The rewrite itself should stay on the per-lane path, unless you can show a lockstep loop that still needs an exit rewrite.

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.

7 participants