Skip to content

Shaders: coalesce aligned constant-buffer loads - #511

Open
aycow wants to merge 5 commits into
Marvisak:mainfrom
aycow:shaders/coalesce-aligned-cbv-loads
Open

aycow wants to merge 5 commits into
Marvisak:mainfrom
aycow:shaders/coalesce-aligned-cbv-loads

Conversation

@aycow

@aycow aycow commented Nov 24, 2026 •

Copy link
Copy Markdown

Change

When the per-lane MUBUF CBV path proves a vector read stays within one 16-byte DXIL row, issue one cbufferLoadLegacy.i32 and extract the required dwords. Unaligned offsets, row crossings, variable byte offsets and unproven built bases keep the existing lowering.

Current upstream integration

Head 02dc7b2 merges cleanly with upstream 42363ab. Coalescing applies to the native root CBV lowering. Main routes table CBVs through raw SRVs, and this PR preserves the table lowering. A built root view falls back to scalar loads when an index can shift the address within a 16-byte row, as with a stride of four bytes.

The regression runs 176 synthetic dispatches per adapter across raw tables and native root views, including strides of 4, 16, and 32 bytes. AMD Radeon Graphics, GeForce RTX 5070 Laptop GPU, and WARP passed with the D3D12 debug layer and full GPU-based validation. The explicit-adapter run used Agility SDK 1.620.2 and a local startup sampler-heap workaround outside the PR. The unmodified PR head also passed the normal matrix and strict shader Clippy.

The current DXIL dump shows one native row load for the aligned four-dword case and four for the stride-four or dynamic-offset cases. A two-dword row crossing still uses two loads. Current-head GPU timing and title performance have yet to be measured.

Synthetic reproduction and validation

On Windows with Shader Model 6.6, run cargo test -p victory-shader indexed_cbv_loads_match_their_byte_addresses -- --nocapture. The synthetic GFX10 fixture compares dword, dwordx2, dwordx3 and dwordx4 loads against the CPU reference at every aligned immediate byte offset from 0 to 28, plus dynamic byte offsets 0, 4, 12 and 16 for each width. The regular test runs on the available default hardware adapter and WARP. An explicit-adapter Agility SDK 1.620.2 run of the expanded matrix at 0b3c1fd passed all 48 cases per adapter on AMD Radeon Graphics, NVIDIA RTX 5070 Laptop GPU and WARP with the debug layer and full GPU-based validation. A mutation using the row’s first dword instead of the requested in-row dword failed at byte offset 4, group 0, lane 0. fromthemoonx identified the gap, provided the mutation, and independently validated the preceding lowering on desktop RTX 3060 and WARP. Independent review · Expanded regression

A separate earlier explicit-adapter harness compared baseline and candidate on six offset cases. The aligned module’s input-row loads fell from four to one and channel selects from 12 to zero. Dynamic and row-crossing modules were byte-identical.

Earlier synthetic GPU timing

One dispatch of 4,096 groups × 32 threads wrote a 2 MiB UAV. Both PSOs were created outside the timing brackets. Four warm-up pairs were discarded and 32 measured pairs alternated variants with debug and GPU-based validation off.

Backend Baseline median Candidate median Baseline max Candidate max
AMD Radeon Graphics 32.520 µs 30.980 µs 50.280 µs 59.840 µs
NVIDIA RTX 5070 Laptop 24.640 µs 14.560 µs 25.632 µs 15.360 µs
WARP 369.550 µs 248.650 µs 542.000 µs 327.000 µs

NVIDIA improved in all 32 pairs. AMD variation was larger than the median difference. The figures apply to this workload. Title shader frequency and frame impact remain unmeasured.

This PR contains only the shader lowering and its regression. AI-assisted with OpenAI Codex.

Current main validation

Rebased onto ffe310e after #566. The per-lane constant-buffer lowering and the expanded 48-case matrix are intact. Seven focused tests passed, including the expanded CBV matrix, the upstream FP16 class case, and all five waterfall tests. A test-only adapter-selection run verified all CBV cases on AMD Radeon Graphics, RTX 5070 Laptop GPU, and WARP with Agility 1.620 and full GPU-based validation.

@fromthemoonx

Copy link
Copy Markdown

Tested 7beab43 (on main d2a4bae) on desktop NVIDIA, with DXIL validation on (Windows SDK 10.0.26100 dxil.dll, found by default).

Environment: Windows 11 Pro build 26300, AMD Ryzen 7 5700X, 16 GB, NVIDIA GeForce RTX 3060 12 GB (driver 610.88), Rust 1.98.1 x86_64-pc-windows-msvc, debug.

Tested

  • indexed_cbv_loads_match_their_byte_addresses: passes on the hardware adapter and WARP, 20 of 20 repeated runs
  • cargo test --locked -p victory-shader: 70 passed, 0 failed
  • cargo test --locked --workspace: 265 passed, 0 failed, 4 ignored
  • cargo clippy -p victory-shader --all-targets: no warnings; cargo fmt --check, git diff --check: clean; cargo xtask policy: 151 files ok

