Skip to content

Shaders: implicit-level samples in compute take their gradients from the quad - #1237

Open
felicienradio wants to merge 1 commit into
Marvisak:mainfrom
felicienradio:shader/compute-quad-gradients
Open

felicienradio wants to merge 1 commit into
Marvisak:mainfrom
felicienradio:shader/compute-quad-gradients

Conversation

@felicienradio

Copy link
Copy Markdown

Console compute programs may sample with an implicit level of detail (image_sample, image_sample_b): the hardware takes the coordinates' coarse derivatives across each quad of lanes. Emitted as DXIL sample / sampleBias, these programs fail validation:

Function: main: error: Entry function performs some operation that is incompatible with the shader stage or other entry properties.
Function: main: error: Function uses features incompatible with the shader stage (cs) of the entry function.

In compute shaders the gradients are now read from the quad (lane 1 − lane 0 for x, lane 2 − lane 0 for y, through waveReadLaneAt), as the hardware's coarse derivatives, and passed to sampleGrad. A bias scales them by 2^bias. Pixel and mesh shaders are unchanged; cube samples keep the old path.

Affected programs include CS_SkyMain, scattering_transmittance_system (fog/in-scattering), the ray-traced shadow denoisers, the irradiance cache / light probes, and the CS_RaytracingResolve family.

Results

victory translate --validate over the title's shaders on Windows (dxil.dll 10.0.26100), on top of #439:

  | before | after -- | -- | -- compute programs validated | 1,658 of 2,193 emitted | 2,193 of 2,193 vertex/pixel, mesh | unchanged | unchanged

Tests

  • cargo test -p victory-shader --features host: all pass.
  • Not yet compared pixel-for-pixel against the native path on a GPU; inactive lanes in a quad read whatever the host has there, as native compute derivatives would.

Independent of the "descriptor read only as data" PR, which unlocks ~490 more CS_RaytracingResolve programs that this change then lets validate.

…the quad

A console compute program may sample with an implicit level of detail
(image_sample, image_sample_b): the hardware takes the coordinates'
coarse derivatives across each quad of lanes. As DXIL `sample` and
`sampleBias`, these programs failed validation with "Function uses
features incompatible with the shader stage (cs) of the entry function".
The gradients are now read from the quad (lane 1 less lane 0, lane 2
less lane 0, through waveReadLaneAt) and passed to `sampleGrad`; a bias
scales them by 2^bias. Pixel and mesh shaders are unchanged.

`victory translate --validate` over the title's shaders on Windows
(dxil.dll 10.0.26100), on top of Marvisak#439: compute programs validated go
from 1,658 to 2,193 of 2,193 emitted; no other count changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SDn5GupcrERtCYPyoztdtG
@Zipettte

Copy link
Copy Markdown

Tested on AMD Radeon RX 7700 XT (RDNA3, gfx1101), driver 32.0.32029.2010, Windows 11, Rust 1.98.1 MSVC at a3346f9: cargo test -p victory-shader passes, 120 passed / 0 failed. Workspace baseline on main (ffe310e) is green on the same machine (342 passed).

Tested with AI assistance (Claude).

@upipibi

upipibi commented Nov 24, 2026

Copy link
Copy Markdown

Context for choosing between this PR and #160, which both change how implicit-level samples are emitted in compute:

  • Impact. A fork that runs main into the world counts 730 compute programs refused by the validator for exactly this ("features incompatible with the shader stage", among them the G-buffer resolves and the sky): fxceless/victory-gta6, at its sampleLevel fallback in lower.rs. It works around it by sampling level 0 outside pixel shaders, and its comment says gradients from the lanes are the real fix: what this PR does.
  • Shaders: texel offsets, comparison and gather forms of image samples #160 goes the other way. It keeps the implicit-derivative sample in compute. Its own test lets the validator 1.6 error through (CS_DERIVATIVES, "1.8 takes them") and relies on the driver's compute derivatives. This PR's gradients from quad lanes 1−0 and 2−0 validate at 1.6 instead. The two touch the same sample / sampleBias emission, so only one approach can be kept.
  • A test. This PR adds none. Shaders: texel offsets, comparison and gather forms of image samples #160's quad_lane pattern (quad q's lanes 2^n texels apart in x and y, so the quad's derivatives pick level n, on a texture whose texels name their level) would check this PR's gradients on the GPU as well.

