Repository navigation
GPU: cheaper title memory copies, refresh batches and copy-back - #2349
denkencar-sketch wants to merge 4 commits into
Conversation
…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.
|
Benchmark (release) | Before | After | Time saved |
catminou4
left a comment
There was a problem hiding this comment.
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.
|
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 The PR's new test(s) pass on this card: One run, unit tests only, title not run. Written with AI help (Claude/Kiro); the numbers are from runs on my machine. |
|
@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.
Idea 1 breaks the picture on its own. copystat shows why:
The 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 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. |
|
Native Windows title run on an RTX 5070 Ti, driver 621.01, i7-14700, Windows 11 build 26200. I compared
One run each, PR build first. The runs started with byte-identical warm cache and save copies, the same scripted Enter and the 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. |
|
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
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. |
|
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):
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 AI-assisted check (Claude Code); Windows 11 / RTX 5090. |
|
Automated triage for the maintainers. This pull request no longer merges cleanly into Generated by Claude Code |
|
I tested the split suggested in the review on native Windows 11 (i7-14700, RTX 5070 Ti). I extracted ideas 3 and 4 from Median CPU time per
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 |
|
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 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 Review implication, not a PR-head test result: 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: AI-assisted investigation and regression: omp / openai-codex/gpt-6-astra. |
…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>
…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>
|
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. |
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 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 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 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.