Prison cell bounce light dark in most launches: probe-ray hits rejected by material shader-ID check (diagnosis, not yet fixed) #3750

Open
opened 2026-11-28 14:48:27 +00:00 by gtport646 · 3 comments
gtport646 commented 2026-11-28 14:48:27 +00:00 (Migrated from github.com)
Contributor

Imported from Marvisak/VIctory. Originally posted by gtport646 on 2026-11-28T14:48:27Z.


The opening's prison cell (gameplay after the PROLOGUE card, Lucia at the window) loses its bounce light in most launches. The walls go grey, the area under the bunk turns black, and the pink/red cast seen on console is missing. On our builds it is dark in about 9 of 10 launches. It can also flip from dark to bright, or bright to dark, mid-run. KyleS98/VIctory-Neo documents the same dark patch on the left wall with the RT builder off (7 of ~55 runs), so the cause may not be RT-specific.

We have narrowed it down but not fixed it, and we are posting the diagnosis in case it helps anyone seeing the same thing.

Setup:

  • RTX 4090, Series S profile.
  • VICTORY_BVH_BUILDER=1, ambient stand-ins off.
  • Measured over ~100 launches.

What happens

  1. Hit shading returns zero. The dark state starts at the screen-probe hit shading (CS_RaytracingResolve variants, e.g. a5dcdb5ab74beaeb). About half the probe-ray hits on the cell's own geometry return radiance exactly 0. FinalGather, Inject and TemporalResolve only pass that on.

  2. The hits take an early store path. The hit shader takes the material record of the wave's first lane: instance desc +52 masked to 24 bits, plus the geometry index. It shades only if both checks pass:

    • the record's shader ID (word0 >> 22, in the 0x74-byte table at s4+0x480) equals the dispatch's shader ID;
    • the record's stamp equals the frame stamp.

    Otherwise it stores zero and exits (around 0x9a0–0xb08). In dark frames the shader-ID check fails; the stamp check holds.

  3. Two sides name different materials for the same hit.

    • Rays are binned per material from the TLAS: the trace f22a76fcb967ee59 @0x2d88 uses the instance node's contribution plus the leaf geometry.
    • The resolve recomputes the material from the title's instance-desc table, read through buffer views.
    • Example: one wall instance binned as material 0xd0 while the resolve computed 0xc1–0xc4.
  4. The instance tables are a two-frame ring. There are two tables per build (A and B), each double-buffered by frame. The TLAS stage (190fbf0ebe040169) reads them by address. CS_InstanceRotationFixup (969c1cef8b783b39) rotates them in place after the build is recorded in the same list.

  5. The outcome is decided at the camera cut into the cell (around frame 1500). Dark runs start bright and decay within 20–30 frames. Runs with multi-second frames near the cut come out bright more often (5/14 vs 0/9).