Reading only, nothing run. AI-assisted (Claude Code).

@wildheathen

wildheathen commented Nov 24, 2026 •

Copy link
Copy Markdown

#1237 and #1065 compared on the new main 70564ae: the same 735 compute programs, plus pipeline creation on an RTX 5080. I'm not the author of either.

Both PRs fix "Function uses features incompatible with the shader stage (cs)", which comes from implicit-LOD sample/sampleBias in compute. #1065 keeps the implicit sample and declares validator 1.8 for those programs. #1237 computes coarse gradients from quad lanes 1−0 and 2−0 and calls sampleGrad, staying at 1.6.

Merging onto 70564ae

Offline (translate --validate --list over shaders.rpf, dxil.dll 10.0.26100, compared program by program)

validated compute validated "incompatible with the shader stage"
70564ae 24,797 1,886 of 2,621 735
+ #1065 25,532 (+735, 0 lost) 2,621 0
+ #1237 25,532 (+735, 0 lost) 2,621 0

#1065 and #1237 gain exactly the same 735 programs. Per program there's no difference between them on this dump.

Pipeline creation on an RTX 5080 (--pipelines, driver 32.0.16.2124, 32-lane waves)

compute pipelines created
70564ae 2,227
+ #1065 2,227
+ #1237 2,227 (the same 723 of the 735)

A GPU test of the level they pick, which both PRs lack

@upipibi asked on #1237 for a test of whether the gradients pick the right mip. Here's one, written on upstream's synthetic_tests harness (View::Mipped):

  • a compute image_sample (implicit level, red channel) on a 32×32 texture with 4 levels, where every texel of level n holds (n+1)·1000;
  • quad q's lanes are 2^n level-0 texels apart (lanes 0/1 in x, 0/2 in y), with n = q mod 3, so the right answer is level n.
WARP RTX 5080
70564ae refused by the validator (the bug) –
+ #1065 all 32 lanes right all 32 lanes right (with the raw-view harness fix, see below)
+ #1237 all 32 lanes right, identical to #1065 all 32 lanes right, identical
The test (append to emit/synthetic_tests.rs)
/// Per lane (32 lanes, wave32): u, v from the record at entry 1; an implicit
/// level sample (`image_sample`, red) of the texture at entry 0, stored at
/// lane × 4. The level comes from the derivatives across each quad.
fn implicit_sample_program() -> Vec<u32> {
    vec![
        0xBE84_0300, // s_mov_b32 s4, s0
        0xBE85_0380, // s_mov_b32 s5, 0
        0xF40C_0302,
        0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0
        0xF408_0502,
        0xFA00_0020, // s_load_dwordx4 s[20:23], s[4:5], 0x20
        0xF408_0A02,
        0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40
        // The sampler of `program`: levels 0-12, linear filters.
        0xB008_01B6, // s_movk_i32 s8, 0x1b6
        0xBE89_03FF,
        0x00C0_0000, // s_mov_b32 s9, 0xc00000
        0xBE8A_03FF,
        0x1850_0000, // s_mov_b32 s10, 0x18500000
        0xBE8B_0380, // s_mov_b32 s11, 0
        0x3420_0084, // v_lshlrev_b32 v16, 4, v0
        0x3428_0082, // v_lshlrev_b32 v20, 2, v0
        0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
        0xE038_1000,
        0x8005_0C10, // buffer_load_dwordx4 v[12:15], v16, s[20:23], 0 offen
        0xBF8C_3F70, // s_waitcnt vmcnt(0)
        0xF080_0108,
        0x0043_040C, // image_sample v4, v[12:13], s[12:19], s[8:11] dmask:0x1 dim:2D
        0xBF8C_3F70, // s_waitcnt vmcnt(0)
        0xE070_1000,
        0x800A_0414, // buffer_store_dword v4, v20, s[40:43], 0 offen
        0xBF81_0000, // s_endpgm
    ]
}

