Skip to content

perf(shader): try the 64-bit atomic locks in rounds before the turns (opt-in) - #257

Merged
pragyaangaur merged 2 commits into
pragyaangaur:mainfrom
hackgods:perf/atomic-lock-rounds
Nov 26, 2026
Merged

pragyaangaur merged 2 commits into
pragyaangaur:mainfrom
hackgods:perf/atomic-lock-rounds

Conversation

@hackgods

Copy link
Copy Markdown
Contributor

Towards #240. These are two commits. The second is opt-in, so nothing changes by default except the pixel-stage fence in the first.

What changed

1. fix(shader): a fence pixel shaders may use in the 64-bit atomic locks. locked_atomic64 fenced with barrier mode 10 in every stage, and DXIL validation refuses mode 10 in a pixel shader. Pixel and other stages without groups now use mode 2 (the global UAV fence alone); compute and mesh keep mode 10. evan-kolberg found this and tested it on #240; the change is the one posted there.

2. perf(shader): the locks tried in rounds before the turns, behind VICTORY_ATOMIC_LOCK_ROUNDS=1.

  • Today the lanes of a wave take turns, one lane a turn, so one 64-bit atomic is up to 32 locked steps in a row, even when every lane's lock is different.
  • With the switch, every lane first makes one attempt at its lock in each of 4 rounds (ATOMIC_LOCK_ROUNDS) that all lanes run alike. The lanes that take it read, write and free it in that same round, all together.
  • No lane waits on a lock inside a round, so lanes of one wave still never wait for each other's locks, and all their locks are free again before the turns.
  • Only lanes still not done (they met another lane of their wave on one lock, or a lock held by another wave in every round) take turns, exactly as today. The turns sit in a branch that a wave whose lanes all finished skips. That needs no wave operation, since D3DMetal's misbehave in divergent code.
  • In pixel programs, helper lanes skip the lock: their atomics are discarded, so they could never take it, and in their turn they would spin to the 65,536 bound.
  • Results stay exact for every op, returned old values included. This is not the high-dword shortcut, so the tie question from [macOS / M2 Pro] Emulated 64-bit image atomics (atomic_locks) cost about 6 s of every world frame and cause the GPU resets; with VICTORY_ATOMIC_LOCKS=0 frames drop from 7.4 s to 1.5 s #240 doesn't arise.
  • Options::atomic_lock_rounds / Parts::atomic_lock_rounds carry it, and the shader cache keys on it (translation_build; changing_translation_settings_invalidates_the_prebuilt_list checks that).
  • The rest of the diff is the new field added to every Parts literal in the tests, following the pattern for narrow_waves.

Measurements (synthetic, no game)

M5 Pro (64 GB), macOS 27.2.1, D3DMetal 4.0 beta 3. One group of 32 lanes on distinct texels, with 16 and with 1,024 64-bit umax per lane. The difference between the two leaves the fixed costs of a run out, and only the dispatch is timed, not pipeline creation (atomic_lock_rounds_timing, ignored; --ignored --nocapture under tools/macos/test-wine.sh):