A gap in the regression test. It only uses buffer_load_dwordx4, which can coalesce only at first == 0, so the in-row dword index is never exercised: with extract(c, row, first + k) changed to extract(c, row, k), the test still passes.

I added a local variant (below, not pushed). It reuses build_indexed_cbv_cs with buffer_load_dword/dwordx2/dwordx3/dwordx4 at every immediate offset 0–28 and checks each lane's count dwords on both backends:

  • this PR: all 64 (op, offset, backend) cases match the CPU reference, coalesced (first 1–3) and row-crossing fallbacks alike
  • with the mutation above: fails at the first case with first != 0

So the lowering is right; the test just doesn't pin that part down yet. Adding a narrower load at a non-zero in-row offset (e.g. dwordx2 at offset 8) to the test would cover it.

Local variant (throwaway: patches the load opcode through a static)
-        0xE038_2000 | (u32::from(dynamic) << 12) | u32::from(byte_offset),
+        0xE000_2000 | (LOCAL_OP.load(std::sync::atomic::Ordering::Relaxed) << 18) | (u32::from(dynamic) << 12) | u32::from(byte_offset),
static LOCAL_OP: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(14);

#[test]
fn local_probe_partial_rows() {
    let input: Vec<u32> = (0u32..192)
        .map(|i| (i + 1).wrapping_mul(0x91de_2f71).rotate_left(i % 32))
        .collect();
    // (op, count): dword 12, dwordx2 13, dwordx4 14, dwordx3 15
    for (op, count) in [(12u32, 1usize), (13, 2), (15, 3), (14, 4)] {
        for offset in (0u16..=28).step_by(4) {
            LOCAL_OP.store(op, std::sync::atomic::Ordering::Relaxed);
            let shader = build_indexed_cbv_cs(offset, false);
            for (label, warp) in [("hardware", false), ("warp", true)] {
                let Ok(host) = Host::new(warp) else { continue };
                let (root, pso) = host.compute_pipeline(&shader).expect("pipeline");
                let mut ud = vec![0u32; shader.user_data_dwords() as usize];
                for u in &shader.user_data {
                    ud[u.index as usize] = match (u.root, u.slot) {
                        (RootType::Table, 1) => 32,
                        _ => 0,
                    };
                }
                let actual = host
                    .dispatch(&root, &pso, &Dispatch {
                        roots: vec![(0, Root::Constants(ud))],
                        views: &[View::Cbv(&input), View::RawUav(256)],
                        samplers: &[],
                        groups: [2, 1, 1],
                    })
                    .expect("dispatch");
                let dword = usize::from(offset) / 4;
                for (g, group) in actual[0].as_chunks::<128>().0.iter().enumerate() {
                    for lane in 0..32 {
                        let got = &group[lane * 4..lane * 4 + count];
                        let want = &input[lane * 4 + dword..lane * 4 + dword + count];
                        assert_eq!(got, want, "{label} op {op} offset {offset} group {g} lane {lane}");
                    }
                }
            }
        }
    }
}

