Skip to content

Water and Light Probe Shader Fix (Wave32 LDS Safety Proofs) - #1773

Merged
trustno1-coder merged 1 commit into
trustno1-coder:mainfrom
Remorce:fix/wave32-lds-safety-proofs
Nov 30, 2026
Merged

trustno1-coder merged 1 commit into
trustno1-coder:mainfrom
Remorce:fix/wave32-lds-safety-proofs

Conversation

@Remorce

@Remorce Remorce commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #43. On NVIDIA (32-lane waves), #43 requires proof that a wave64 program's LDS accesses are safe before splitting it across two 32-lane host waves. The water classification and light-probe variance filter shaders use safe patterns the analysis couldn't prove yet. On current main they translate only through a last-resort fallback: the wave-wide form, or failing that the write-only shortcut from before #43. This adds three proofs to #43's analysis that cover those patterns. With them, both shaders are lowered by exact proof in the normal split form and no longer go through the wave-wide fallback or the write-only shortcut. Every other shader's output is unchanged.

Summary

  • What this adds: three narrow proofs in emit/lds.rs:
    • values made under the write's own lane mask;
    • one constant per dword, inside loops too;
    • loop counters that step by the group size.
  • Why, with the fallbacks in place: the wave-wide form puts group barriers inside branches and loops, and the write-only shortcut is the rule shader: static Wave32 LDS alias and lane-private hazard analysis #43 tightened. With these proofs, both shaders no longer use the wave-wide form or the write-only shortcut: main only tries those for a program the normal lowering refuses, and these are no longer refused.
  • What stays refused: the tree culling and decal classification shaders still have a real read-after-atomic race between the halves, so they stay refused. VICTORY_LDS_WRITE_ONLY_OK is untouched.
  • Results: 6 of 2,675 programs change how they are lowered, and every other program's output is byte-for-byte unchanged.

Details

Values made under the write's own lane mask

eval_val treats any guarded definition as unknown. So v_mov v11, 0; v_mov v14, 1; ds_write_b32 v11, v14 offset:4 under one v_cmpx mask leaves the address and data unknown, and the region is "unproven".

A guarded definition now counts as known when every lane of the LDS instruction holds its guard. This is checked with Bools::meet, which answers "may meet" when it runs out of budget, so the check fails safe. The eval memo is keyed by the lanes looked at.

One constant per dword

Take a write-only region where every write puts a known constant at a constant address, with the same constant wherever two writes meet. It ends with the same bytes in any order of the two host halves, however often a loop repeats it, and nothing in the region reads those bytes. Such a region is now accepted even when it contains a loop. This is the "any lane sets the flag" idiom in CS_Classification_Water.

Loop counters stepping by the group

CS_VarianceFilterAlpha loads a tile into LDS with i = tid; while (...) { lds[(i << 2) + 0] = ...; lds[(i << 2) + 1280] = ...; i += 64 }.

The proof: for a counter that starts at the thread's linear index and steps by a multiple of the group size n (a power of two), thread t's counter stays t modulo n. With addresses of the form (counter << s) + off, take m = n << s. If each off % m and width fit in one slot, thread t only touches bytes [t << s, (t + 1) << s) modulo m, in every pass.

  • Different threads: two threads never touch the same bytes.
  • One thread: a thread that touches its own bytes again does so inside one host wave, in program order.
  • Loop bounds: no bound on the counter is needed, because m divides 2^32.

The shader rebuilds i from three bit fields before shifting it. The counter's bits are followed through shifts, masks, v_bfe_u32 and ORs of disjoint bits, so that reshuffle resolves to i << 2.

What stays refused

In InstanceCulling:CS_Tree_BatchCull* and vfx_proj_decal_vbuffer:CS_ProjDecalReduceClassification_Scalarized, one lane-divergent region covers most of the program. It has an LDS atomic early on and a read of the same address later, with nowhere to put a barrier. One half can read before the other half's atomics land. That looks like a real hazard rather than a gap in the proof, so they stay refused by default.

Results

