Repository navigation
Shaders: a lane-branch region that only raises an LDS flag runs as two host waves (one more wave64 compute on NVIDIA) - #592
Conversation
…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
left a comment
There was a problem hiding this comment.
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_meetingsandlds_flag_region; reuse a single successor representation. The outer mixed-region loop does not need the intermediatecollect::<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.
… an LDS flag runs as two host waves 2cc4c197ee29e291 now gets a 32-lane pipeline on NVIDIA (refused before).
|
Tested the lowerer from
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 checkAppend the following test to #[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:?}"
);
}
}
}
} |
|
RX 7900 XTX (RDNA3), Windows 10 + #402 for SM 6.6, main |
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_meetingsmakes 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 atWaveSize(64), which the driver refuses: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 write1to one flag and read it back to leave the loop early. After the region, every lane reads both flags.What
The new
lds_flag_regioninemit/lower.rschecks a region that reads and writes LDS. If the check passes,lds_meetingskeeps 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:ds_read_b32ords_write_b32at a constant address, and every write stores the same constant;Under these conditions a read that misses the other half's write changes nothing the region leaves behind:
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=0turns 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.
translate --validate --pipelines --listonshaders.rpfwithVICTORY_HOST_MAX_WAVE=32, basec96b4f2against 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.wave64_tests.rs, on a hand-assembled 64-thread program.WaveSize(32). This test fails withVICTORY_LDS_FLAGS=0.cargo test -p victory-shader --lib: 216 passed.cargo clippy -p victory-shader --all-targets -- -D warnings: clean.VICTORY_SPLIT_LDS=1):host pipeline shaders=[compute 2cc4c197ee29e291]is created and bound;02384a60…and6b82bc7d….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