Not tested: the timing (the harness isn't in the PR); no game data used.

AI-assisted (Claude Code) ran the checks and drafted this comment.

aycow added a commit to aycow/VIctory that referenced this pull request Nov 24, 2026
Expand the GPU readback regression to the immediate offsets in two rows, plus dynamic offsets for each width. Credit the regression matrix and mutation suggested by fromthemoonx in PR Marvisak#511.

Co-authored-by: fromthemoonx <114431313+fromthemoonx@users.noreply.github.com>
@aycow

aycow commented Nov 24, 2026

Copy link
Copy Markdown
Author

@fromthemoonx Thanks for spotting the coverage gap and proposing the expanded matrix. I credited the contribution in 0b3c1fd, now on this PR. The test checks dword, dwordx2, dwordx3 and dwordx4 at every aligned byte offset from 0 to 28, plus dynamic offsets for each width.

The final regression passed 48 cases per adapter on AMD, NVIDIA and WARP with full GPU-based validation. With your mutation changing first + k to k, it failed at the first nonzero in-row case: one dword at byte offset 4, group 0, lane 0. The lowering and the previously reported synthetic timing numbers are unchanged.

@catminou4 catminou4 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.

Test-merge with current main (ffe310e) conflicts — needs a rebase. Main moved recently (PR #566 waterfall loops touched lower.rs/resource.rs/valu_tests.rs), so shader PRs opened before it need rebasing. I'll re-review once it merges cleanly.

aycow and others added 2 commits November 24, 2026 11:15
Expand the GPU readback regression to the immediate offsets in two rows, plus dynamic offsets for each width. Credit the regression matrix and mutation suggested by fromthemoonx in PR Marvisak#511.

Co-authored-by: fromthemoonx <114431313+fromthemoonx@users.noreply.github.com>
@aycow
aycow force-pushed the shaders/coalesce-aligned-cbv-loads branch from 0b3c1fd to ff96ffe Compare November 24, 2026 16:25
@aycow

aycow commented Nov 24, 2026

Copy link
Copy Markdown
Author

@catminou4 The #566 conflict is resolved in ff96ffe, based on ffe310e. GitHub reports the branch merges cleanly. The expanded 48-case matrix passed on AMD Radeon Graphics, RTX 5070 Laptop GPU, and WARP with full GPU-based validation using a test-only adapter selector. The five upstream waterfall fixtures and the preserved FP16 class test passed as well.

@aycow

aycow commented Nov 24, 2026 •

Copy link
Copy Markdown
Author

@catminou4 Update to the re-review request: main advanced after the clean ffe310e check. GitHub now shows a conflict with 70564ae. I resolved the test-file conflict locally, and full GPU-based validation exposed a material change in 683ad7a: table constant buffers now bind as raw SRVs, while #511's historical regression binds CBVs. The 48-case AMD/NVIDIA/WARP results apply to ff96ffe on ffe310e. I'm checking the remaining native-CBV path before asking for review against the new main.

AI-assisted using Codex.

@aycow

aycow commented Nov 24, 2026

Copy link
Copy Markdown
Author

The current-main table-constant binding has now been tested separately. On 70564ae it is a raw SRV path. A local same-row vector experiment passed 240 cases each on AMD and WARP with full validation. The old CBV regression remains useful historical evidence. A mechanical port also needs a new alignment proof for indexed built root descriptors: current lowering folds the descriptor stride into the address before the old row proof. I'm coordinating the raw case with #1393 and recommend superseding this PR's table-CBV approach once that direction is agreed.

AI-assisted using Codex.

Marvisak commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

Merge candidate. The new head d320fab only merges current main into the branch (conflict resolved in valu_tests.rs); the PR's own change is the same as at the last triage, and it merges cleanly with main.

I re-read the native CBV path of the MUBUF lowering in crates/victory-shader/src/emit/lower.rs against the merged code: coalescing into one cbufferLoadLegacy row still requires an immediate-only offset (no offen, no scalar offset, no built base or extra term), a row-aligned index (built root view stride a multiple of 16) and first + count <= 4, so the extracted dwords match what cbuffer_dword would read. The raw-SRV table path is untouched. indexed_cbv_loads_match_their_byte_addresses in valu_tests.rs still covers every width and aligned offset, tables and strides 4/16/32.

CI: passing (check). Recommending a look, not approving.


Generated by Claude Code

@aycow

aycow commented Nov 25, 2026

Copy link
Copy Markdown
Author

@catminou4 The branch now merges cleanly with main at 02dc7b2. The change keeps native CBV coalescing and adds a stride guard for indexed root views. The 176-dispatch matrix passed on AMD, NVIDIA, and WARP with full GPU-based validation. I updated the description with the scope and the validation setup.

# Conflicts:
#	crates/victory-shader/src/emit/valu_tests.rs
@fuzeofficlal

Copy link
Copy Markdown
Contributor

Code review and RTX 5090 + WARP + DXIL verification at head d320fabee173 merged cleanly onto main (63bcca43c6a0; emit/lower.rs = 521,706 B, 2,582 B under the 512 KiB cap):

  • Code review (crates/victory-shader/src/emit/lower.rs:4881-4890, 9527-9540):
    • Coalesces non-table root CBV loads into a single cbufferLoadLegacy.i32(h, byte >> 4) only when immediate (!*offen && !scalar_offset && base == 0 && extra.is_none()), row_aligned_index (stride.is_multiple_of(16) for Source::Built), offset.is_multiple_of(4), and first + count <= 4 (guaranteeing no 16-byte row crossing even under 32-bit address wrap). Table CBVs keep their rawBufferLoad path untouched.
  • Verified (Windows 11, NVIDIA RTX 5090 + WARP, dxil.dll 10.0.26100.0, VICTORY_D3D12_DEBUG=1, Rust 1.98.1):
    • cargo xtask policy: 191 files ok; cargo clippy -p victory-shader --all-targets -- -D warnings (default + --features diagnostics): 0 warnings
    • emit::lower::tests (33/33), indexed_cbv_loads_match_their_byte_addresses (RTX 5090 + WARP), and emit::semantics_tests (34/34 on both RTX 5090 and WARP, 1 ignored) all passed.

LGTM.

@Dukestar69 Dukestar69 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.

LGTM — verified on Windows (RTX 5090 + WARP):

  • Coalescing into a single cbufferLoadLegacy.i32 when !offen && !scalar_offset && base == 0 && extra.is_none() && row_aligned_index && offset % 4 == 0 && first + count <= 4 is sound and cleanly avoids redundant row loads
  • cargo test -p victory-shader --lib indexed_cbv_loads_match_their_byte_addresses passed on RTX 5090 and under VICTORY_WARP=1
  • cargo clippy -p victory-shader --all-targets -- -D warnings passed with 0 warnings
  • cargo xtask policy passed (191 files ok)

Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).

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.

6 participants