Ruled out, each with data

  • Descriptor/texture slots the hit shader picks: all current and uploaded in the dark state.
  • The heap cap: slots stay under about 123k.
  • Constants and NaN/Inf.
  • Dropped GI dispatches and late pipelines.
  • Alias copies of R9G9B9E5 views.
  • Sampler order.
  • Tile lists: all 3,600 MaterialTilesInitial tiles are listed.
  • Waterfall-loop shape (we already match Neo's "good" variant).
  • THIN=0.
  • CPU/GPU load, the clock, input timing, and the shader cache warm or cold.
  • Re-taking the by-address pages at submission instead of at recording.

Current leading hypothesis

A parity slip: the TLAS used by a frame's traces was built from one half of the instance ring, while the resolve's buffer views read the other half. That would give exactly the small contribution mismatches we see. Whether it happens would depend on how the layer's record/submit timing lines up with the ring at the cut. We are measuring this now.

Questions

  • Has anyone seen the cell (or other interiors) lose bounce light per launch, with or without the RT builder?
  • Does anyone's tree change when the TLAS build, or the instance-desc table it reads, is brought up to date relative to the resolve?
  • Has anyone looked at CS_InstanceRotationFixup or the instance-table ring?

Diagnostic switches we added for this (off by default) are available if useful: VICTORY_HEAP_PEEK, VICTORY_DESC_TRACE, VICTORY_ORDER_TRACE and VICTORY_PEEK_AT extensions.


Co-authored with Claude (Anthropic).

<!-- greyfinch-sync:Marvisak/VIctory:issue:6666701643 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/issues/3750). Originally posted by [gtport646](https://github.com/gtport646) on 2026-11-28T14:48:27Z. --- The opening's prison cell (gameplay after the PROLOGUE card, Lucia at the window) loses its bounce light in most launches. The walls go grey, the area under the bunk turns black, and the pink/red cast seen on console is missing. On our builds it is dark in about 9 of 10 launches. It can also flip from dark to bright, or bright to dark, mid-run. KyleS98/VIctory-Neo documents the same dark patch on the left wall with the RT builder **off** (7 of ~55 runs), so the cause may not be RT-specific. We have narrowed it down but not fixed it, and we are posting the diagnosis in case it helps anyone seeing the same thing. Setup: - RTX 4090, Series S profile. - `VICTORY_BVH_BUILDER=1`, ambient stand-ins off. - Measured over ~100 launches. ### What happens 1. **Hit shading returns zero.** The dark state starts at the screen-probe hit shading (`CS_RaytracingResolve` variants, e.g. `a5dcdb5ab74beaeb`). About half the probe-ray hits on the cell's own geometry return radiance exactly 0. FinalGather, Inject and TemporalResolve only pass that on. 2. **The hits take an early store path.** The hit shader takes the material record of the wave's first lane: instance desc `+52` masked to 24 bits, plus the geometry index. It shades only if both checks pass: - the record's shader ID (`word0 >> 22`, in the 0x74-byte table at `s4+0x480`) equals the dispatch's shader ID; - the record's stamp equals the frame stamp. Otherwise it stores zero and exits (around `0x9a0`–`0xb08`). In dark frames the **shader-ID** check fails; the stamp check holds. 3. **Two sides name different materials for the same hit.** - Rays are binned per material from the **TLAS**: the trace `f22a76fcb967ee59 @0x2d88` uses the instance node's contribution plus the leaf geometry. - The resolve recomputes the material from the title's **instance-desc table**, read through buffer views. - Example: one wall instance binned as material `0xd0` while the resolve computed `0xc1`–`0xc4`. 4. **The instance tables are a two-frame ring.** There are two tables per build (A and B), each double-buffered by frame. The TLAS stage (`190fbf0ebe040169`) reads them by address. `CS_InstanceRotationFixup` (`969c1cef8b783b39`) rotates them in place after the build is recorded in the same list. 5. **The outcome is decided at the camera cut into the cell** (around frame 1500). Dark runs start bright and decay within 20–30 frames. Runs with multi-second frames near the cut come out bright more often (5/14 vs 0/9). ### Ruled out, each with data - Descriptor/texture slots the hit shader picks: all current and uploaded in the dark state. - The heap cap: slots stay under about 123k. - Constants and NaN/Inf. - Dropped GI dispatches and late pipelines. - Alias copies of R9G9B9E5 views. - Sampler order. - Tile lists: all 3,600 MaterialTilesInitial tiles are listed. - Waterfall-loop shape (we already match Neo's "good" variant). - `THIN=0`. - CPU/GPU load, the clock, input timing, and the shader cache warm or cold. - Re-taking the by-address pages at submission instead of at recording. ### Current leading hypothesis A **parity slip**: the TLAS used by a frame's traces was built from one half of the instance ring, while the resolve's buffer views read the other half. That would give exactly the small contribution mismatches we see. Whether it happens would depend on how the layer's record/submit timing lines up with the ring at the cut. We are measuring this now. ### Questions - Has anyone seen the cell (or other interiors) lose bounce light per launch, with or without the RT builder? - Does anyone's tree change when the TLAS build, or the instance-desc table it reads, is brought up to date relative to the resolve? - Has anyone looked at `CS_InstanceRotationFixup` or the instance-table ring? Diagnostic switches we added for this (off by default) are available if useful: `VICTORY_HEAP_PEEK`, `VICTORY_DESC_TRACE`, `VICTORY_ORDER_TRACE` and `VICTORY_PEEK_AT` extensions. --- Co-authored with Claude (Anthropic).
gtport646 commented 2026-11-28 16:15:08 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Marvisak/VIctory. Originally posted by gtport646 on 2026-11-28T16:15:08Z.


Update: fixed on our side, with two causes. The cell now comes out lit in 5 of 5 launches through frame 3000+, about 61-63 under the bunk against about 60 on the console (RTX 4090, Series S, VICTORY_BVH_BUILDER=1, no ambient stand-ins).

Cause 1: shader-bin offsets computed as two 32-lane halves

CS_GenerateShaderBinOffsets (8dd8d739047fe557) is one 64-lane console wave doing a prefix sum over all 64 lanes, with lane 63 adding the total. Our translator had no exact form for it on a 32-lane host, so it ran each 32-lane half as its own wave, each summing alone. Bin offsets then overlapped wherever bins fell in both halves. That happens when the set of hit shaders in view changes, which is exactly the camera cut into the cell. Whole waves of probe-ray hits were binned under the wrong shader, and the hit shader (a5dcdb5ab74beaeb) rejected them on its shader-ID check and stored zero.

Fix: give that program the exact wave-wide form (one branch taken by the whole wave). The rejection burst at the cut disappears. If your tree runs wave64 programs as two host waves, check which form this program gets. With VICTORY_HOST_MAX_WAVE=32 VICTORY_WAVE_WHY=1 victory translate --list <dir>, any "local waves" or "approximate" form here is the bug.

Cause 2: compacted-size copy taken before the builder ran (port of Iweisc/leopard 6ab839ebdc)

The title asks the BVH builder for a structure's compacted size, then copies it out of the builder's small result buffer in the same command list. We made that copy on the CPU at submission, before the list's own dispatches ran, so it read the old size. The title then gave the structure room for the wrong size, and the copy into that room overwrote neighbouring structures. Hits that walk a corrupted structure stay dark without tripping the shader-ID check, which matched the runs that were dark with zero rejections.

Fix: a copy whose source is a builder result page is recorded on the card at its place in the list, into a read-back buffer that lands with the list. That's about 4,100 such copies per run in the opening. With it off, the cell drops back to 52-55.

Things that did not help

  • Re-taking by-address pages at submission.
  • Forcing the irradiance-cache programs wave-wide (this made the cell darker).
  • Sampler order, waterfall-loop shape, THIN=0.

@KyleS98: your dark left wall with the builder off might be cause 1, or another inexact wave64 translation. We can share the patches if useful.


Co-authored with Claude (Anthropic).

<!-- greyfinch-sync:Marvisak/VIctory:comment:7242092695 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/issues/3750#issuecomment-7242092695). Originally posted by [gtport646](https://github.com/gtport646) on 2026-11-28T16:15:08Z. --- **Update: fixed on our side, with two causes.** The cell now comes out lit in 5 of 5 launches through frame 3000+, about 61-63 under the bunk against about 60 on the console (RTX 4090, Series S, `VICTORY_BVH_BUILDER=1`, no ambient stand-ins). ### Cause 1: shader-bin offsets computed as two 32-lane halves `CS_GenerateShaderBinOffsets` (`8dd8d739047fe557`) is one 64-lane console wave doing a prefix sum over all 64 lanes, with lane 63 adding the total. Our translator had no exact form for it on a 32-lane host, so it ran each 32-lane half as its own wave, each summing alone. Bin offsets then overlapped wherever bins fell in both halves. That happens when the set of hit shaders in view changes, which is exactly the camera cut into the cell. Whole waves of probe-ray hits were binned under the wrong shader, and the hit shader (`a5dcdb5ab74beaeb`) rejected them on its shader-ID check and stored zero. **Fix:** give that program the exact wave-wide form (one branch taken by the whole wave). The rejection burst at the cut disappears. If your tree runs wave64 programs as two host waves, check which form this program gets. With `VICTORY_HOST_MAX_WAVE=32 VICTORY_WAVE_WHY=1 victory translate --list <dir>`, any "local waves" or "approximate" form here is the bug. ### Cause 2: compacted-size copy taken before the builder ran (port of Iweisc/leopard `6ab839ebdc`) The title asks the BVH builder for a structure's compacted size, then copies it out of the builder's small result buffer in the same command list. We made that copy on the CPU at submission, before the list's own dispatches ran, so it read the old size. The title then gave the structure room for the wrong size, and the copy into that room overwrote neighbouring structures. Hits that walk a corrupted structure stay dark without tripping the shader-ID check, which matched the runs that were dark with zero rejections. **Fix:** a copy whose source is a builder result page is recorded on the card at its place in the list, into a read-back buffer that lands with the list. That's about 4,100 such copies per run in the opening. With it off, the cell drops back to 52-55. ### Things that did not help - Re-taking by-address pages at submission. - Forcing the irradiance-cache programs wave-wide (this made the cell darker). - Sampler order, waterfall-loop shape, `THIN=0`. @KyleS98: your dark left wall with the builder off might be cause 1, or another inexact wave64 translation. We can share the patches if useful. --- Co-authored with Claude (Anthropic).
gtport646 commented 2026-11-29 03:38:41 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Marvisak/VIctory. Originally posted by gtport646 on 2026-11-29T03:38:41Z.


Update: a third cause, fixed. It may affect anyone running with VICTORY_BVH_BUILDER=1 on a 32-lane GPU (NVIDIA).

The title's streamed ray-tracing structures were unpacked with a garbage root in ~41% of cases on 32-lane hosts. XboxBvhBuilder's Box16Rehydration (caa78b8ca62bc3d6) and Box32Rehydration (28918b7150a7aad5) unpack one level of a streamed structure's boxes in place. Each group is one 64-lane console wave, dispatched counted in threads, so the last group of each level is partial (the root's level is always a single node). Both programs take s_bcnt1 exec on entry as the level's node count and use it to find each lane's children. Our translator only honoured the thread count for wave64 programs on 64-lane hosts. On a 32-lane host all 64 lanes ran, every partial group read children from the wrong place, and the root came out as garbage. Rays then make one box test at the root and never reach a triangle. Walls, floors and fixtures are mostly these streamed structures, so close-range rays miss them.

