Skip to content

GPU: cheaper title memory copies, refresh batches and copy-back - #2349

Draft
denkencar-sketch wants to merge 4 commits into
Marvisak:mainfrom
denkencar-sketch:perf/cpu-hotpath
Draft

denkencar-sketch wants to merge 4 commits into
Marvisak:mainfrom
denkencar-sketch:perf/cpu-hotpath

Conversation

@denkencar-sketch

Copy link
Copy Markdown
Contributor

Summary

CPU-side cost of preparing and copying title memory in victory-gpu (the ~400-500 ms/frame preparation, write-watch and copy-back overhead in #400). Four changes in host.rs, watch.rs and shadow.rs; they are separate ideas in one branch and can be split if you prefer.

  1. User-space title copy instead of ReadProcessMemory. host::read called ReadProcessMemory(GetCurrentProcess(), ...) on every shadow refresh and copy-back only to survive rare unmapped or read-only pages. A small x86-64 global_asm! leaf, victory_copy_fast (rep movsb), now does the copy; the vectored handler in watch::install (host::recover_copy) redirects Rip to a fault label that returns false for any fault inside the copy window except a breakpoint or single step. The routine keeps rdi and rsi in r10 and r11, so it never touches the stack. Overlapping ranges go through a temporary buffer (the kernel path could corrupt them), and a non-x86-64 target or a failed reserve falls back to ReadProcessMemory. watch::ensure_installed() makes sure the handler exists before the first copy.
  2. Disjoint refresh intervals. Batch::add merged a shadow's refreshes into one bounding span, so two small draws at opposite ends of a large buffer refreshed everything between. Batch now keeps sorted disjoint ranges (coalescing only overlapping or touching ones, or ones within one 64 KiB watch page for tracked shadows).
  3. Lock-free unchanged path. Changed gets an exact dirty count and a has_saved flag so Tracked::take and Tracked::changed return without locks when nothing changed (about 97% of checked ranges in World on an RTX 5070 Ti: where the ~0.8 s per frame go, and four open copy PRs measured against main #400), and saved bytes are cleared in one batch while GUARDS is held.
  4. Copy-back scratch and word merge. A reusable thread-local 64 KiB buffer replaces a fresh Vec per page, and the three-way merge compares 8 bytes at a time, skipping writes to write-combined memory when the title and host bytes already agree.

Behaviour change to be aware of

A copy's refresh no longer fills the gap between its declared ranges. What a shader may read is what its views declare, and the old bounding span refreshed gaps only by chance; across the ranges of a 174 MB buffer the span was most of the copy cost. The page stays changed and is copied by the next submission that declares it, so nothing is lost, but a shader reading outside its declared range sees the earlier bytes in that submission. Test: a_refresh_leaves_the_gap_between_its_declared_ranges (fails on main, passes here).

Testing

New tests include overlapping_copies_preserve_data, batch_ranges_stay_disjoint_across_gaps_and_coalesce_within_page, word_merge_matches_bytewise_merge, a_guard_page_source_fails_the_copy (dies with 0x80000001 without the fix) and the gap test above, plus an #[ignore] benchmark bench_copy_and_watch_throughput. On Windows x64 (MSVC): cargo build --release --locked ok; cargo test --workspace --locked in debug and release 707 passed, 0 failed, 11 ignored (main: 701 passed); -p victory-gpu --lib -- --test-threads=1 149 passed in both profiles; 20 consecutive victory-gpu lib runs green; cargo clippy --workspace --all-targets --locked -- -D warnings clean; cargo xtask policy ok. A fuzz of the interval insert and coverage code (6000 rounds, offsets at the page edge) matched a byte-by-byte reference.

Measured in release on the benchmark: 256 B copies 63.7 ms -> about 4.9 ms; 200 write_mapped calls over 64 blocks with 32 unmapped 329 ms -> 171 ms. The 200 MB copy goes from 9 ms to about 2 ms, but with a cache-hot 64 KiB source and destination, so treat it as an upper bound.

Not tried: a run in the game, the GNU Windows target (the toolchain pins MSVC), and the Rip redirect under hardware-enforced stack protection (EHCONT). One known difference from the kernel path: with an unreadable page in the middle of a range, the new copy writes the mapped prefix where ReadProcessMemory wrote nothing.

AI-assisted.

…ut unwind information

A guard page raises STATUS_GUARD_PAGE_VIOLATION inside the rep movsb; only
access violations and in-page errors were recovered, so the process ended
(the kernel's copy returns false). Any fault with Rip in the copy now
fails it, but for a breakpoint or a single step.

The copy pushed rdi and rsi without unwind information, so a stack walker
read the saved rsi as its return address. It keeps them in r10 and r11
now, no stack at all.
…ord merge

The slow zero-fill of the overlap buffer stays, allowed with its reason
(the reserve is what lets an absurd length fall back to the kernel).
… a test says so

Decision on the behaviour change of the batched refresh: kept. The old
bounding span of a copy's ranges refreshed a page the title wrote between
two declared ranges only by chance; what a shader may read is what its
views declare, and across the ranges of a 174 MB buffer the span was most
of the copy cost. The page stays changed (the watch keeps it) and is
copied by the next submission that declares it, so nothing is lost, only
a read outside the declared range sees the earlier bytes in this one.
The test fails on 940d32f (the gap is copied there) and passes here.
@denkencar-sketch

Copy link
Copy Markdown
Contributor Author

Benchmark (release) | Before | After | Time saved
256 B copies, 200k of them | 63.7 ms | 4.9 ms | about 92% (13× faster)
200 MB copy, cache-hot (upper bound) | 9.06 ms | 1.94 ms | about 79% (4.7× faster)
200 write_mapped over 64 blocks, 32 unmapped

@denkencar-sketch
denkencar-sketch marked this pull request as ready for review November 25, 2026 11:42

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

Cheaper title memory copies: refresh ranges coalesced per copy without pulling gaps, textures hashed once per submission (+633). Static review only: victory-gpu/victory-hle are Windows-only (D3D12/windows-sys); not compiled or tested on this macOS arm64 host. rustc 1.98.1. Big perf-motivated rework of the refresh path; needs Windows validation, but the coalescing logic reads carefully.

@welisonzika14-jpg

Copy link
Copy Markdown

First run on NVIDIA hardware here, as far as I can see. RTX 5070 (Blackwell, driver 621.24), Ryzen 7 5700X, Windows 11, Rust 1.98.1 MSVC, no game files. Head 7cfd391 merged onto main 940d32f, cargo test -p victory-gpu -p victory-shader --lib --no-fail-fast.

The PR's new test(s) pass on this card: host::title_copies::a_guard_page_source_fails_the_copy, host::title_copies::the_fast_copy_uses_no_stack, host::title_copies::overlapping_copies_preserve_data, host::title_copies::batch_ranges_stay_disjoint_across_gaps_and_coalesce_within_page, host::title_copies::a_refresh_leaves_the_gap_between_its_declared_ranges, shadow::tests::word_merge_matches_bytewise_merge. The rest is the same as main on this card: the 5 known NVIDIA failures from #1744 (2 view heap cap tests in victory-gpu, 3 in victory-shader), nothing new.

One run, unit tests only, title not run.

Written with AI help (Claude/Kiro); the numbers are from runs on my machine.

@desplmfao

Copy link
Copy Markdown
Contributor

@denkencar-sketch I ran this in the title, since the description says it hasn't been run there yet. It changes what the title draws, so here is what I measured.

Setup: Grand Theft Auto VI Series X, the first mission's prison yard. RTX 5080 on Linux, Proton with vkd3d-proton 3.2.0. Our stack of open PRs plus this one, warm pipeline cache, about 4,900 draws per frame in the scene.

Build ms/frame preparing copies Picture
without this PR 901 521 399 complete
all four ideas 624 274 55 about half the scene missing: 2,400 draws/frame, the yard outside the window not drawn
ideas 1 + 3 + 4 (idea 2 reverted) 600–650 252–272 53–63 the player character and the walls vanish, the window turns black, and the lighting flickers from frame to frame
idea 1 only (victory_copy_fast) 800 407 110 geometry stretched across the screen, green and magenta smears

Idea 1 breaks the picture on its own. copystat shows why:

moves unmapped
without this PR 146 ms 0.00–0.03 MB/frame
idea 1 only 3.7 ms 0.6–1.2 MB/frame

The rep movsb copy fails on memory the ReadProcessMemory path reads fine. copy_mapped then fills those 4 KiB pieces with zeros, so vertex and constant data arrive as zeros. Under Wine, NtReadVirtualMemory for the current process is a memmove inside __TRY, so faults stay in Wine's own handler. With this PR they go through the vectored handlers instead, where something else, possibly the write-watch handler or a handler installed first, may take them. I haven't pinned down which pages. A log line in recover_copy naming the address and exception code would show it.

Idea 2 removes about half the scene. That's the gap behaviour your description already warns about: the title's shaders do read outside their declared ranges (here, apparently, the data that decides what gets drawn outside).

Ideas 3 and 4: I didn't run them on their own. Reading the code, the lock-free path and the word merge look equivalent to main.

The speed is real: copies went from 399 to 55 ms a frame. But as it stands this PR changes the picture badly in the title. Since it wasn't tried in the title and changes behaviour there, I'd suggest marking it as a draft until it has had a game run. I'd keep ideas 3 and 4, find out which reads idea 1 fails, and drop or gate idea 2.

How it was found: A/B runs of the same scene, then branches with idea 2 reverted and with idea 1 alone, compared on the fps and copystat lines.

@Venom2054

Copy link
Copy Markdown

Native Windows title run on an RTX 5070 Ti, driver 621.01, i7-14700, Windows 11 build 26200. I compared 7cfd391 with the same local build without #2349. Both used 940d32f with #439, #2311 and the local GPU fixes listed in the #2311 test.

Intro sequence Without #2349 With #2349
Elapsed time for 250 frames 182.33 s 170.25 s
Mean frame time 729.3 ms 681.0 ms
Frames per second 1.37 1.47
Host preparation 378.6 ms 293.5 ms
Copies during preparation 235.3 ms 136.2 ms
Copy volume 681.2 MB 669.0 MB
Host draws per frame 3436.0 3487.0
Copy move time 112.77 ms 57.13 ms
Unmapped per frame 14.15 MB 12.89 MB

One run each, PR build first. The runs started with byte-identical warm cache and save copies, the same scripted Enter and the diag build. DRED was on, the D3D12 debug layer and per-command GPU timing were off. Elapsed time is between captures at +50 and +300 presented frames after the first frame with at least 500 host draws. The preparation and copy counters are medians of periodic samples (31 without, 29 with). Copy time is part of preparation.

On native Windows both builds already reported unmapped MB during the intro. The capture offsets landed on different shots. This pair measures throughput across that sequence and cannot establish whether #2349 drops geometry in a matched scene. With #2349 I reached +500 frames (288 s after the marker) without device removal before stopping. A street and backlit figures were visible at different points, with much of the foreground still dark.

@Venom2054

Copy link
Copy Markdown

I followed up on the prison-yard comparison on native Windows. On this RTX 5070 Ti, people in the yard and the watchtower were visible through the opening with and without 7cfd391. The foreground character and the area to the right of the opening were dark in both builds once the lighting had settled.

Prologue yard, view from behind the character Without #2349 With #2349
Time for 64 frames 42.10 s 37.44 s
Mean frame time 657.8 ms 585.0 ms
FPS 1.52 1.71
Host preparation 289.3 ms 223.9 ms
Copies during preparation 180.0 ms 113.0 ms
Host draws per frame 5007.0 4982.0
Unmapped per frame 0.04 MB 0.03 MB

One run per build. Same local stack and hardware, starting profile, warm cache and scripted inputs. Both builds had identical local diagnostics to confirm the game read the controller state and to capture every eighth presented frame. The PR build ran first. The transition into the yard advanced at different rates, so I used the first capture after 310 s from GameInput creation in each run. I timed the next 64 presentations and checked the tower, window and foreground character at the start, middle and end. The last four rows are medians of periodic counters (8 samples without, 6 with). The camera positions differed slightly. I could verify these landmarks and the draw counts on this stack; smaller visual differences remain possible.

@wbkepler

Copy link
Copy Markdown
Contributor

Measured in the game on Windows 11 / RTX 5090, on a local integration branch with other open NVIDIA fixes (diagnostics build, 300 s runs, averages of the 5 s windows once the world is up):

per frame before with this PR
frame time ~530 ms (1.9–2.1 fps) ~440 ms (2.2–2.3 fps)
CPU preparing 233 ms 200 ms
title memory copies 60 ms 40 ms
refresh batches 84 ms 57 ms
kernel copies (ReadProcessMemory) 11.9 ms 5.1 ms
final batch flush 49 ms 35 ms
copying back 150 ms 126 ms

Stable: no device removal, panic or access violation in 300 s, same draw count in the world. The gap behaviour change (disjoint refresh ranges) showed no visible problem in that run.

Note: our branch already carries different copy-back changes in shadow.rs, so this PR's copy-back hunks there (thread-local scratch, word merge) were left out when merging. The numbers cover the fast copy, disjoint refresh ranges, and the lock-free watch path.

AI-assisted check (Claude Code); Windows 11 / RTX 5090.

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, crates/victory-gpu/src/watch.rs). It will be reviewed once it is rebased onto the current main. The earlier verdict (needs-work) was for an older state of main.


Generated by Claude Code

@Venom2054

Copy link
Copy Markdown

I tested the split suggested in the review on native Windows 11 (i7-14700, RTX 5070 Ti). I extracted ideas 3 and 4 from 7cfd391 onto 940d32f. Production changes were confined to watch.rs and shadow.rs. Both builds used the original host.rs, including its copy routine and refresh ranges.

Median CPU time per Tracked::take call over 16 tracked 64 KiB pages:

Synthetic workload Main Ideas 3 + 4
All pages unchanged 13.83 ns 2.08 ns
Write one byte on a rotating page every 256 calls 23.45 ns 11.79 ns

Each measurement made 500,000 calls. The test checked the exact changed range after every write and an empty result otherwise. I ran 12 pairs in alternating order with a separate warm-up. The split was faster in all 12 pairs for both workloads. These timings cover the tracking path in idea 3. The effect on frame time and geometry in the yard is still open.

All 11 watch and shadow tests passed on the split, including word_merge_matches_bytewise_merge from idea 4. The full victory-gpu library suite had 141 passes on main and 142 on the split. Both had the same two failures (dynamic_slots_are_held_until_released and lists_share_a_table_and_copies_keep_their_views) and three ignored tests, including the timing harness. Both used the optimized diag profile with default features.

@pickles976

Copy link
Copy Markdown

Additional Wine guard-page evidence for the copy-path work, rather than a competing implementation.

Measured: on Wine 11.0/Linux x86-64, the existing ReadProcessMemory(GetCurrentProcess(), ...) path already consumes a source PAGE_GUARD. I added a CPU-only consumer regression to host::title_copies in a local integration based on 71476715eeb6c07759a71d18e4d79561a3c29242 (other local PR integrations present; the production copy_mapped/read path here is still the RPM implementation). It allocates three 4 KiB pages containing 0x77, protects the middle as READWRITE|GUARD and the last as NOACCESS, then calls copy_mapped(..., title_dst=false) into a host buffer. VirtualQuery afterward reports the middle page's guard bit cleared:

assertion `left == right` failed: the title's guard must remain armed
  left: 0
 right: 256
test result: FAILED. 0 passed; 1 failed; 0 ignored

The allocation is released before the result assertions. The zero-fill assertion follows the failing guard assertion, so this run does not establish its result.

Wine 11's NtReadVirtualMemory uses memmove inside __TRY for this pseudo-handle, not a kernel-mediated read. That distinction matters when the caller retries failed ranges.

Review implication, not a PR-head test result: a_guard_page_source_fails_the_copy in 7cfd391 checks the failed read but not whether the title's guard remains armed. The fast-copy fault handler redirects RIP without re-arming the guard. Please cover guard state (and copy_mapped's subsequent fallback), not just the initial false: a GPU staging read should not silently consume the title's next guard fault. This is distinct from the already-reported disjoint-range/rendering issue. I have not executed this PR head or established that this synthetic case causes a retail-game failure; no native-Windows, FPS or VRAM claim.

Consumer regression, inside the existing host::title_copies module
    #[test]
    fn title_copy_preserves_guarded_source_pages() {
        use windows_sys::Win32::System::Memory::{
            MEMORY_BASIC_INFORMATION, PAGE_GUARD, VirtualQuery,
        };
        const PAGE: usize = 4096;
        let base = unsafe {
            VirtualAlloc(std::ptr::null(), 3 * PAGE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)
        }.cast::<u8>();
        assert!(!base.is_null());
        let mut old = 0;
        unsafe {
            base.write_bytes(0x77, 3 * PAGE);
            assert_ne!(VirtualProtect(base.add(PAGE).cast(), PAGE, PAGE_READWRITE | PAGE_GUARD, &mut old), 0);
            assert_ne!(VirtualProtect(base.add(2 * PAGE).cast(), PAGE, PAGE_NOACCESS, &mut old), 0);
        }
        let mut copied = vec![0xee; 3 * PAGE];
        copy_mapped(copied.as_mut_ptr(), base, copied.len(), false);
        let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
        let queried = unsafe {
            VirtualQuery(base.add(PAGE).cast(), &mut info, std::mem::size_of_val(&info))
        };
        release(base);
        assert_ne!(queried, 0);
        assert_eq!(info.Protect & PAGE_GUARD, PAGE_GUARD, "the title's guard must remain armed");
        assert!(copied[..PAGE].iter().all(|&b| b == 0x77));
        assert!(copied[PAGE..].iter().all(|&b| b == 0), "guard and no-access pages read as zeros");
    }

Command: cargo test --locked --target x86_64-pc-windows-msvc -p victory-gpu --lib host::title_copies::title_copy_preserves_guarded_source_pages -- --exact --nocapture, Rust 1.98.1 MSVC cross-build, Wine runner.

AI-assisted investigation and regression: omp / openai-codex/gpt-6-astra.

AntoninMichelq added a commit to AntoninMichelq/VIctory-forkAMD that referenced this pull request Nov 25, 2026
…th rep movsb, not through the kernel

After upstream PR Marvisak#2349 (denkencar-sketch, dcb4ac3 + 78dced0), read only.
The refreshes of host copies read 110-160 MB of title memory a frame
through ReadProcessMemory: the frame line's "copies", 36-46 ms (runs of
2026-11-25). With the switch, reads into our own memory (copy_mapped into
a host copy, read_into) are a leaf rep movsb with no stack; a vectored
handler, ahead of the others, sends a fault inside it (a page not there, a
guard page; not a breakpoint or a single step) to its return of 0, so the
copy fails as the kernel's does and the callers fall back as before.
Writes into title memory stay the kernel's (our guards take user writes
there as the title's). Tests: no-access and guard pages fail the copy, the
copy uses no stack.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
AntoninMichelq added a commit to AntoninMichelq/VIctory-forkAMD that referenced this pull request Nov 25, 2026
…he ranges asked only, GPU upload heaps said in the log