#[test]
fn implicit_level_samples_in_compute_take_the_level_of_their_quad() {
    // 32×32 and three smaller levels; every texel of level n holds (n + 1) × 1000.
    const W: usize = 32;
    let mut texels = Vec::new();
    for l in 0..4usize {
        let s = W >> l;
        texels.extend(std::iter::repeat_n([((l + 1) * 1000) as f32, 0.0, 0.0, 1.0], s * s));
    }
    // Quad q (lanes 4q..4q+3: 0 and 1 apart in x, 0 and 2 apart in y) puts
    // its lanes 2^n level-0 texels apart, n = q mod 3: its derivatives pick
    // level n.
    let mut records: Vec<[u32; 4]> = Vec::new();
    let mut want = Vec::new();
    for lane in 0..32usize {
        let (q, i) = (lane / 4, lane % 4);
        let n = q % 3;
        let s = 1usize << n;
        let (x0, y0) = (4 + (q % 4) * 6, 4 + (q / 4) * 12);
        let (x, y) = (x0 + (i & 1) * s, y0 + (i >> 1) * s);
        let (u, v) = (
            (x as f32 + 0.5) / W as f32,
            (y as f32 + 0.5) / W as f32,
        );
        records.push([u.to_bits(), v.to_bits(), 0, 0]);
        want.push(((n + 1) * 1000) as f32);
    }
    let input: Vec<u32> = records.iter().flatten().copied().collect();
    let shader = build(&implicit_sample_program()).expect("lower");
    if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
        v.validate(&mut shader.dxil.clone())
            .expect("DXIL validation failed");
    }
    let views = [
        View::Mipped(W as u32, W as u32, 4, &texels),
        View::Buffer {
            data: &input,
            stride: Stride::Structured(16),
        },
        View::RawUav(32),
    ];
    let _one = super::valu_tests::ONE_AT_A_TIME
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    let mut ran = 0;
    for (label, warp) in [("hardware", false), ("warp", true)] {
        let Ok(host) = Host::new(warp) else {
            eprintln!("no SM 6.6 {label} device; skipped");
            continue;
        };
        let (root, pso) = host.compute_pipeline(&shader).expect("pipeline");
        let ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
        let out = host
            .dispatch(
                &root,
                &pso,
                &Dispatch {
                    roots: vec![(0, Root::Constants(ud))],
                    views: &views,
                    samplers: &[],
                    groups: [1, 1, 1],
                },
            )
            .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}"));
        ran += 1;
        let got: Vec<f32> = out[0][..32].iter().map(|&b| f32::from_bits(b)).collect();
        assert_eq!(got, want, "{label}: the level each quad's derivatives pick");
    }
    assert!(ran > 0, "no device");
}

What's left to choose on

No game data, shader bytes or shader names here; counts only.

AI-assisted (Claude Code).

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

Needs rebase. This pull request conflicts with main (conflicting: crates/victory-shader/src/emit/lower.rs). It will be reviewed once it is rebased onto the current main.


Generated by Claude Code

@ElSeba0811

Copy link
Copy Markdown

I've got another case worth checking on the GTX 1070 Ti: a Y-only texture footprint in a 2D thread group. Our 1D tests passed, but this one picked the wrong mip.

We tested the earlier quad-gradient code from #180 (aa692580ed69e4fa20b8312df55027108fe8d7c7) in our local ffe310e checkout. This PR's a3346f9 patch uses the same lane-0/1/2 gradient construction, but I haven't run this exact head. I'm sharing a regression case to check, not claiming your branch failed.

The synthetic test builds coordinates from guest x/y/z thread IDs, samples four constant-color mip levels and checks every lane. We used [64,1,1], [8,8,1] and [8,4,2] groups, with wave32 and wave64.

On the old mapping, [8,8,1], wave32, Y-only got 32 of 64 lanes wrong: all 64 read mip 0, while the upper 32 should have read mip 1.

Our local fix emits a 1D host group with the same total threads, then reconstructs guest x/y/z from the flat ID. Dispatch group counts and guest logical dimensions stay the same. The 1D, 2D, 3D and Y-only cases then passed exact checks on both GTX and WARP. Positive/negative bias, sampler LOD bounds, texel offsets and whole-quad EXEC masks passed too. Arbitrarily partially active quads are still outside that coverage.

This is separate from the structured/raw SRV test issue discussed above: our coordinates come from thread IDs, not an input buffer. The local tests are compute_quad_gradients_select_distinct_mips_on_hardware_and_warp and compute_quad_gradients_preserve_bias_bounds_offsets_and_whole_quad_exec.

The 1D mapping still needs integration review. No world-rendering or FPS claim here, just a case that may catch something the 1D or symmetric tests miss.

AI-assisted with Codex. Synthetic-test details only; no game data attached.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants