Skip to content

GPU: skip unmapped regions after a failed bulk read into host memory - #202

Open
ifBars wants to merge 1 commit into
Marvisak:mainfrom
ifBars:gpu/sparse-host-reads
Open

ifBars wants to merge 1 commit into
Marvisak:mainfrom
ifBars:gpu/sparse-host-reads

Conversation

@ifBars

@ifBars ifBars commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

During first-story rendering on Windows 10, about 650 bulk reads per frame fell back to 64 KiB and 4 KiB retries in one sample. Those reads encountered roughly 136 MB of unmapped memory. This patch keeps the successful bulk read unchanged. After a failed read of at least 64 KiB into host memory, it uses VirtualQuery to skip contiguous holes and reads committed regions through the kernel. If the mapping changes before the read completes, the existing page retries recover the readable bytes. It queries again on every copy.

Validation

  • On an i5-11600K, copying a 32 MiB range with 32 committed 64 KiB islands took 27.36 ms with the existing page retries and 1.23 ms with region queries. The buffers matched byte for byte across ten alternating trials.
  • The new regression test checks separated committed pages, unaligned edges, a newly committed page, a page changed to NOACCESS, and untouched bytes around the destination. On d2a4bae, the GPU crate passed 44 tests with one ignored. The asset policy check passed.
  • The downstream renderer also tested under story load on a 3060 Ti. For the first six complete world samples, reported median CPU copy time was 322 ms before the later changes and 160 ms after. The downstream build also changed descriptors and shader translation, so the in-game comparison cannot isolate this patch. The run reached its 60-second world limit at 0.6–1.4 fps and displayed the next opening credit.

AI-assisted. No game assets or derived shader data are included.

@TheHoracio

Copy link
Copy Markdown

Independent timing of this change on another platform: Ryzen 7 9800X3D, Windows 11 Pro 10.0.26300, release build (cargo test --release). The benchmark is synthetic, with no game data: an #[ignore]d test appended locally to crates/victory-gpu/src/host.rs that calls copy_mapped. Each value is the mean of 5 or 10 repetitions after one warm-up.

Case Without this PR With this PR (head dcf6664)
32 MiB reserved, 32 committed 64 KiB islands (one per MiB) 24.86 ms 0.85 ms
256 MB fully committed, copy_mapped 29.22 ms 30.65 ms
256 MB fully committed, plain memcpy (reference) 15.07 ms 15.36 ms
  • The islands case matches your 27.36 → 1.23 ms on the i5-11600K / Windows 10.
  • A fully mapped range is unchanged. This PR only takes the new path after a failed bulk read.
  • A side note from the same numbers: a fully mapped kernel read (ReadProcessMemory) runs at about 8.7 GB/s here, against about 17 GB/s for memcpy. At the ~350 MB per frame reported in GPU: keep replaced host resources for 6 frames; bigger dynamic descriptor pool, no fallback to stale tables #135, that is about 40 ms. So most of the 240–470 ms per frame of copies that testers report likely comes from fallbacks like the ones this PR removes, not from raw copy speed.
Benchmark (local only)
#[cfg(test)]
mod zz_copy_bench {
    use windows_sys::Win32::System::Memory::*;
    fn alloc(len: usize, commit: bool) -> *mut u8 {
        unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | if commit { MEM_COMMIT } else { 0 }, PAGE_READWRITE) as *mut u8 }
    }
    fn time(label: &str, reps: usize, mut f: impl FnMut()) {
        f();
        let t = std::time::Instant::now();
        for _ in 0..reps { f(); }
        let ms = t.elapsed().as_secs_f64() * 1000.0 / reps as f64;
        eprintln!("BENCH {label}: {ms:.2} ms");
    }
    #[test]
    #[ignore]
    fn copy_paths() {
        // 1. fully mapped 256 MB
        let n = 256 << 20;
        let src = alloc(n, true);
        let dst = alloc(n, true);
        unsafe { std::ptr::write_bytes(src, 7, n); std::ptr::write_bytes(dst, 0, n); }
        time("memcpy 256 MB mapped", 5, || unsafe { std::ptr::copy_nonoverlapping(src, dst, n) });
        time("copy_mapped 256 MB mapped", 5, || super::copy_mapped(dst, src, n, false));
        // 2. 32 MiB reserved with 32 committed 64 KiB islands (every 1 MiB)
        let m = 32 << 20;
        let s2 = alloc(m, false);
        for k in 0..32 {
            let p = unsafe { VirtualAlloc(s2.add(k << 20) as _, 64 << 10, MEM_COMMIT, PAGE_READWRITE) } as *mut u8;
            unsafe { std::ptr::write_bytes(p, 9, 64 << 10) };
        }
        let d2 = alloc(m, true);
        time("copy_mapped 32 MiB, 32 x 64 KiB islands", 10, || super::copy_mapped(d2, s2, m, false));
    }
}

