Skip to content

Shaders: a lane-branch region that only raises an LDS flag runs as two host waves (one more wave64 compute on NVIDIA) - #592

Open
FrancescoGelosoEterea wants to merge 1 commit into
fxceless:mainfrom
FrancescoGelosoEterea:lds-flags
Open

FrancescoGelosoEterea wants to merge 1 commit into
fxceless:mainfrom
FrancescoGelosoEterea:lds-flags

Conversation

@FrancescoGelosoEterea

Copy link
Copy Markdown

Why

On a 32-lane host (NVIDIA), a console wave64 compute program with LDS in a group over 32 threads runs as two host waves. lds_meetings makes them meet at group barriers on the edges of every lane-branch region that touches LDS. It refuses a region that both reads and writes LDS, because a read inside it may miss the other host wave's write. Such a program stays at WaveSize(64), which the driver refuses:

host pipeline refused error=0x80070057 shaders=[compute 2cc4c197ee29e291]

This is sr_tracing:CS_Tiling_Generate_Opaque, one of the wave64 computes still refused on NVIDIA (#7, #11). It uses LDS only as two group-wide flags. One lane zeroes them. Inside per-lane branches and a loop, lanes write 1 to one flag and read it back to leave the loop early. After the region, every lane reads both flags.

What

The new lds_flag_region in emit/lower.rs checks a region that reads and writes LDS. If the check passes, lds_meetings keeps the region instead of refusing it. The barriers on its edges stay the same as for any other region. The check requires all of the following:

  • every LDS access in the region is a ds_read_b32 or ds_write_b32 at a constant address, and every write stores the same constant;
  • at most one address is both read and written in the region (the flag), and every write a lane can reach after one of its reads goes to that flag;
  • the region has no other effect: no store, atomic, export, message or barrier;
  • no register the region writes is live, lane by lane, where a lane leaves it. A lane's own unguarded write kills a register. The read of a VGPR's old value, which only the lanes outside EXEC keep, does not count as a use.

Under these conditions a read that misses the other half's write changes nothing the region leaves behind:

  • the lane only goes on as if the flag were still down;
  • anything that lane writes is the flag's own constant, which the missed write has already put there.

So the flag ends up raised exactly when some lane raises it, as on the console, and nothing else depends on when the lane saw it. VICTORY_LDS_FLAGS=0 turns the check off.

For this program the lowering then takes the exact "local waves (idiom)" form, not an approximate one, with WaveSize(32). In the emitted DXIL all 8 group barriers sit in blocks every thread reaches (the entry and the joins after the branches), never inside a branch.

Tested

RTX 5070 Ti, driver 621.24, Windows 11. Own 1.0.2.1 copy.

  • Offline, the whole shader pack (translate --validate --pipelines --list on shaders.rpf with VICTORY_HOST_MAX_WAVE=32, base c96b4f2 against this branch): of 25,889 programs, exactly one changes: 2cc4c197… goes from refused (E_INVALIDARG) to created. Nothing is lost. Compute pipelines created go from 2,645 to 2,646; every other count (emitted, validated, graphics and mesh pipelines) is the same.
  • Tests: two new tests in wave64_tests.rs, on a hand-assembled 64-thread program.
    • A branch that raises a flag and reads it back lowers to WaveSize(32). This test fails with VICTORY_LDS_FLAGS=0.
    • A branch that writes the flag a second, different value after its read stays at 64.
    • cargo test -p victory-shader --lib: 216 passed.
    • cargo clippy -p victory-shader --all-targets -- -D warnings: clean.
  • In game (prologue, 7 minutes in the world, on a branch with this change plus wave64: halve programs whose every LDS access names only its own lane's words #158, Certify Wave32 LDS synchronization for visibility dispatch #368 and other open PRs, VICTORY_SPLIT_LDS=1):
    • host pipeline shaders=[compute 2cc4c197ee29e291] is created and bound;
    • no device removal, crash or dropped dispatch;
    • the room renders as before;
    • the computes still refused there are 02384a60… and 6b82bc7d….

The two that are left (CS_DefragHeap_ComputeRelocations, CS_CollectTriangles_Meshlets) use LDS atomics and lane reads across halves, which this check does not cover.

🤖 Generated with Claude Code

…o host waves

A console wave64 program with LDS in a group over 32 threads runs on a
32-lane host as two host waves that meet at group barriers on the edges of
each lane-branch region. A region that both reads and writes LDS was
refused, since a read inside it may miss the other half's write.

That changes nothing the region leaves behind when it only raises a flag:
every access is a ds_read_b32/ds_write_b32 at a constant address, every
write stores the same constant, at most one address is both read and
written, every write a lane can reach after a read goes to that flag, the
region has no other effect, and no register it writes is live (lane by
lane) where a lane leaves it. A missed write then only keeps a lane going
as if the flag were down, and what it writes is the constant already
there. VICTORY_LDS_FLAGS=0 turns this off.

sr_tracing:CS_Tiling_Generate_Opaque (2cc4c197ee29e291) now translates in
waves of 32 and its pipeline is created on an RTX 5070 Ti. Translating
the whole shader pack for a 32-lane host, it is the only program whose
outcome changes.

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

@kaayzouee kaayzouee left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code review — request changes

Reviewed 8bc48bf. The optimization addresses a distinct issue; the target branch still rejects mixed LDS-read/write lane regions. The reported pipeline-creation and gameplay results are useful, but they do not establish the correctness of this general-purpose, default-enabled compiler transformation.

Blocking: the flag-region proof does not establish termination

lds_flag_region() limits stores to a single value and checks register liveness at region exits. Neither condition proves that lanes actually reach those exits under a different inter-wave schedule.

Consider the following schematic program, with the flag initialized to zero before the divergent region and participating lanes in both halves:

if lane < 63:
    while LDS[0] != 0:
        continue
    LDS[0] = 1
// reconverge; consume LDS[0]

On the original lockstep wave, all participating lanes can read zero, leave the loop, then write one. On split waves, one half can finish and write one before the second half first reads the flag. The second half can then remain in the loop indefinitely; the reconvergence barrier never completes.

This satisfies the stated flag constraints: one constant address, one stored value, no nonflag stores after a read, no other side effects, and no live temporary registers on exit. The reachability walk detects cycles but does not reject this pattern or establish a decreasing loop bound. This is a counterexample to the stated sufficient conditions, not an independently compiled reproducer of the complete lowering pipeline.

Please add a negative regression that exercises this kind of flag-dependent progress, and strengthen the analysis to prove termination/progress for the accepted loop idiom. A narrowly scoped recognizer for the actual bounded early-exit pattern is preferable to accepting arbitrary flag-dependent loops. At minimum, retain the old default behavior until these conditions are established.

High: the positive tests do not exercise the claimed semantic property

In flag_program(), the read of LDS writes v3, but the value is never consumed. The branch preceding the read is controlled by s1, not by the read. The optional second write is likewise independent of the read value. Both tests assert only the selected wave size.

Thus the positive test would pass even if LDS-dependent control flow were never analyzed correctly. It also does not exercise the loop that motivates this PR. Please add a synthetic shader where an LDS read actually controls an early exit, check resulting UAV contents on a host device where available, and add negative cases for live results, a nonflag write reachable after the read, and flag-dependent nontermination. Pipeline creation and DXIL validation alone cannot establish equivalence.

Analysis and maintainability

  • The new 244-line predicate combines constant resolution, memory effects, CFG traversal, and lane-aware liveness. Extract small, independently testable helpers for these responsibilities rather than keeping them in one function.
  • There are three similar successor closures across lds_meetings and lds_flag_region; reuse a single successor representation. The outer mixed-region loop does not need the intermediate collect::<Vec<_>>(), since the reads/writes arrays are not mutated there.
  • The liveness routine reconstructs operand semantics using mnemonic substrings and manually selected operand lists. The existing ir::operand_reads() already distinguishes true operands from old VGPR destination values. Consider reusing it, with explicit conservative handling of partial writes, guards, and the structured branch conditions. Avoid treating unrecognized instructions as proven side-effect-free.
  • The address sets compare byte addresses while the actual LDS lowering indexes by byte address shifted right by two. Explicitly reject unaligned or out-of-bounds constants in this new proof, or use the same validated dword identity. The base emitter already assumes alignment/bounds, but a proof of nonaliasing should not silently inherit that assumption.
  • Ordinary LDS loads/stores are emitted without an intra-region group fence. The proof needs to account for the host's weak memory ordering (see Direct3D shader memory consistency model), not just a sequential interleaving model.

Verdict

Request changes. The performance/compatibility motivation is sound, but a compiler transformation advertised as exact needs stronger semantic preconditions and regression tests that actually exercise those preconditions. Given that only one shader changes in the reported pack, a smaller, conservative recognizer is worth considering.

Static review only: I traced the region formation, predicate, IR operand handling, LDS lowering, and test construction. I did not independently compile the counterexample, run the shader pack, or execute GPU tests. The progress counterexample is to the documented analysis conditions; its exact end-to-end acceptance should be confirmed with a regression test.


This is an automated message, if you believe this is incorrect, please reply with the relevant technical context or a reproducible counterexample so the finding can be reassessed.

@Dathinel

Copy link
Copy Markdown
Contributor

Tested the lowerer from 8bc48bf on d510ee4 with an RTX 3050 Laptop (4 GB, driver 32.0.16.1062). The PR's two wave-size tests passed. I also dispatched its synthetic LDS flag program with one UAV output per thread, so a missing write could not pass as a cleared flag.

  • With the default setting, all 36 dispatches returned the expected 64 dwords each (2,304 values). Four consecutive runs passed.
  • With VICTORY_LDS_FLAGS=0, the same test binary stopped at host compute pipeline creation with an invalid-parameter error.

The inputs exercise both sides of the 32-thread boundary, each scalar branch outcome, and both same-value flag variants. This measures the synthetic program only. AI-assisted test and review.

Reproduce the hardware check

Append the following test to crates/victory-shader/src/emit/wave64_tests.rs with the PR applied. Run cargo test --locked -p victory-shader --lib -- lds_flag_rtx_readback --nocapture on the hardware adapter. Repeat with the environment variable above for the control.

#[test]
fn lds_flag_rtx_readback() {
    let host = Host::new(false).expect("hardware");
    for second in [None, Some(1)] {
        let mut native = flag_program(second);
        let last = native.code.len() - 12;
        let tail: Vec<u8> = [0xE070_0000u32, 0x8002_0500, S_ENDPGM]
            .iter()
            .flat_map(|w| w.to_le_bytes())
            .collect();
        assert_eq!(native.code[last..], tail);
        native.code.truncate(last);
        for word in [
            0x3406_0082, // v_lshlrev_b32 v3, 2, v0 (one dword per thread)
            0x4A0A_0A81, // v_add_nc_u32 v5, 1, v5 (zero now means unwritten)
            0xE070_1000,
            0x8002_0503,
            S_ENDPGM,
        ] {
            native.code.extend(word.to_le_bytes());
        }
        let p = crate::spill::build(&native).unwrap();
        let shader = lowered(&native, &p, &HashSet::new()).unwrap();
        let (root, pso) = host.compute_pipeline(&shader).expect("hardware pipeline");
        for below in [0u32, 1, 16, 31, 32, 33, 48, 63, 64] {
            for skip in [0, 1] {
                let mut ud = vec![0; shader.user_data_dwords().max(1) as usize];
                for u in &shader.user_data {
                    if let (RootType::Constants, 0, d @ 0..=1) = (u.root, u.slot, u.dword) {
                        ud[u.index as usize] = [below, skip][d as usize];
                    }
                }
                let out = host
                    .dispatch(
                        &root,
                        &pso,
                        &Dispatch {
                            roots: vec![(0, Root::Constants(ud))],
                            views: &[View::RawUav(64)],
                            samplers: &[],
                            groups: [1, 1, 1],
                        },
                    )
                    .expect("readback");
                assert_eq!(
                    out[0],
                    vec![1 + u32::from(below > 0); 64],
                    "below={below} skip={skip} second={second:?}"
                );
            }
        }
    }
}

@HAL9000RELOADED

Copy link
Copy Markdown

RX 7900 XTX (RDNA3), Windows 10 + #402 for SM 6.6, main d510ee4: both new tests pass on the card with this PR. With the tests alone on the base, a_branch_that_only_raises_an_lds_flag_runs_in_waves_of_32 fails. No other test changed. Run table: #129 (#129 (comment)).

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