Retail shaders, victory translate <game dir> --list with VICTORY_HOST_WAVE=32, from nick0451's run with this PR merged onto main d148613.

Now lowered by proof, no longer through the wave-wide or write-only fallback:

  • water_shading:CS_Classification_Water (0e366d15868e17bd)
  • indirect_light_probes:CS_VarianceFilterAlpha (5964b734c70b91eb)

Take an earlier, exact form:

  • sr_tracing:CS_Tiling_Generate_Water and _Alpha: from local waves (APPROXIMATE) to local waves (idiom).
  • water_shading:CS_VolumePortalTiling_Generate: from the "without skips" retry to "without early-outs".
  • TAA2:CS_TAA2_PrepareFrameStats: accepted as lane-private, the same loop pattern as the light probes.

Unchanged: the other 2,669 programs' emitted output, byte-for-byte.

Validation: every emitted compute program passes dxil.dll's validator. In game (RTX 3090, balcony save over open water), both shaders are translated and bound, the same 4 shaders are refused with and without this PR, and frame rate and visuals match.

Tests

Three new tests in emit::lds::tests, each with cases that must be accepted and cases that must be refused. All three accept cases fail on current main.

  • Lane mask:
    • accepted: a constant write under its own mask;
    • refused: a write under a different mask from the one its address was made under.
  • Constant loop:
    • accepted: the same constant written in a divergent loop;
    • refused: two different constants at one dword, or a lane-varying value.
  • Counter:
    • accepted: a counter stepping by the group, with arrays at 0 and 256, and at 0 and 1280 as in the retail shader;
    • refused: a second array at 4, a step of 32, or a counter not started at the thread index.

cargo test -p victory-shader --lib passes (351), and clippy is clean for the change.

…d, and loop counters stepping by the group

Three more cases trustno1-coder#43's analysis proves safe on 32-lane hosts:

- A value made under a lane guard is known to an LDS instruction whose lanes
  all hold that guard (checked on the guards with `meet`, which answers no
  when it gives up). Before, any guarded definition left the address or data
  unknown, so `v_mov v11, 0; v_mov v14, 1; ds_write_b32 v11, v14` under one
  mask was "unproven".
- A write-only region whose writes put a known constant at a constant
  address, the same constant wherever two writes meet, is accepted in a loop
  too: the bytes end the same in any order of the host halves.
- A loop counter that starts at the thread's linear index and steps by a
  multiple of the (power-of-two) group size keeps each thread in its own
  slots modulo `n << shift`, in every pass, when the addresses are
  `(counter << shift) + off` with each `off % m` and width inside one slot.
  The counter's bits are followed through shifts, masks, bit-field extracts
  and ORs of disjoint bits.

On the retail shaders with VICTORY_HOST_WAVE=32: water_shading
CS_Classification_Water (0e366d15868e17bd) and indirect_light_probes
CS_VarianceFilterAlpha (5964b734c70b91eb) translate again (37 -> 35 without
a wave32 lowering), and four that translated take an earlier form
(sr_tracing CS_Tiling_Generate_Water/Alpha leave the APPROXIMATE local
waves). Every other program's output is unchanged; all emitted compute
programs pass dxil.dll's validator.

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

Copy link
Copy Markdown
Contributor

Independent synthetic verification on Windows 11 x64, NVIDIA GeForce RTX 5080 (32-lane waves), Rust 1.98.1 MSVC, exact PR head 82221d1:

  • cargo test -p victory-shader --lib --locked emit::lds::tests -- --nocapture --test-threads=1: 24 passed, 0 failed (all 3 new safety-proof tests pass: a_write_under_its_own_lane_mask_reads_the_constants_made_under_it, the_same_constant_written_in_a_lane_loop_is_accepted_and_two_constants_are_not, and a_loop_counter_stepping_by_the_group_keeps_each_thread_in_its_own_slots).
  • Full cargo test -p victory-shader --lib --locked -- --test-threads=1 (skipping pre-existing NVIDIA heap_direct_texture_reads_mark_their_heap_index): 351 passed, 0 failed, 8 ignored.
  • Clean cherry-pick onto current main (f9dfb76) with zero conflicts and zero compiler warnings in lds.rs.