Not tested: in a title, on Windows 10, on other CPUs.

AI use: Claude Code (Claude Opus 5.5) wrote the benchmark, ran it on the machine above and drafted this comment.

@SkippySteve

Copy link
Copy Markdown

I ran this under Wine/Proton on Linux using only the synthetic victory-gpu tests. I used no game data and did not run a title session.

Setup

  • Linux 7.2.15, NVIDIA RTX 2060 SUPER, driver 615.78.08
  • UMU-Proton 11.0-2e (wine-11.0) with its bundled vkd3d-proton, in a fresh Proton prefix. I created the prefix with proton run, then ran the test executables with Proton's files/bin/wine and d3d12,d3d12core,dxgi=n,b.
  • Cross-built with cargo xwin test -p victory-gpu --target x86_64-pc-windows-msvc --no-run, debug profile.
  • Builds compared: main at d2a4bae (the PR's base), the PR at dcf6664, and main with only the new test added. The last build runs the new test against the old page-retry path.

Test results (3 runs each, --test-threads=1; every run gave the same result)

build passed failed ignored sparse_copies_preserve_islands_and_observe_remaps
main 40 3 1 n/a
main + new test only 41 3 1 ok
PR #202 41 3 1 ok

All three builds fail the same 3 tests, so the PR adds no failures. Those failures are already known on Wine:

The PR leaves #128 unchanged. That bug is on the title_dst = true path, where VirtualQuery reports vkd3d-proton's mapped destination as MEM_FREE. This PR only changes the !title_dst fallback, after a failed bulk read. Its sources there are title memory from the shadow, texture readback and Fill paths. That memory comes from VirtualAlloc, which Wine tracks, so VirtualQuery returns the correct state and the new test passes under Wine with the remap checks included.

Timing under Wine (an ignored ad-hoc test I added locally, not part of the PR). It copies 32 MiB with 32 committed 64 KiB islands, spaced 1 MiB apart, using copy_mapped(.., false). Each run is 10 copies, every one checked byte for byte; the table shows the median for each of 3 runs, in a debug build.

build median per run (ms)
main (page retries) 24.1 / 25.7 / 34.7
PR (region queries) 4.5 / 4.4 / 4.5

That is about 5–7× faster. You measured about 22× on Windows (27.36 → 1.23 ms). On Wine the VirtualQuery calls are not free, but they cost far less than the failed ReadProcessMemory retries they replace. I didn't see anything Wine-specific that argues against the change.

Not tested: release builds, AMD/RADV, and any in-game load.

muhammed-aksoy pushed a commit to muhammed-aksoy/VIctory that referenced this pull request Nov 24, 2026
@tanishq-dubey

Copy link
Copy Markdown

Independent Wine test of head dcf666486a3cb1fd47ad60437ef110d94c9f810e: cross-built the victory-gpu Windows test binary and ran sparse_copies_preserve_islands_and_observe_remaps under Wine 11.22 on Linux x86_64. 1 passed, 0 failed, including the protection change and newly committed page.

I also tried the same code in a world run alongside other local changes; it remained black and the runs are not controlled enough to attribute the timing difference to this PR. No game data attached. AI-assisted.

@tcurtsinger

Copy link
Copy Markdown

Independent Windows 11 timing on a Ryzen 9 9950X3D, comparing d2a4bae and dcf6664. The benchmark called the production copy path and checked every destination byte, including zero-filled holes. Four fresh processes per revision ran in interleaved order, each with three warm-ups and nine timed copies. The values below are medians of the four process medians.

32 MiB source Main This PR
32 committed 64 KiB islands 24.064 ms 0.508 ms
Fully committed control 2.226 ms 2.072 ms

In a separate RTX 4080 intro run, one sample on the previous build spent 299.8 ms copying 172.9 MB. A sample with this PR and four other changes spent 76.6 ms copying 172.6 MB. Only the synthetic comparison isolates this PR. The cutscene and memory results are in the RTX 4080 run report.

AI-assisted testing (Codex).

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

Tested dcf6664 on Windows 11, RTX 5070, MSVC: the workspace passes (196 outside victory-shader, which has its own known parallel-GPU hang and I ran separately), including sparse_copies_preserve_islands_and_observe_remaps. I could not compare in-game copy times.

  • The fast path is unchanged. Only a failed bulk read of at least 64 KiB into host memory (!title_dst) takes the new route.
  • VirtualQuery per region turns the 64K/4K probe storm over large holes into one zero-fill per hole. A committed region whose read still fails, because a mapping changed between query and read, falls back to read_pieces, so a race can't lose bytes. The test covers that remap case.
  • Not caching queries across copies is right, since titles remap.
  • Committed-but-PAGE_NOACCESS is zero-filled like a hole, which matches what read_pieces produced for those pages before.

No issues found.

AI-assisted (Claude Code).

mercuryVM added a commit to mercuryVM/VIctory that referenced this pull request Nov 24, 2026
…iled bulk read into host memory

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

Copy link
Copy Markdown
Contributor

Independent Windows check of dcf6664 merged onto ffe310e, prompted by the query/read window in #783.

I forced one 4 KiB page inside a committed 128 KiB region to be decommitted immediately after VirtualQuery reported the region and before the kernel copy. copy_mapped recovered the readable bytes on both sides, zeroed the new hole, and preserved the destination sentinels. Removing the read_pieces retry after a failed region read made the test fail. Restoring it passed along with the existing sparse-copy test.

I also compared the existing piece retries and the region scan in one binary. Both timings include the initial failed bulk read. These are medians of three fresh-process medians. Each process alternated the two routes, used seven timed samples per route after warm-up, and compared every output byte.

Synthetic 174 MiB range Piece retries Region scan
One 4 KiB hole 84.8 ms 86.8 ms
Two committed 64 KiB islands 411.0 ms 29.8 ms

The speedup on this setup depended on how much of the address range was unmapped. The query/read regression exercises the host-destination read path, and the timing is a synthetic copy benchmark.

AI-assisted; run on Windows using process-owned test memory.

github-actions Bot added a commit to KevinPratap/VIctory that referenced this pull request Nov 24, 2026
github-actions Bot added a commit to KevinPratap/VIctory that referenced this pull request Nov 24, 2026
github-actions Bot added a commit to KevinPratap/VIctory that referenced this pull request Nov 24, 2026

Marvisak commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

This pull request no longer merges cleanly into main (conflicts in crates/victory-gpu/src/host.rs). It will be reviewed once it is rebased onto the current main. The earlier verdict (merge-candidate) was for an older state of main.


Generated by Claude Code

@ifBars
ifBars force-pushed the gpu/sparse-host-reads branch from dcf6664 to 2ea6961 Compare November 25, 2026 10:02
@ifBars

ifBars commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (940d32f) and pushed 2ea6961. The conflict was two tests added at the same location in host.rs; both tests are preserved. The sparse-copy behavior is unchanged. I also added the safety comment required by the current Clippy check beside VirtualQuery.

Validation on Windows 10:

  • Both CI Clippy commands pass: standard and all-features workspace/all-targets, with --locked -- -D warnings.
  • The sparse-copy regression passes with default features and with all features. The asset-policy check and all six xtask tests pass.
  • The GPU suite has 140 passed, 4 failed, 2 ignored. Unmodified main on this machine has 139 passed, the same 4 failed, and 2 ignored. Those failures are dynamic_slots_are_held_until_released, a_texture_written_in_one_format_reads_in_another_through_a_placed_view, lists_share_a_table_and_copies_keep_their_views, and pipelines_load_on_many_threads_at_once.
  • The remaining workspace tests were run serially. The shader suite has 172 passed, 75 failed, 3 ignored; the failures report no SM 6.6 device available. This is not a fully passing local workspace run. No new title session or performance measurement was made.

GitHub now reports the PR as mergeable. AI-assisted (Codex).

Hosted validation: CI passed for commit 2ea6961, including both Clippy configurations and the full workspace test suite.

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.

8 participants