Form Per wave-wide 64-bit umax
Turns (today's default) 29.3 µs
Rounds, the turns always run (an intermediate version) 10.8 µs
Rounds, the turns skipped when all lanes are done (this PR) 6.4 µs

Also measured: removing the fences from the turns (unsafe, as an experiment only) saved about 8%, so the cost is the serial steps, not the fences.

This is not a game measurement. In the game, waves also meet on texels across draws (overdraw), which the rounds only partly absorb. cocobailey offered to run candidates on the M2 Pro with the tables from #240: with VICTORY_ATOMIC_LOCK_ROUNDS=1 and a fresh shader cache entry (the option keys it), the frame, GPU, Metal-error and queue-move columns would show what it does there.

How it was tested

No game files were used.

  • image_atomics_of_64_bits now runs in turns and in rounds (texel (0, 0) puts all 32 lanes on one lock, so the rounds finish a few and the rest take turns): passes on D3DMetal hardware in both.
  • New image_atomics_of_64_bits_in_rounds_match_the_turns (the random-input comparison asked for on [macOS / M2 Pro] Emulated 64-bit image atomics (atomic_locks) cost about 6 s of every world frame and cause the GPU resets; with VICTORY_ATOMIC_LOCKS=0 frames drop from 7.4 s to 1.5 s #240):
    • 6 random key sets. Each lane takes the umax of its key into one of 8 texels, with high dwords of 0 to 3, so ties on the high dword are frequent and the low dword decides.
    • As 1 group and as 8 groups meeting on the same locks.
    • Row 0 must match a CPU model, and be identical in turns and in rounds. Every returned old value must be 0 or a key that went into the same texel, and no lock may be left taken.
  • New image_atomic_adds_of_64_bits_apply_once: 64-bit adds of 0xFFFF_FFFF, all 32 lanes into one texel plus each lane into its own, as 1 and 8 groups. Adds aren't idempotent, so a lane applied in a round and again in a turn would show; the carry into the high dword is checked too.
  • tools/macos/test-wine.sh --workspace --no-fail-fast on the rebased branch: 1,052 passed, 0 failed, 22 ignored. (In one full run before the rebase, two watch::tests failed; they passed in five reruns, alone and in the whole victory-gpu crate, and don't involve shader code. This looks like the cross-test interference tracked in GPU tests that read back shader writes fail in about a third of runs on an M5 Max, never with one test thread #31.)
  • cargo test --workspace (native): 524 passed, 0 failed, 17 ignored.
  • cargo clippy --workspace --all-targets [--all-features] --locked -- -D warnings (gnullvm): clean, as CI runs it.
  • cargo xtask policy: 246 files ok.
  • Formatting: the changed lines and the new tests are rustfmt-clean. I didn't reformat untouched code.

Not covered:

  • The pixel-shader path on GPU. Host::draw binds no UAVs, so the helper-lane skip and the mode-2 fence are exercised only by evan-kolberg's validation, not on hardware here.
  • The converter warning. The Metal shader converter prints "Shader might rely on forward progress/persistent thread" for the lock shaders. Each lock loop is bounded, as before.

🤖 Generated with Claude Code

hackgods and others added 2 commits November 26, 2026 14:26
…ocks

`locked_atomic64` fenced with barrier mode 10 (the global unordered-access
fence and the group's) in every stage, and DXIL validation refuses mode 10
in a pixel shader. The alpha prepasses whose 64-bit `umax` runs under these
locks are pixel shaders. Pixel and other stages without groups now use the
global fence alone (mode 2); compute and mesh keep mode 10, so their DXIL
is unchanged. Found and tested by evan-kolberg on pragyaangaur#240.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…(opt-in)

Under D3DMetal every 64-bit image atomic runs under a lock, and the lanes
of a wave take turns, one lane a turn, so a wave's atomic is up to 32
locked steps in a row. On an M2 Pro these locks cost about 6 s of a 7.4 s
world frame (pragyaangaur#240).

With `VICTORY_ATOMIC_LOCK_ROUNDS=1` every lane first tries its lock once in
each of `ATOMIC_LOCK_ROUNDS` (4) rounds that all lanes run alike, and the
lanes that take it read, write and free it in that round together. No lane
waits on a lock inside a round, so lanes of one wave still never wait for
each other's locks, and their locks are free again before the turns. Only
lanes still not done take turns, as before, in a branch that a wave whose
lanes all finished skips. In pixel programs helper lanes skip the rounds
and the turns: their atomics are discarded, so they could never take a
lock and would spin to the bound in their turn.

On an M5 Pro with D3DMetal 4.0 beta 3, a wave's 64-bit umax on distinct
texels took 29 us in turns and 6 us in rounds (dispatch time only, 1,024
against 16 atomics per lane; `atomic_lock_rounds_timing`, ignored). The
rounds without the skipped branch took 11 us; without the fences the turns
took only 8 % less.

The option keys the shader cache. It stays opt-in until it is measured in
the game. Tests: `image_atomics_of_64_bits` in turns and in rounds (32
lanes on one lock among them), random umax keys with frequent high-dword
ties against a CPU model in both forms and with 8 groups meeting on the
same locks, and 64-bit adds that would show a lane applied twice.

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

Copy link
Copy Markdown
Contributor

Independent pixel-shader readback on the M4 Pro at 2fdd2e14756baa7d40c7b48c63fbd8bf020df62a. macOS 27.2.1 (26B131), CrossOver 26.3.0.39832, D3DMetal 4.0 beta 3. All inputs were generated.

  • Contended UMAX and returned old values. Turns → rounds → rounds → turns all passed. Each process drew four overlapping 8×8 passes into one R32G32_UINT texel with GLC enabled. Mixed high dwords and high-dword ties exercised the full comparison. Each set of 64 returned old values admitted a legal UMAX ordering. Across all four processes, 1,024 old values were checked, the final texel was (low=62, high=19), the lock readback was zero, and the canary matched.
  • Rounds-only boundary quad. One live pixel at (2,2) read the expected token 63 from its off-coverage quad neighbor (3,2) after the atomic. The other 63 target pixels kept their sentinels. The live pixel returned old (33,4) and the final texel was (55,4). The lock readback was zero and the canary matched. This witnesses helper participation at the quad read. The fixture did not instrument the lock guard itself.

Both mixed-operand shader variants and the boundary shader separately passed the native GPTK DXIL validator. These results cover generated hardware pixel correctness. Title frame pacing was outside this test.

Tested and summarized with Codex.

@GDemay

GDemay commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Read the full diff against #240's 09:34Z announcement and against the round model in #261. The landed form is honest to the 10:27Z update on #240 and to this PR's own body, but it is not the announced turns-with-round-attempts, and the bench's model needs a small update to rule on this exact code — I'll push that to #261.

The form. Rounds-then-turn-fallback: a new loop capped at ATOMIC_LOCK_ROUNDS = 4 runs first — per round every lane whose done flag is false makes exactly one atomicCompareExchange, and the winners run the read-modify-write in that round through the same step body the turns use. No spin inside a round. After round 4, lanes still not done enter today's turn loop unchanged — all 32 lane-index iterations of it — while finished lanes skip it on a per-lane branch with no wave op. A round winner never re-attempts and never takes a turn, so no lane can apply twice.

Counts vs #261's model (barriers/attempts/loop-iterations, single wave of 32, one CAS winner per contended word per round): one texel 64/150/36 vs modeled 64/528/32; four lanes per texel 8/80/4 — identical; distinct texels 2/32/4 vs 2/32/1; the test's program 66/182/40 vs modeled 66/560/33. Barriers match the model in every shape; attempts match at pool and own; at full collision the 4-round cap plus uncontended fallback turns give 150 attempts (122 in the rounds: 32+31+30+29, then 28 turns) instead of the modeled 528 — 4.7x today's lock-word traffic rather than the announcement-as-modeled's 16.5x, still today's 64 barriers plus an 118-CAS storm. #261's round fn should grow the 4-round cap and the fallback turn pass to model what ships; the direction of its worst-case warning stands, its magnitude drops 3.5x. One deliberate-looking price: the round loop always runs 4 iterations even when every lane finished in round 1 (no all-done early exit without a wave op), so the distinct-texel shape pays 3 empty iterations — branches only, no lock traffic.

Exactness looks right: the old values ride the phis from the round latch into the final result on the skip edge and from the turn latch on the turn edge; the op body is the unchanged step shared by both paths (add/sub/and/or/xor/min/max/swap/cmpxchg), so no op can diverge between forms; colliding lanes stay one-winner-per-word-per-round. The two new hardware tests meet the bar #240 asked for — random keys with forced high-dword ties against a CPU model, identical rows in both forms, per-lane old values checked, 1 and 8 groups; and a non-idempotent 64-bit add that would expose any double-apply.

The fence fix is evan-kolberg's #240 patch verbatim in its own commit, credited in the message, body and code. It changes the default path too (pixel and other group-less stages now fence mode 2, CS/MS keep mode 10) — worth restating in the merge note so a future bisect does not miss it.

Before this closes the 6 s of #240, three things stay open. (1) The 29.3 -> 6.4 us M5 numbers are synthetic and distinct-texel only; the game's cost is on the M2 Pro with overdraw meeting locks across draws, and the one-lock shapes pay more than today — cocobailey's M2 Pro tables with VICTORY_ATOMIC_LOCK_ROUNDS=1 and a fresh cache entry (frame, GPU, Metal errors, queue moves, fence/hair/props) are the merge gate. (2) The pixel path on GPU is only DXIL-validated in-tree (Host::draw binds no UAVs), so the helper-lane skip and the mode-2 fence have no hardware coverage here. (3) The cap of 4 exactly covers the four-lanes-per-texel prepass; heavier per-texel collisions fall back to turns after 4 rounds — correct, but worth a line in docs/macos.md if the prepass resolution ever changes. If the M2 Pro tables come back clean, flipping the default should be its own commit so a regression bisects to one change.

GDemay pushed a commit to GDemay/VIctory-macOS that referenced this pull request Nov 26, 2026
PR pragyaangaur#257 lands a different round form than pragyaangaur#240 announced: four rounds
capped, one attempt per lane not done in each, nobody spinning — then
today's turn loop whole, for whoever the rounds leave, its finished
lanes passing through. The bench's round model was the announcement's
unbounded rounds; this makes it the code that shipped.

The worst case it models shrinks with the cap: at one texel for every
lane, 150 attempts (122 in the rounds, 28 turns) against the modeled
528, the barriers unchanged at today's 64 — 4.7x today's lock-word
traffic, not the announcement's 16.5x. A wave of distinct locks still
finishes in the first round, paying three empty rounds for having no
wave operation to leave by; four lanes per texel is unchanged, the cap
exactly covering it.

Co-Authored-By: GLM 5.3 <noreply@z.ai>
@pragyaangaur
pragyaangaur merged commit a4e35b5 into pragyaangaur:main Nov 26, 2026
1 check passed
@evan-kolberg

Copy link
Copy Markdown
Contributor

I measured the pixel UMAX rounds path on an M4 Pro using a fixed generated workload at 2fdd2e14756baa7d40c7b48c63fbd8bf020df62a. The runtime was macOS 27.2.1 (26B131), CrossOver 26.3.0.39832 and D3DMetal 4.0 beta 3.

Pixels' destination Serial turns median Four rounds plus fallback median
64 distinct locks per draw 0.777 ms 0.375 ms
All 64 fragments share a texel 1.241 ms 1.240 ms

Each cell had four warmups and 16 measured batches. Each batch used one pre-recorded list, four 8×8 raster draws (256 UMAX calls), the same initialization, transitions and readback copies, and one queue fence. The timer covered host wall time from submission through fence completion. The modes alternated order in eight blocks per layout. With distinct locks, rounds saved 0.369–0.437 ms in every block. In the shared-texel layout the block differences crossed zero.

All 80 batches passed the returned-old-value history, final 64-bit image, cleared lock table and per-fence readback checks. On this workload, rounds took 48% of the serial median batch time with distinct locks and the shared-texel case shows no material change. The yard's lock distribution and the effect on its frame time are still open.

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.

4 participants