GPU: cheaper title memory copies, refresh batches and copy-back #2349
No reviewers
Labels
No labels
accessibility
area: build
area: formats
area: gpu
area: loader
area: runtime
area: shader
bug
documentation
duplicate
enhancement
good first issue
gpu: amd
gpu: intel
gpu: nvidia
help wanted
host: wine
invalid
out of scope
question
request
run report
triage: confirmed
triage: has patch
triage: merge candidate
triage: needs info
triage: needs rebase
triage: needs work
triage: proposed close
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/Marvisak--VIctory!2349
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-2349"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
@denkencar-sketch on GitHub · 2026-11-25 11:25 UTC · original
denkencar-sketch:perf/cpu-hotpath→main· +633 −135 · 3 files · 4 commits · draftSummary
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 inhost.rs,watch.rsandshadow.rs; they are separate ideas in one branch and can be split if you prefer.ReadProcessMemory.host::readcalledReadProcessMemory(GetCurrentProcess(), ...)on every shadow refresh and copy-back only to survive rare unmapped or read-only pages. A small x86-64global_asm!leaf,victory_copy_fast(rep movsb), now does the copy; the vectored handler inwatch::install(host::recover_copy) redirectsRipto a fault label that returnsfalsefor any fault inside the copy window except a breakpoint or single step. The routine keepsrdiandrsiinr10andr11, 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 toReadProcessMemory.watch::ensure_installed()makes sure the handler exists before the first copy.Batch::addmerged a shadow's refreshes into one bounding span, so two small draws at opposite ends of a large buffer refreshed everything between.Batchnow keeps sorted disjoint ranges (coalescing only overlapping or touching ones, or ones within one 64 KiB watch page for tracked shadows).Changedgets an exactdirtycount and ahas_savedflag soTracked::takeandTracked::changedreturn without locks when nothing changed (about 97% of checked ranges in #400), and saved bytes are cleared in one batch whileGUARDSis held.Vecper 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 onmain, 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 with0x80000001without the fix) and the gap test above, plus an#[ignore]benchmarkbench_copy_and_watch_throughput. On Windows x64 (MSVC):cargo build --release --lockedok;cargo test --workspace --lockedin debug and release 707 passed, 0 failed, 11 ignored (main: 701 passed);-p victory-gpu --lib -- --test-threads=1149 passed in both profiles; 20 consecutivevictory-gpulib runs green;cargo clippy --workspace --all-targets --locked -- -D warningsclean;cargo xtask policyok. 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
Ripredirect 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 whereReadProcessMemorywrote nothing.AI-assisted.
@denkencar-sketch on GitHub · 2026-11-25 11:34 UTC · original
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
@welisonzika14-jpg on GitHub · 2026-11-25 12:25 UTC · original
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
7cfd391merged ontomain940d32f,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 asmainon this card: the 5 known NVIDIA failures from #1744 (2 view heap cap tests invictory-gpu, 3 invictory-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 on GitHub · 2026-11-25 12:38 UTC · original
@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.
victory_copy_fast)Idea 1 breaks the picture on its own. copystat shows why:
The
rep movsbcopy fails on memory theReadProcessMemorypath reads fine.copy_mappedthen fills those 4 KiB pieces with zeros, so vertex and constant data arrive as zeros. Under Wine,NtReadVirtualMemoryfor the current process is amemmoveinside__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 inrecover_copynaming 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 on GitHub · 2026-11-25 12:51 UTC · original
Native Windows title run on an RTX 5070 Ti, driver 621.01, i7-14700, Windows 11 build 26200. I compared
7cfd391with the same local build without #2349. Both used940d32fwith #439, #2311 and the local GPU fixes listed in the #2311 test.One run each, PR build first. The runs started with byte-identical warm cache and save copies, the same scripted Enter and the
diagbuild. 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 on GitHub · 2026-11-25 13:19 UTC · original
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.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 on GitHub · 2026-11-25 13:21 UTC · original
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):
ReadProcessMemory)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 on GitHub · 2026-11-25 15:30 UTC · original · edited 2026-11-25 16:00 UTC
Automated triage for the maintainers.
This pull request no longer merges cleanly into
main(conflicts incrates/victory-gpu/src/host.rs,crates/victory-gpu/src/watch.rs). It will be reviewed once it is rebased onto the currentmain. The earlier verdict (needs-work) was for an older state ofmain.Generated by Claude Code
@Venom2054 on GitHub · 2026-11-25 15:39 UTC · original
I tested the split suggested in the review on native Windows 11 (i7-14700, RTX 5070 Ti). I extracted ideas 3 and 4 from
7cfd391onto940d32f. Production changes were confined towatch.rsandshadow.rs. Both builds used the originalhost.rs, including its copy routine and refresh ranges.Median CPU time per
Tracked::takecall over 16 tracked 64 KiB pages: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
watchandshadowtests passed on the split, includingword_merge_matches_bytewise_mergefrom idea 4. The fullvictory-gpulibrary suite had 141 passes on main and 142 on the split. Both had the same two failures (dynamic_slots_are_held_until_releasedandlists_share_a_table_and_copies_keep_their_views) and three ignored tests, including the timing harness. Both used the optimizeddiagprofile with default features.@pickles976 on GitHub · 2026-11-25 17:14 UTC · original
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 sourcePAGE_GUARD. I added a CPU-only consumer regression tohost::title_copiesin a local integration based on71476715eeb6c07759a71d18e4d79561a3c29242(other local PR integrations present; the productioncopy_mapped/readpath here is still the RPM implementation). It allocates three 4 KiB pages containing0x77, protects the middle as READWRITE|GUARD and the last as NOACCESS, then callscopy_mapped(..., title_dst=false)into a host buffer.VirtualQueryafterward reports the middle page's guard bit cleared: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
memmoveinside__TRYfor 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_copyin7cfd391checks 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 (andcopy_mapped's subsequent fallback), not just the initialfalse: 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
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.
@denkencar-sketch on GitHub · 2026-11-25 23:34 UTC · original
Converting to draft while this is split/reworked against current \main:
Thank you @desplmfao, @Venom2054, @wbkepler, @pickles976, and @welisonzika14-jpg for the thorough measurements and testing.
View command line instructions
Manual merge helper
Use this merge commit message when completing the merge manually.
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.