AI-assisted. Synthetic tests only.

@NotADonky43

Copy link
Copy Markdown
Contributor

RTX 5070 Ti / Windows / Series X: cherry-picked #1773 alone onto f9dfb76f and ran its LDS analysis tests (24 passed). Took the 12 distinct compute shaders that an actual warmed opening on f9 logged as refusing Wave32 translation. With the blanket LDS fallback left off, the patch recovered 1 of these 12 in offline translation. Then compared the corresponding 12 recorded PSO recipes in isolated caches with the same adapter, profile, sampler ordering and quarantine: stock 0/12 host pipelines made; with #1773 1/12. No worker crashed. This goes one step beyond translation success; it is not a shader-output parity, gameplay FPS or visual claim. The earlier 12 are runtime refusal samples, not the entire shader corpus. No title files or raw logs attached. Newer NVIDIA main has subsequently changed wave lowering; these numbers apply to f9.

@nick0451

Copy link
Copy Markdown

Tested against current main, where things have moved since this PR was opened. RTX 3090 (32-lane), Windows 11, this PR merged onto main d148613.

victory translate <game dir> --list with VICTORY_HOST_WAVE=32, main against this PR, every shader compared by output hash: of 2,675 shaders, exactly 6 differ, the ones the PR names. Every other output is byte-identical, as claimed.

shader main d148613 this PR
water_shading:CS_Classification_Water 0e366d15868e17bd emitted 4418d484… emitted 4cc19109…
indirect_light_probes:CS_VarianceFilterAlpha 5964b734c70b91eb emitted e40ec28c… emitted 88bc2d9b…
sr_tracing:CS_Tiling_Generate_Water / _Alpha emitted emitted (other output)
water_shading:CS_VolumePortalTiling_Generate emitted emitted (other output)
TAA2:CS_TAA2_PrepareFrameStats emitted emitted (other output)

Note: on current main the two headline shaders already translate. They're no longer refused, presumably through main's newer wave64 fallbacks (9bba2a2 wave-wide form, 3302735). So against today's main, this PR changes how those 6 are lowered (by its proofs, not the fallback) rather than bringing back dropped draws.

In game (balcony save, looking at open water, 2 rounds each after a warm-up): both shaders are translated and bound in both builds, with 4 refused shaders in both, the same set. 25.0 fps against main's 25.6 (inside the 2-3% noise). The water and sky look the same by eye in the screenshots. No crash.

🤖 Generated with Claude Code

@Melow-code Melow-code 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.

Read the proofs and ran them on Linux, 82221d1 merged onto main 568c5e5. One finding, in analysis time. I found no accepted program that is unsafe.

Finding: counter_bits takes exponential time on a shared DAG (emit/lds.rs, the v_or_b32 and v_or3_b32 arms). It is not memoized, unlike eval_val, and each v_or_b32 evaluates both operands. An OR of all-zero bits succeeds, so v_mov_b32 v2, 0 then N times v_or_b32 v2, v2, v2 ahead of a ds_write_b32 makes about 2^N calls; depth > 32 does not bound that usefully. run_analyze on that body, debug build, best of three:

levels main 568c5e5 this PR this PR with a memo
12 0.9 ms 17 ms 0.9 ms
16 1.0 ms 297 ms 1.2 ms
20 1.1 ms 5.8 s 2.2 ms

A chain from a value that is not zero is refused at the first level, and stays fast (2.3 ms at 20).

shared_dag_eval_val_stays_linear_time guards the same thing for eval_val. I have no real program with such a chain; it is a synthetic case. The memo I tried is a RefCell<HashMap<(Value, Option<Bool>), Option<(Option<Value>, [u8; 32])>>> around counter_bits, keyed by the value and use_lanes. The 28 emit::lds tests pass with it, three of them mine, and the check below accepts the same number of programs. (It also remembers a None that came from the depth limit, which only refuses more.) A test, to sit beside the existing one:

let mut inner = vec![v_mov_k(2, 0), v_mov_k(3, 5)];
for _ in 0..20 {
    inner.push(0x3800_0000 | 2 << 17 | 2 << 9 | 258); // v_or_b32 v2, v2, v2
}
inner.extend(ds_write_b32(2, 3, 0));
inner.extend(ds_read_b32(4, 2, 4));
inner.extend(store_uav(4));
let t = std::time::Instant::now();
let _ = run_analyze(&if_v0_lt_s0(&inner), [64, 1, 1], 1);
assert!(t.elapsed().as_secs() < 2, "{:?}", t.elapsed());

The strided proof held against brute force: 20,000 random loops (groups of 32, 64, 96 and 128, in one and two dimensions; one to three shifts, masks and ORs on the counter; random step, start and offsets; accesses of 1, 4, 8 and 16 bytes). 1,222 were accepted. Simulating 24 passes of every thread, none of them lets two threads touch one byte; 16,419 of the 18,778 refused ones do. A step or a start that only some lanes take is refused.

Also: cargo test -p victory-formats -p victory-shader --lib: 57 and 279 passed (three of them mine), 0 failed.

Not run: Windows, any card, the game's shaders. The same-constant and lane-mask proofs were read, not fuzzed.

AI-assisted review (Claude Code).

@steven-seagull27

Copy link
Copy Markdown
Contributor

To help address @Melow-code's counter_bits shared-DAG finding, I put together a 1-commit fast-forward patch directly on top of 82221d1 that you can cherry-pick or fast-forward into this PR:

What it changes (crates/victory-shader/src/emit/lds.rs)

  • Adds counter_bits_memo: RefCell<HashMap<(Value, Option<Bool>), Option<CounterBits>>> to AddrCtx alongside visiting/hit_cycle guards (mirroring eval_val), memoizing counter_bits across v_or_b32, v_or3_b32, v_lshl_or_b32, and v_and_or_b32.
  • Adds synthetic regression test shared_dag_counter_bits_stays_linear_time covering 20-level and 40-level v_or_b32 DAGs (including past depth > 32) and a 20-level v_or3_b32 DAG.

Synthetic before / after timings (debug build, Windows x64)

Synthetic shared DAG (run_analyze) 82221d1 (before) d6f46fd (with memo)
20-level v_or_b32 v2, v2, v2 (2^20 calls) 1.64 s 1.50 ms
40-level v_or_b32 v2, v2, v2 (crosses depth > 32) — 0.75 ms
13-level v_or3_b32 v2, v2, v2, v2 (3^13 calls) 2.65 s 0.35 ms
20-level v_or3_b32 v2, v2, v2, v2 (3^20 calls) — 0.88 ms

Verification

  • cargo test --locked -p victory-shader --lib -- emit::lds::tests --test-threads=1: 25 passed, 0 failed (0.17 s).
  • cargo clippy --locked -p victory-shader --lib --tests: zero warnings in lds.rs.

AI-assisted. Synthetic tests only.

@Melow-code

Copy link
Copy Markdown
Contributor

Checked d6f46fd: the finding from my review is fixed.

  • The shared-DAG case (v_mov_b32 v2, 0, then N times v_or_b32 v2, v2, v2): 1.3 to 3.7 ms from 8 to 20 levels (debug build, Linux, best of three; 5.8 s at 20 levels on 82221d1).
  • The same brute force on the strided proof as before: 20,000 random loops, the same 1,222 accepted, the same 18,778 refused, no accepted one unsafe.
  • cargo test -p victory-shader --lib emit::lds: 29 passed (three of them mine), 0 failed.

Read only: the cycle guard. A None from the depth limit is remembered too, which can only refuse more.

Not run: Windows, any card, the game's shaders.

AI-assisted (Claude Code).

@Remorce

Remorce commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor Author

@Melow-code @steven-seagull27 I've left the memo out for now, but I'm open to bringing it in and would like your view before this is merged.