- VICTORY_REFRESH_RANGES=1: a submission's refreshes of a host copy are
  the ranges its lists asked for, joined only where within 64 KiB (past
  256 ranges, their envelope), not one range from the lowest to the
  highest (upstream Marvisak#2349 dcb4ac3/7cfd3912, Marvisak#2428 3a2279f, read only).
  Run cpuframe (2026-11-26 00:19): 8.5 GB of refresh ranges asked of the
  write watch a frame (the 174 MB heap's envelope at every flush), 33 ms,
  for ~130 MB copied. Tests for the joining.
- VICTORY_BACK_BLOCKS=1: what shaders wrote goes back into title memory
  by 1 KiB block, only the blocks the merge changed, not the span from the
  first changed byte to the last (upstream Marvisak#2242/Marvisak#2280 without their shader
  marks); never writes the title's newer bytes over with older ones there.
- VICTORY_FAST_TITLE_WRITE=1: those writes by rep movsb (the caller opened
  our guards), through the kernel only if a fault fails it: hundreds of
  pieces a frame were each a kernel call.
- A log line says whether the card offers GPU upload heaps (resizable BAR);
  an ignored test asks this PC's card: the RX 7600 does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@denkencar-sketch
denkencar-sketch marked this pull request as draft November 25, 2026 23:34
@denkencar-sketch

Copy link
Copy Markdown
Contributor Author

Converting to draft while this is split/reworked against current \main:

  • Idea 4 (shadow writeback merge) is now covered by merged GPU: Speed up shadow buffer writeback merging #2054.
  • Idea 3 (lock-free unchanged check) partially overlaps with \main's atomic \dirty_bit\ / \Tracked::clean().
  • Ideas 1 and 2 need investigation/fixes for the in-game rendering regressions reported by @desplmfao and the \PAGE_GUARD\ preservation issue noted by @pickles976 before this is ready for review again.

Thank you @desplmfao, @Venom2054, @wbkepler, @pickles976, and @welisonzika14-jpg for the thorough measurements and testing.

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