What it fixed for us (RTX 4090, Series S, builder on, 4 launches plus a control run with the switch off on the same exe):

  • garbage roots (dumped structures checked against title memory): 41% → ~1.3%
  • irradiance-cache gather hits within 2 m of the camera: 7–11% → 77–92%
  • irradiance-cache cells assigned a room: diner 0 → 233–411, prison cell 3 → ~840
  • the diner phone screen (emissive, 1,000×+ too dark through the room test) now matches the console, and the red cast under the cell bunk is gone

The fix is a port of Mangrove 75e590bac2's partial-active handling, plus one case it missed. Lanes past the dispatch count stay alive, because the split wave's barriers need them. They are excluded from memory accesses, from EXEC ballots and reductions, and from selects by EXEC lanes. The last part is the addition: these programs zero inactive lanes with s_or_saveexec + v_cndmask before their DPP prefix sums. Offline, exactly 4 programs change (Box16, Box32, PrefixSum256, PrefixSum512), all 52 builder programs validate, and none of the title's 2,996 own programs change. VICTORY_COUNTED_HALVES=0 restores the old behaviour, and the switch is part of the translation-cache key.

diff (2 files, +86 / -16)
diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs
index c0d7fbc651..0a6d55c008 100644
--- a/crates/victory-gpu/src/shader_cache.rs
+++ b/crates/victory-gpu/src/shader_cache.rs
@@ -67,6 +67,7 @@ fn build() -> [u8; 32] {
             "VICTORY_BIN_OFFSETS_WIDE",
             "VICTORY_IC_WIDE",
             "VICTORY_WIDE_DIGESTS",
+            "VICTORY_COUNTED_HALVES",
             "VICTORY_WAVE_DEEP_SKIPS",
             "VICTORY_WAVE_OWN_BITS",
             "VICTORY_WAVE_LOCAL",
diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs
index 141fb7bdd2..9c3f54f0d7 100644
--- a/crates/victory-shader/src/emit/lower.rs
+++ b/crates/victory-shader/src/emit/lower.rs
@@ -93,9 +93,17 @@ pub(crate) fn lower(parts: &Parts) -> Result<Lowered, ShaderError> {
 /// Whether the title dispatches the program by a count of threads whose last
 /// group may be partial: the structure builder's programs of one dimension.
 /// Their lanes past the count must not run (they count the lanes of a wave
-/// and store). Not where a group barrier would wait for lanes that left, nor
-/// where two host waves of 32 stand for a console wave (they exchange, which
-/// takes all lanes).
+/// and store). Not where a group barrier would wait for lanes that left. Where
+/// two host waves of 32 stand for a console wave (they exchange, which takes
+/// all lanes) the lanes past the count stay and are left out of memory, EXEC's
+/// ballots, the wave's reductions and selects by EXEC's lanes instead
+/// (`Lower::partial_active`; port of Mangrove 75e590bac2): the builder's box
+/// stages (Box16Rehydration, Box32Rehydration, one console wave of 64 lanes a
+/// group) take the count of EXEC's lanes on entry as their number of nodes, and
+/// with all 64 lanes the last group of every level read its nodes' children
+/// from the wrong place and stored garbage nodes past the level (the streamed
+/// structures' roots, run j1: 370 of 908 rehydrated structures in the cell).
+/// `VICTORY_COUNTED_HALVES=0`: as before (not counted on a 32-lane host).
 /// `VICTORY_NAN_SCRUB=1` (off by default): see `Lower::scrub_nan`. Ported
 /// from trustno1-coder/VIctory-NVIDIA (same AMD-fork lineage).
 pub(crate) fn nan_scrub() -> bool {
@@ -110,10 +118,16 @@ fn counted_in_threads(parts: &Parts) -> bool {
     cs.threads[0] > 1
         && cs.threads[1..] == [1, 1]
         && crate::spill::is_spilled(parts.native)
-        && (!parts.native.wave64 || host_max_wave() >= 64)
+        && (!parts.native.wave64 || host_max_wave() >= 64 || counted_halves())
         && !parts.p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "s_barrier")
 }
 
+/// `VICTORY_COUNTED_HALVES` (on unless `0`): see [`counted_in_threads`].
+pub(crate) fn counted_halves() -> bool {
+    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+    *ON.get_or_init(|| std::env::var_os("VICTORY_COUNTED_HALVES").is_none_or(|v| v != "0"))
+}
+
 /// [`lower`]; `counted`: the lanes past a dispatch's count of threads leave
 /// at once (`shader.rs` `USER_DISPATCH_THREADS_X`; after DexNom/VIctory
 /// bc3cd4b0, which does so for two of the programs by their digests).
@@ -370,6 +384,11 @@ struct Lower<'a> {
     /// handed to host waves (`wave_base`), and the base made in the entry block.
     halves: Option<u32>,
     wave_base: Option<V>,
+    /// A partial final group (`USER_DISPATCH_THREADS_X`) whose console waves are two host
+    /// waves: the threads past the count stay for the exchange's group barriers, so they
+    /// cannot leave at entry; this says which threads the console launched, and memory,
+    /// EXEC's ballots, the wave's reductions and selects by EXEC's lanes leave the others out.
+    partial_active: Option<V>,
     /// Vertex and mesh outputs holding 16-bit values: row, whether two per
     /// dword, and the row packed after it.
     half_outputs: HashMap<u8, (bool, Option<u8>)>,
@@ -1773,6 +1792,7 @@ impl<'a> Lower<'a> {
             pair: None,
             halves,
             wave_base: None,
+            partial_active: None,
             flat: None,
             no_barrier,
             fence_only,
@@ -1894,7 +1914,7 @@ impl<'a> Lower<'a> {
             .scalar
             .get(&(b, i))
             .ok_or("an untracked global address")?;
-        let guard = self.guard(b, i)?;
+        let guard = self.memory_guard(b, i)?;
         let Some(Operand::Vector { reg, .. }) = *dst else {
             return Err("a global load result");
         };
@@ -2053,6 +2073,7 @@ impl<'a> Lower<'a> {
                     .get(&mask)
                     .ok_or("a wave reduction's untracked mask")?;
                 let on = self.boolean(m, c)?;
+                let on = self.launched(c, on, mask);
                 let x = self.i32_of(src)?;
                 let id = self.s.m.i32(ident);
                 return Ok(self.s.m.select(c, on, x, id));
@@ -2083,6 +2104,7 @@ impl<'a> Lower<'a> {
             .get(&mask)
             .ok_or("a wave reduction's untracked mask")?;
         let on = self.boolean(m, c)?;
+        let on = self.launched(c, on, mask);
         let x = self.i32_of(src)?;
         let id = self.s.m.i32(ident);
         let x = self.s.m.select(c, on, x, id);
@@ -2229,6 +2251,7 @@ impl<'a> Lower<'a> {
             .get(&mask)
             .ok_or("a wave reduction's untracked mask")?;
         let on = self.boolean(m, c)?;
+        let on = self.launched(c, on, mask);
         let lo = self.i32_of(lo)?;
         let hi = self.i32_of(hi)?;
         let z = self.s.m.i32(0);
@@ -2410,10 +2433,16 @@ impl<'a> Lower<'a> {
             let all = self.s.m.cmp(original, pred::EQ, limit, zero);
             let inside = self.s.m.cmp(original, pred::IULT, x, limit);
             let runs = self.s.m.bin(original, Bin::Or, all, inside);
-            let (body, done) = (self.s.m.new_block(), self.s.m.new_block());
-            self.s.m.terminate(original, Term::CondBr(runs, body, done));
-            self.s.m.terminate(done, Term::Ret);
-            self.s.entry = body;
+            if self.halves.is_some() || self.exchange.is_some() {
+                // A console wave in two host waves exchanges through group
+                // barriers, which every thread must reach: the threads stay.
+                self.partial_active = Some(runs);
+            } else {
+                let (body, done) = (self.s.m.new_block(), self.s.m.new_block());
+                self.s.m.terminate(original, Term::CondBr(runs, body, done));
+                self.s.m.terminate(done, Term::Ret);
+                self.s.entry = body;
+            }
         }
         self.find_coherent();
         let order = crate::ir::reverse_postorder(&p.blocks);
@@ -3356,7 +3385,7 @@ impl<'a> Lower<'a> {
         };
         let (lo, hi) = (word(self, 0)?, word(self, 1)?);
         let (lo, hi) = self.address_plus(lo, hi, i32::from(*offset));
-        let guard = self.guard(b, i)?;
+        let guard = self.memory_guard(b, i)?;
         let (i32t, res, void) = (self.s.t.i32, self.s.t.res_ret, self.s.t.void);
         let iu = self.s.m.undef(i32t);
         let align = self.s.m.i32(4);
@@ -3611,6 +3640,7 @@ impl<'a> Lower<'a> {
                 let bit = self.boolean(m, at);
                 self.balloting.remove(&lo);
                 let bit = bit?;
+                let bit = self.launched(at, bit, lo);
                 let i32t = self.s.t.i32;
                 let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
                 let r = self
@@ -4334,7 +4364,11 @@ impl<'a> Lower<'a> {
             Some(b) if b == self.cur_ir => self.cur,
             Some(b) => self.tail[b].ok_or("a lane mask written after its use")?,
         };
-        let bit = self.boolean(m, at)?;
+        let mut bit = self.boolean(m, at)?;
+        if let Some(a) = self.partial_active {
+            // (a mask ANDed with EXEC: the threads kept for barriers have no bit)
+            bit = self.s.m.bin(at, Bin::And, bit, a);
+        }
         let (i1t, i32t) = (self.s.t.i1, self.s.t.i32);
         let some = self.s.op(at, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[bit]);
         self.s.flags |= flags::WAVE_OPS;
@@ -4378,12 +4412,16 @@ impl<'a> Lower<'a> {
         // what the halves exchange is "some lane speaks against" either way (for `any`:
         // some lane's `when` holds; else: some lane's does not), so a half with no lane says
         // nothing
-        let set = if any {
+        let mut set = if any {
             mine
         } else {
             let t = self.s.m.bool(true);
             self.s.m.bin(c, Bin::Xor, mine, t)
         };
+        if let Some(a) = self.partial_active {
+            // (a thread the console did not launch says nothing)
+            set = self.s.m.bin(c, Bin::And, set, a);
+        }
         let (i1t, i32t) = (self.s.t.i1, self.s.t.i32);
         let some = self.s.op(c, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[set]);
         self.s.flags |= flags::WAVE_OPS;
@@ -4459,6 +4497,25 @@ impl<'a> Lower<'a> {
         inst.write(pick(reg)?)
     }
 
+    /// [`Self::guard`] of a memory access: not by the threads a partial final group only
+    /// keeps for its barriers ([`Self::partial_active`]).
+    fn memory_guard(&mut self, b: usize, i: usize) -> Result<Option<V>, Why> {
+        let g = self.guard(b, i)?;
+        Ok(match (g, self.partial_active) {
+            (Some(g), Some(a)) => Some(self.s.m.bin(self.cur, Bin::And, g, a)),
+            (g, a) => g.or(a),
+        })
+    }
+
+    /// `on` (the lanes of a mask, at `at`) without the threads a partial final group keeps
+    /// for its barriers, when the mask is of EXEC's lanes (`Structured::active`).
+    fn launched(&mut self, at: usize, on: V, mask: Value) -> V {
+        match self.partial_active {
+            Some(a) if self.x.st.active.contains(&mask) => self.s.m.bin(at, Bin::And, on, a),
+            _ => on,
+        }
+    }
+
     fn guard(&mut self, b: usize, i: usize) -> Result<Option<V>, Why> {
         match self.x.st.guards[b][i] {
             None => Ok(None),
@@ -5001,7 +5058,12 @@ impl<'a> Lower<'a> {
             return Err("GDS");
         }
         let name = inst.name();
-        let guard = self.guard(b, i)?;
+        // (a lane read leaves no access behind: the threads kept for barriers take part)
+        let guard = if name == "ds_swizzle_b32" || name.contains("permute") {
+            self.guard(b, i)?
+        } else {
+            self.memory_guard(b, i)?
+        };
         let c = self.cur;
         let offset = u32::from(*offset0) | u32::from(*offset1) << 8;
         let dst_reg = match dst {
@@ -8798,7 +8860,14 @@ impl<'a> Lower<'a> {
                 };
                 const UNTRACKED: Why = "a select on an untracked mask";
                 let cond = match mask.and_then(|m| self.x.st.masks.get(&m).copied()) {
-                    Some(m) => self.boolean(m, c)?,
+                    Some(m) => {
+                        let on = self.boolean(m, c)?;
+                        // (a select by EXEC's lanes: a thread kept for barriers has no bit)
+                        match mask {
+                            Some(lo) => self.launched(c, on, lo),
+                            None => on,
+                        }
+                    }
                     // A mask the code holds as a number (a constant bit
                     // pattern: every other lane, every other pair...):
                     // this lane's bit of it. Exact where host lanes are
@@ -10956,7 +11025,7 @@ impl<'a> Lower<'a> {
         // A load or sample with no channel enabled returns the first.
         let dmask = if *dmask == 0 { &1 } else { dmask };
         let site = (b, i);
-        let guard = self.guard(b, i)?;
+        let guard = self.memory_guard(b, i)?;
         let c = self.cur;
         let (kind, coords) = match dim {
             0 => (1, 1),
@@ -11815,7 +11884,7 @@ impl<'a> Lower<'a> {
             return Err(name);
         }
         let site = (b, i);
-        let guard = self.guard(b, i)?;
+        let guard = self.memory_guard(b, i)?;
         let c = self.cur;
         let store = name.starts_with("buffer_store_");
         // DXIL atomic operations: add, and, or, xor, signed and unsigned

About 1.3% of roots are still broken. They are the same structures in every run, so we're still investigating. The cell's bounce light is still about 0.5–0.7× the console's in its darkest corners, and that's what we're chasing next.


Co-authored with Claude (Anthropic).

<!-- greyfinch-sync:Marvisak/VIctory:comment:7250173262 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/issues/3750#issuecomment-7250173262). Originally posted by [gtport646](https://github.com/gtport646) on 2026-11-29T03:38:41Z. --- **Update: a third cause, fixed. It may affect anyone running with `VICTORY_BVH_BUILDER=1` on a 32-lane GPU (NVIDIA).** **The title's streamed ray-tracing structures were unpacked with a garbage root in ~41% of cases on 32-lane hosts.** `XboxBvhBuilder`'s `Box16Rehydration` (`caa78b8ca62bc3d6`) and `Box32Rehydration` (`28918b7150a7aad5`) unpack one level of a streamed structure's boxes in place. Each group is one 64-lane console wave, dispatched **counted in threads**, so the last group of each level is partial (the root's level is always a single node). Both programs take `s_bcnt1 exec` on entry as the level's node count and use it to find each lane's children. Our translator only honoured the thread count for wave64 programs on 64-lane hosts. On a 32-lane host all 64 lanes ran, every partial group read children from the wrong place, and the root came out as garbage. Rays then make one box test at the root and never reach a triangle. Walls, floors and fixtures are mostly these streamed structures, so close-range rays miss them. What it fixed for us (RTX 4090, Series S, builder on, 4 launches plus a control run with the switch off on the same exe): - garbage roots (dumped structures checked against title memory): 41% → ~1.3% - irradiance-cache gather hits within 2 m of the camera: 7–11% → 77–92% - irradiance-cache cells assigned a room: diner 0 → 233–411, prison cell 3 → ~840 - the diner phone screen (emissive, 1,000×+ too dark through the room test) now matches the console, and the red cast under the cell bunk is gone **The fix** is a port of Mangrove `75e590bac2`'s partial-active handling, plus one case it missed. Lanes past the dispatch count stay alive, because the split wave's barriers need them. They are excluded from memory accesses, from EXEC ballots and reductions, and from selects by EXEC lanes. The last part is the addition: these programs zero inactive lanes with `s_or_saveexec` + `v_cndmask` before their DPP prefix sums. Offline, exactly 4 programs change (Box16, Box32, PrefixSum256, PrefixSum512), all 52 builder programs validate, and none of the title's 2,996 own programs change. `VICTORY_COUNTED_HALVES=0` restores the old behaviour, and the switch is part of the translation-cache key. <details><summary>diff (2 files, +86 / -16)</summary> ```diff diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index c0d7fbc651..0a6d55c008 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -67,6 +67,7 @@ fn build() -> [u8; 32] { "VICTORY_BIN_OFFSETS_WIDE", "VICTORY_IC_WIDE", "VICTORY_WIDE_DIGESTS", + "VICTORY_COUNTED_HALVES", "VICTORY_WAVE_DEEP_SKIPS", "VICTORY_WAVE_OWN_BITS", "VICTORY_WAVE_LOCAL", diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 141fb7bdd2..9c3f54f0d7 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -93,9 +93,17 @@ pub(crate) fn lower(parts: &Parts) -> Result<Lowered, ShaderError> { /// Whether the title dispatches the program by a count of threads whose last /// group may be partial: the structure builder's programs of one dimension. /// Their lanes past the count must not run (they count the lanes of a wave -/// and store). Not where a group barrier would wait for lanes that left, nor -/// where two host waves of 32 stand for a console wave (they exchange, which -/// takes all lanes). +/// and store). Not where a group barrier would wait for lanes that left. Where +/// two host waves of 32 stand for a console wave (they exchange, which takes +/// all lanes) the lanes past the count stay and are left out of memory, EXEC's +/// ballots, the wave's reductions and selects by EXEC's lanes instead +/// (`Lower::partial_active`; port of Mangrove 75e590bac2): the builder's box +/// stages (Box16Rehydration, Box32Rehydration, one console wave of 64 lanes a +/// group) take the count of EXEC's lanes on entry as their number of nodes, and +/// with all 64 lanes the last group of every level read its nodes' children +/// from the wrong place and stored garbage nodes past the level (the streamed +/// structures' roots, run j1: 370 of 908 rehydrated structures in the cell). +/// `VICTORY_COUNTED_HALVES=0`: as before (not counted on a 32-lane host). /// `VICTORY_NAN_SCRUB=1` (off by default): see `Lower::scrub_nan`. Ported /// from trustno1-coder/VIctory-NVIDIA (same AMD-fork lineage). pub(crate) fn nan_scrub() -> bool { @@ -110,10 +118,16 @@ fn counted_in_threads(parts: &Parts) -> bool { cs.threads[0] > 1 && cs.threads[1..] == [1, 1] && crate::spill::is_spilled(parts.native) - && (!parts.native.wave64 || host_max_wave() >= 64) + && (!parts.native.wave64 || host_max_wave() >= 64 || counted_halves()) && !parts.p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "s_barrier") } +/// `VICTORY_COUNTED_HALVES` (on unless `0`): see [`counted_in_threads`]. +pub(crate) fn counted_halves() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_COUNTED_HALVES").is_none_or(|v| v != "0")) +} + /// [`lower`]; `counted`: the lanes past a dispatch's count of threads leave /// at once (`shader.rs` `USER_DISPATCH_THREADS_X`; after DexNom/VIctory /// bc3cd4b0, which does so for two of the programs by their digests). @@ -370,6 +384,11 @@ struct Lower<'a> { /// handed to host waves (`wave_base`), and the base made in the entry block. halves: Option<u32>, wave_base: Option<V>, + /// A partial final group (`USER_DISPATCH_THREADS_X`) whose console waves are two host + /// waves: the threads past the count stay for the exchange's group barriers, so they + /// cannot leave at entry; this says which threads the console launched, and memory, + /// EXEC's ballots, the wave's reductions and selects by EXEC's lanes leave the others out. + partial_active: Option<V>, /// Vertex and mesh outputs holding 16-bit values: row, whether two per /// dword, and the row packed after it. half_outputs: HashMap<u8, (bool, Option<u8>)>, @@ -1773,6 +1792,7 @@ impl<'a> Lower<'a> { pair: None, halves, wave_base: None, + partial_active: None, flat: None, no_barrier, fence_only, @@ -1894,7 +1914,7 @@ impl<'a> Lower<'a> { .scalar .get(&(b, i)) .ok_or("an untracked global address")?; - let guard = self.guard(b, i)?; + let guard = self.memory_guard(b, i)?; let Some(Operand::Vector { reg, .. }) = *dst else { return Err("a global load result"); }; @@ -2053,6 +2073,7 @@ impl<'a> Lower<'a> { .get(&mask) .ok_or("a wave reduction's untracked mask")?; let on = self.boolean(m, c)?; + let on = self.launched(c, on, mask); let x = self.i32_of(src)?; let id = self.s.m.i32(ident); return Ok(self.s.m.select(c, on, x, id)); @@ -2083,6 +2104,7 @@ impl<'a> Lower<'a> { .get(&mask) .ok_or("a wave reduction's untracked mask")?; let on = self.boolean(m, c)?; + let on = self.launched(c, on, mask); let x = self.i32_of(src)?; let id = self.s.m.i32(ident); let x = self.s.m.select(c, on, x, id); @@ -2229,6 +2251,7 @@ impl<'a> Lower<'a> { .get(&mask) .ok_or("a wave reduction's untracked mask")?; let on = self.boolean(m, c)?; + let on = self.launched(c, on, mask); let lo = self.i32_of(lo)?; let hi = self.i32_of(hi)?; let z = self.s.m.i32(0); @@ -2410,10 +2433,16 @@ impl<'a> Lower<'a> { let all = self.s.m.cmp(original, pred::EQ, limit, zero); let inside = self.s.m.cmp(original, pred::IULT, x, limit); let runs = self.s.m.bin(original, Bin::Or, all, inside); - let (body, done) = (self.s.m.new_block(), self.s.m.new_block()); - self.s.m.terminate(original, Term::CondBr(runs, body, done)); - self.s.m.terminate(done, Term::Ret); - self.s.entry = body; + if self.halves.is_some() || self.exchange.is_some() { + // A console wave in two host waves exchanges through group + // barriers, which every thread must reach: the threads stay. + self.partial_active = Some(runs); + } else { + let (body, done) = (self.s.m.new_block(), self.s.m.new_block()); + self.s.m.terminate(original, Term::CondBr(runs, body, done)); + self.s.m.terminate(done, Term::Ret); + self.s.entry = body; + } } self.find_coherent(); let order = crate::ir::reverse_postorder(&p.blocks); @@ -3356,7 +3385,7 @@ impl<'a> Lower<'a> { }; let (lo, hi) = (word(self, 0)?, word(self, 1)?); let (lo, hi) = self.address_plus(lo, hi, i32::from(*offset)); - let guard = self.guard(b, i)?; + let guard = self.memory_guard(b, i)?; let (i32t, res, void) = (self.s.t.i32, self.s.t.res_ret, self.s.t.void); let iu = self.s.m.undef(i32t); let align = self.s.m.i32(4); @@ -3611,6 +3640,7 @@ impl<'a> Lower<'a> { let bit = self.boolean(m, at); self.balloting.remove(&lo); let bit = bit?; + let bit = self.launched(at, bit, lo); let i32t = self.s.t.i32; let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); let r = self @@ -4334,7 +4364,11 @@ impl<'a> Lower<'a> { Some(b) if b == self.cur_ir => self.cur, Some(b) => self.tail[b].ok_or("a lane mask written after its use")?, }; - let bit = self.boolean(m, at)?; + let mut bit = self.boolean(m, at)?; + if let Some(a) = self.partial_active { + // (a mask ANDed with EXEC: the threads kept for barriers have no bit) + bit = self.s.m.bin(at, Bin::And, bit, a); + } let (i1t, i32t) = (self.s.t.i1, self.s.t.i32); let some = self.s.op(at, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[bit]); self.s.flags |= flags::WAVE_OPS; @@ -4378,12 +4412,16 @@ impl<'a> Lower<'a> { // what the halves exchange is "some lane speaks against" either way (for `any`: // some lane's `when` holds; else: some lane's does not), so a half with no lane says // nothing - let set = if any { + let mut set = if any { mine } else { let t = self.s.m.bool(true); self.s.m.bin(c, Bin::Xor, mine, t) }; + if let Some(a) = self.partial_active { + // (a thread the console did not launch says nothing) + set = self.s.m.bin(c, Bin::And, set, a); + } let (i1t, i32t) = (self.s.t.i1, self.s.t.i32); let some = self.s.op(c, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[set]); self.s.flags |= flags::WAVE_OPS; @@ -4459,6 +4497,25 @@ impl<'a> Lower<'a> { inst.write(pick(reg)?) } + /// [`Self::guard`] of a memory access: not by the threads a partial final group only + /// keeps for its barriers ([`Self::partial_active`]). + fn memory_guard(&mut self, b: usize, i: usize) -> Result<Option<V>, Why> { + let g = self.guard(b, i)?; + Ok(match (g, self.partial_active) { + (Some(g), Some(a)) => Some(self.s.m.bin(self.cur, Bin::And, g, a)), + (g, a) => g.or(a), + }) + } + + /// `on` (the lanes of a mask, at `at`) without the threads a partial final group keeps + /// for its barriers, when the mask is of EXEC's lanes (`Structured::active`). + fn launched(&mut self, at: usize, on: V, mask: Value) -> V { + match self.partial_active { + Some(a) if self.x.st.active.contains(&mask) => self.s.m.bin(at, Bin::And, on, a), + _ => on, + } + } + fn guard(&mut self, b: usize, i: usize) -> Result<Option<V>, Why> { match self.x.st.guards[b][i] { None => Ok(None), @@ -5001,7 +5058,12 @@ impl<'a> Lower<'a> { return Err("GDS"); } let name = inst.name(); - let guard = self.guard(b, i)?; + // (a lane read leaves no access behind: the threads kept for barriers take part) + let guard = if name == "ds_swizzle_b32" || name.contains("permute") { + self.guard(b, i)? + } else { + self.memory_guard(b, i)? + }; let c = self.cur; let offset = u32::from(*offset0) | u32::from(*offset1) << 8; let dst_reg = match dst { @@ -8798,7 +8860,14 @@ impl<'a> Lower<'a> { }; const UNTRACKED: Why = "a select on an untracked mask"; let cond = match mask.and_then(|m| self.x.st.masks.get(&m).copied()) { - Some(m) => self.boolean(m, c)?, + Some(m) => { + let on = self.boolean(m, c)?; + // (a select by EXEC's lanes: a thread kept for barriers has no bit) + match mask { + Some(lo) => self.launched(c, on, lo), + None => on, + } + } // A mask the code holds as a number (a constant bit // pattern: every other lane, every other pair...): // this lane's bit of it. Exact where host lanes are @@ -10956,7 +11025,7 @@ impl<'a> Lower<'a> { // A load or sample with no channel enabled returns the first. let dmask = if *dmask == 0 { &1 } else { dmask }; let site = (b, i); - let guard = self.guard(b, i)?; + let guard = self.memory_guard(b, i)?; let c = self.cur; let (kind, coords) = match dim { 0 => (1, 1), @@ -11815,7 +11884,7 @@ impl<'a> Lower<'a> { return Err(name); } let site = (b, i); - let guard = self.guard(b, i)?; + let guard = self.memory_guard(b, i)?; let c = self.cur; let store = name.starts_with("buffer_store_"); // DXIL atomic operations: add, and, or, xor, signed and unsigned ``` </details> About 1.3% of roots are still broken. They are the same structures in every run, so we're still investigating. The cell's bounce light is still about 0.5–0.7× the console's in its darkest corners, and that's what we're chasing next. --- Co-authored with Claude (Anthropic).
gtport646 commented 2026-11-29 13:45:26 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Marvisak/VIctory. Originally posted by gtport646 on 2026-11-29T13:45:26Z.


Another cause of dark indirect light, and it may affect every tree that inherited the pixel-loop cap.

Our translator cut translated loops at 128 iterations in pixel shaders (256 vertex/mesh, 4,096 compute), as a GPU-hang safety net. PS_IntegrateEnvBRDF (a467d848… here) runs three sample loops of 1,024. Every pixel hit the cut and was discarded, so the environment-BRDF lookup table was never written. It runs once at load and kept whatever memory it started with. Everything that reads it got garbage, which shows up as ambient and indirect light at about 0.5–0.7×, mostly in shadowed areas. Directly lit surfaces look right. Because the table held uninitialised memory, the result can also vary from launch to launch.

Credit to fixafail (44010e8ae8), who measured title loops above these caps.

Measured on our side (RTX 4090, Series S, builder on, cell-only, against the console capture):

before (pixel cap 128) after (cap 4,096)
paper under the bunk (ratio to console, R/G/B) .66 / .45 / .38 .94–.95 / .75–.76 / .65–.66
left wall .64 / .66 / .66 .81–.82 / .75 / .76–.77
darkest third of the frame (console / ours) 1.93 1.38–1.49
  • Raising the cap only for PS_IntegrateEnvBRDF reproduces the whole change, so it is that one program.
  • Runs: 8 launches at 4,096 in every stage, with no device loss and no fps change.
  • We kept compute at 4,096: fixafail's 65,536 for compute made our frames take 2–5 s from the load on.
  • The diner gain is smaller, and its shadows are still somewhat darker than the console, so this isn't the only remaining gap.

Quick check for your tree: if your pixel-loop cap is below 1,024, try PS_IntegrateEnvBRDF (or every pixel loop) at 4,096 and compare shadowed areas against the console.

The change on our side is one line in the loop-limit lowering: the per-stage defaults become a single 4,096.


Co-authored with Claude (Anthropic).

<!-- greyfinch-sync:Marvisak/VIctory:comment:7256777732 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/issues/3750#issuecomment-7256777732). Originally posted by [gtport646](https://github.com/gtport646) on 2026-11-29T13:45:26Z. --- **Another cause of dark indirect light, and it may affect every tree that inherited the pixel-loop cap.** Our translator cut translated loops at **128 iterations in pixel shaders** (256 vertex/mesh, 4,096 compute), as a GPU-hang safety net. `PS_IntegrateEnvBRDF` (`a467d848…` here) runs **three sample loops of 1,024**. Every pixel hit the cut and was discarded, so the **environment-BRDF lookup table was never written**. It runs once at load and kept whatever memory it started with. Everything that reads it got garbage, which shows up as ambient and indirect light at about 0.5–0.7×, mostly in shadowed areas. Directly lit surfaces look right. Because the table held uninitialised memory, the result can also vary from launch to launch. Credit to **fixafail** (`44010e8ae8`), who measured title loops above these caps. **Measured on our side** (RTX 4090, Series S, builder on, cell-only, against the console capture): | | before (pixel cap 128) | after (cap 4,096) | |---|---|---| | paper under the bunk (ratio to console, R/G/B) | .66 / .45 / .38 | .94–.95 / .75–.76 / .65–.66 | | left wall | .64 / .66 / .66 | .81–.82 / .75 / .76–.77 | | darkest third of the frame (console / ours) | 1.93 | 1.38–1.49 | - Raising the cap **only for `PS_IntegrateEnvBRDF`** reproduces the whole change, so it is that one program. - Runs: 8 launches at 4,096 in every stage, with no device loss and no fps change. - We kept compute at 4,096: fixafail's 65,536 for compute made our frames take 2–5 s from the load on. - The diner gain is smaller, and its shadows are still somewhat darker than the console, so this isn't the only remaining gap. **Quick check for your tree:** if your pixel-loop cap is below 1,024, try `PS_IntegrateEnvBRDF` (or every pixel loop) at 4,096 and compare shadowed areas against the console. The change on our side is one line in the loop-limit lowering: the per-stage defaults become a single 4,096. --- Co-authored with Claude (Anthropic).
Sign in to join this conversation.
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
Marvisak/VIctory#3750
No description provided.