My concern is whether this case is realistic for the game. The chain in the test is the same register ORed with itself 20 times, which I wouldn't expect a compiler to emit, and the full retail set (2,675 programs) translates through this PR without stalling. Even if a shader did hit it, the cost would be a one-time translation delay, not wrong output.

Have either of you seen address math in a real shader, from this title or another, that shares values deeply enough for this to matter? If so, I'm glad to bring it in here. If not, I'd lean towards landing it on its own later, next to the eval_val guard.

Apologies if I've misunderstood anything.

@Melow-code

Copy link
Copy Markdown
Contributor

@Remorc-e no, I have not seen it in a real shader, from this title or another. I do not have the title's programs, and my case was synthetic, made by reading the code. You read it right: it can only cost translation time, not a wrong result.

With the 2,675 programs translating without a stall, leaving it out here and landing it later next to the eval_val guard is fine with me. My check of d6f46fd above stands for whenever it is wanted.

AI-assisted (Claude Code).

Lyrnc added a commit to Lyrnc/VIctory-NVIDIA that referenced this pull request Nov 29, 2026
…r the threads that run it

Two more proofs for trustno1-coder#1435, on top of trustno1-coder#2358 (commutative atomics) and trustno1-coder#1773 (own-mask
values, one constant per dword, strided loop counters), whose commits come first here.

- Refinement D: at most one thread of the group runs the region's LDS instructions
  (`if (tid == 0) { ... }`). One thread is in one host wave and makes its accesses in
  program order, so whatever it reads or writes, the halves cannot see each other's order.
- Refinement E: over the threads that may run each access, no two threads touch one byte
  where one writes. `if (tid < 16) { lds[28 + 12 t]; lds[220 + 12 t]; }` overlaps over the
  whole group (thread 16's first slot is thread 0's second) but not over threads 0..15.

Which threads may run an LDS instruction: for each thread, the lane compares in its
block's reach and its guard whose operands are known per thread (constants and thread
ids) take that thread's outcome, constant masks its bit, other atoms stay free (a walk of
the decision diagram, with a node budget that answers "may run"). Free atoms only add
threads, so both proofs err towards refusing. Groups of more than 1024 threads are not
looked at.

Not taken, on purpose: a lane-branch region where several lanes of one host half read
what other lanes of it wrote with no barrier (a wave reduction under `tid < 32`). The
console wave saw those writes in lockstep; the host has no order between its lanes there.
That needs a lowering with a wave-level sync, not a proof.

Tests: one thread at tid 0, 40 and 63, under a branch and under v_cmpx; two threads
refused; an 8 x 8 group column refused; footprints accepted for 16 threads and refused
for 17; a read of the next thread's slot refused (across the halves and within one); one
or two atomic families in a lane loop (trustno1-coder#2358's proof).

The trustno1-coder#1773 commit was cherry-picked onto main with its Access fields merged next to trustno1-coder#2358's
(`atomic_alg` beside `data_const`, `strided`, `ds_off`) and both proofs in the read-write
check.

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

Lyrnc commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

Hardware check of this PR's pattern on a gfx1036 oracle (native wave64), against the 32-lane result on an RTX 5080 and a Radeon 680M. Hand-written wave64 cases matched in every case. On main those cases only translated through the folded form; with this PR they go to the plain split. Rebased onto current main together with the other LDS proof PR, the lds tests pass (51), and so does the full victory-shader lib apart from 3 failures that main has too.

#3441 is built on this PR and #2358/#1773 (the two conflict with each other; the resolution is in #3441). It adds two more proofs and takes the refused/folded count from 181 (main) via 162 (this pair) to 139.

AI use: Claude Code (Claude Opus 5.5).

moritz-eckhard-nickel added a commit to moritz-eckhard-nickel/VIctory-NVIDIA that referenced this pull request Nov 30, 2026
@trustno1-coder
trustno1-coder merged commit d611fcc into trustno1-coder:main Nov 30, 2026
3 of 5 checks passed
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