GPU: batch dirty heap page ranges under one diff pass in sync_heaps #3137
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/3139"
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?
Imported from Marvisak/VIctory. Originally posted by MeMako on 2026-11-26T09:55:41Z.
Part 1 of the triage-requested 3-part split of #3055: batches dirty 64 KiB heap page ranges, pre-reads mapped pages via
read_intointo a reusable buffer before locking, and diffs all dirty slot ranges under oneself.made->VIEWSlock with zero thread changes. Part 2 (batched buffer lookup viafind_existing_batch/PreparedBuffer) will be opened once Part 1 lands, and #3055 stays as a Draft for Part 3 (parallel sync viacrate::texture::in_parallel).Problem
In
descriptor::sync_heaps(), each dirty 64 KiB heap page callsHostHeap::sync_slotsindividually. Every page allocates three temporaryVecs (records,current,stale), locksVIEWSandself.madeseparately, and checksVIEWSeven for empty unchanged slots (tag != VIEW_TAG && made == 0).Fix
crates/victory-gpu/src/descriptor.rs:sync_heaps()and passes them in one call toHostHeap::sync_ranges, adding the returned readable slot count toSyncSlotsunderdiagnostics.views_current(&[[u32; 3]]) -> Vec<bool>withwith_views(|views| ...), avoiding the per-pageVec<bool>allocation.crates/victory-gpu/src/descriptor/host.rs:merge_ranges(ranges, cap)to clamp, sort, and merge overlapping/adjacent ranges once (preserving the capped-heap warning viapast_cap.max(last - 1)).HostHeap::sync_ranges(&self, ranges: &[(u32, u32)], start: u64, step: u64) -> u64(keepingsync_slotsunder#[cfg(test)]as a 1-line wrapper).crate::host::read_intobefore taking any locks (closing the probe-to-read concurrent-unmap window and removingunsafereads fromsync_ranges), then holdsself.made->VIEWS(same lock order asmirror) across the pure in-memory diff pass while skipping theVIEWSlookup for slots withtag != VIEW_TAG.HostHeap::mirrorpath with no thread changes.merge_ranges_sorts_clamps_and_merges_adjacent_and_overlappingandsync_ranges_merges_overlapping_and_out_of_order_ranges.Verification & Benchmarks
Host: Windows 11 (
10.0.26200), AMD Ryzen 9 7950X, AMD Radeon RX 9070 XT (RDNA 4, driver32.0.32029.2010), basemain63bcca4.cargo clippy --workspace --all-targets --locked -- -D warnings: clean.cargo clippy --workspace --all-targets --all-features --locked -- -D warnings: clean.cargo test -p victory-gpu --lib --locked -- --test-threads=1: 233 passed, 0 failed, 1 ignored (includingmerge_ranges_sorts_clamps_and_merges_adjacent_and_overlappingandsync_ranges_merges_overlapping_and_out_of_order_ranges).cargo run --locked -p xtask -- policy:asset policy: 191 files ok.Standalone benchmark (
--release,world_frame_sync_heapson Draft #3055, 700,416 slots across 342 dirty 64 KiB pages, 9-round medians,mainvs. Part 1 alone):main(63bcca4) median24618c9) median0changed / 700k scanned)6,000changed / 700k scanned)14,000changed / 700k scanned)Hardware runs and tests were performed by me on my 7950X / RX 9070 XT; PR and code drafted with Antigravity.
Imported from Marvisak/VIctory. Originally posted by Dukestar69 on 2026-11-26T12:29:44Z.
Review: APPROVED
Verified on RTX 5090 against
origin/main(63bcca4):cargo test -p victory-gpu --lib descriptor:: -- --test-threads=1 --skip dynamic_slots_are_held_until_released: 22/22 passed (includingsync_ranges_merges_overlapping_and_out_of_order_ranges).cargo clippy -p victory-gpu --all-targets -- -D warnings: clean.cargo xtask policy: 191 files ok.Cleanly batches dirty heap page ranges under one diff pass in
sync_heaps.Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).
Imported from Marvisak/VIctory. Originally posted by Jackster on 2026-11-26T12:15:34Z.
On the retail title the batch does not move it, and the time is in view creation, not the scan
Same setup as my note on #2821 (Windows 11, RX 7900 XTX, 300 s world runs, same save, same cache).
stack2=63bcca4+ #2703 #1010 #2985 #2849 #2908 #2472 #2958 #3118 #2821, with and without this PR merged in:-8% on the sync, not the 2.43x the scan benchmark suggests: that gain needs many unchanged slots to skip, and in the world nearly every slot looked at has changed, so there is little to skip. The frame coming out lower I put down to scene spread in a single run.
What the sync is doing, from counters I added to
HostHeap::mirror(~400k slots examined a frame):So the cost is the ~47k
Create*Viewcalls, not the per-page scan this PR batches.For scale, deferring the read-only ones (constant buffers, buffer shader resources, non-UAV memory views) to the submission that first reads them took the sync from 261 ms to 126-151 ms and the frame from 1,025 ms to 859-880 ms at the same draw count. That prototype is not correct yet: a skipped slot keeps its previous descriptor, and constant-buffer slots have no read mark to bring them back (the tree marks texture reads; a local change also marks buffer loads; CBVs are the gap).
Suggestion: a "changed vs unchanged" line in the benchmark would predict which titles gain from the batch.
Written with an AI assistant.
Imported from Marvisak/VIctory. Originally posted by MeMako on 2026-11-26T12:28:05Z.
Thanks for running this on a real world trace and breaking down the
HostHeap::mirrorcounters — super helpful data!A few notes on those numbers:
+ #3139run (316,757 -> 394,581, likely scene spread as you noted), descriptor sync still dropped261.3 -> 239.1 ms(0.825 -> 0.606 usper mirrored slot,-26.5%), which lines up with the heavier-change end of our standalone benchmark table (14k / 700k->1.11x).0,6k, and14kchanged out of700kslots), and adding a higher-churn row (~12% changed, matching your ~47k / 400k ratio) makes sense so readers can see where Part 1's scan/diff speedup tapers off.Create*Viewbreakdown is spot-on and is exactly why#3055was split into three parts: Part 1 (#3139) cleans up thesync_heapsscan/diff half (eliminating per-page allocations/locks and skipping empty unchanged slots), while Part 2 (pr/sync-heaps-2-batched-buffers, queued behind this) batches theBUFFERSlookup for buffer/CBV/placed-memory views, and Part 3 (Draft#3055) parallelizesCreate*Viewacross workers viacrate::texture::in_parallel. Deferring read-only views to first use would also stack nicely on top of all three once CBV read-marking is solved.Comment drafted with Antigravity.
Imported from Marvisak/VIctory. Originally posted by Jackster on 2026-11-26T14:06:04Z.
Follow-up: with the read marks in place, the deferral does not hold up
When I wrote the note above I had only the upper bound: skipping read-only slots without making them later. With the translator now marking buffer and constant-buffer heap reads, the host makes a marked slot after the submission that read it, and the saving largely disappears:
-4%, not -25%. The work moves rather than disappearing: the frame needs ~32k distinct views either way, and deferring them only decides when they are made.
One correction to my earlier note that may save someone time: a heap constant buffer is not a kind-13 handle. Shaders read one as a raw buffer view (kind 11,
emit/mod.rs"Constant buffers in the heap"), which is why the read-only raw kinds had to be let into the index map (heap_handle) before anything downstream could mark them.So for this PR's premise: batching helps only stale-heavy workloads (measured: not this one), and deferral helps only if the slots are never made at all (they are). What is left is the number and cost of the views a frame genuinely needs.
Written with an AI assistant.
Imported from Marvisak/VIctory. Originally posted by MeMako on 2026-11-26T15:06:51Z.
Thanks for the follow-up test — that's a really useful result, and the raw-view (kind 11) note on heap CBVs is great to have documented too.
Ruling out deferral actually lines up directly with why this work was split into three parts per triage feedback on
#3055: Part 1 (#3139) is intentionally just the zero-risk structural layer (collapsing the per-page loops into one deduplicatedstalebatch with no threading or lock-scope changes), not the full fix for those 261 ms. Since a frame genuinely needs those ~32k–47k views created either way, the bigger wins sit in Part 2 (batchedBUFFERSlookup) and Part 3 (parallelCreate*Viewacross workers).Draft
#3055already has all three parts stacked together if you ever feel like throwing it onstack2to see how much of the 261 ms moves once per-view lookup and view creation are batched and parallelized.Comment drafted with Antigravity.
Imported from Marvisak/VIctory. Originally posted by imjustprism on 2026-11-26T18:31:22Z.
Review: COMMENTED
ran
24618c9in the title and read the diff. rx 9070 xt, world, medians per frame:sync_heaps), ms63bcca4plus #2122 (this card needs it) plus a local timer aroundsync_heaps. two of the five runs without are plain; the other three have #2051 merged in, which does not touch this path. diag build, series-x, the same scripted key presses, warm shader and pipeline caches, quiet machine, 12-minute runs, medians over 47 to 74 world frame lines per run. no errors and no device removed. one run with the pr, so all i can say is: no change i can measure here. that fits your own table: at 1.48 ms per 700,000 unchanged slots on main, the scan is under 1 ms of the 12 ms here (an estimate from your figure, not a measurement), so the batch can save a few tenths of a millisecond at most. the rest is making the slots that changed, as the comments above found.what i checked from the description:
sync_ranges_merges_overlapping_and_out_of_order_rangesand the otherdescriptor::hosttests pass here.points from reading the diff:
descriptor/host.rs:731and:732. on main each 64 KiB page read its records with no lock, then tookVIEWSalone, let it go, and tookmadealone. nowmadeandVIEWSare held together across every range of the heap, with the reads of title memory inside (host.rs:737). the order is the onemirroralready uses (host.rs:790), so nothing can deadlock. but a title thread that records a view (descriptor.rs:504) or releases a resource (descriptor.rs:535) takesVIEWSwithoutSHADER_HEAPS: on main it could get in between two pages, now it waits for the whole heap. the hold is short, about your scan time, and i did not measure the wait. either the description and the doc onsync_rangesshould say so (the doc also says it skipsVIEWSfor empty slots, whileVIEWSstays locked and only the lookup is skipped), or the records can be read into a buffer before the locks are taken, which keeps the old scope.descriptor.rs:189. each page is probed with a 4-byte read and its records are read later with plain reads. on main the read came right after the probe of that page. now it comes after all pages are probed, two sorts, and the waits for both locks. the comment there says the title unmaps heap pages; if it can do that while another thread submits, the window for a fault is wider than it was. the race itself is older than this pr. do you know whether that can happen? reading each range withread_intobefore the locks would close it, and it is the same change as above.sync_ranges(i ran it that way: 1 passed), because a slot that is listed twice is mirrored twice with the same result. so it pins the result but not the merging. its doc says "adjacent", and no two of its ranges touch;(0, 16), (16, 32)would cover that.sync_heaps(descriptor.rs:202) and again insync_ranges(host.rs:722), afterTracked::takealready sorted its runs (watch.rs:464).sync_heapsis the only caller outside tests, so one of the two is enough.nothing here is a wrong result: each slot's stale decision matches main, the clamp to
countholds, andlast - 1runs only whenlastis abovecount.Imported from Marvisak/VIctory. Originally posted by MeMako on 2026-11-27T01:26:36Z.
Thanks for the review and the 9070 XT run. Good catches all around, pushed fixes in
f799496:descriptor.rs:189): Yes,SHADER_HEAPSonly stops theHeapfrom being dropped, not another thread unmapping backing pages. Replaced the 4-byte probe + later plain reads with page-chunkedread_intocopies into a reusable buffer before taking any locks, which closes that window and removes theunsafereads fromsync_ranges.descriptor/host.rs:731-732): Withread_intomoved out front,self.madeandVIEWSare now only held across the pure in-memory diff. Updated thesync_rangesdoc and PR description to state the actual lock scope and clarify that empty slots skip theVIEWSlookup, not the lock.merge_ranges(ranges, cap)helper indescriptor/host.rsand dropped the duplicate pass insync_heaps.merge_ranges_sorts_clamps_and_merges_adjacent_and_overlappingwith(0, 16), (16, 32)so removing the sort or merge actually fails, and added an adjacent pair tosync_ranges_merges_overlapping_and_out_of_order_ranges.Re: the benchmark,
world_frame_sync_heapslives on Draft#3055to keep this diff small.Re-ran
clippy(default +--all-features),victory-gpulib tests (233 passed), andxtask policyon Win 11 / RX 9070 XT.Imported from Marvisak/VIctory. Originally posted by AndyLatimer on 2026-11-27T02:30:48Z.
Review: CHANGES_REQUESTED
Tested
f799496locally againstorigin/main(63bcca4, clean merge) on Windows 11, NVIDIA GeForce RTX 3060 Ti, Rust 1.98.1 MSVC. Two bugs found and reproduced with synthetic tests:sync_rangesdrops committed 4 KiB OS pages inside partially uncommitted 64 KiB blocks (crates/victory-gpu/src/descriptor/host.rs):sync_rangesreads each span once perwatch::PAGE(64 KiB) viaread_into. If a 64 KiB chunk contains a committed 4 KiB OS page followed by an uncommitted 4 KiB page,ReadProcessMemoryfails for the entire 64 KiB read and skips mirroring valid descriptors on the committed 4 KiB page.f799496withsync_ranges_mirrors_committed_4k_page_beside_uncommitted_page(1 committed 4 KiB page + uncommitted remainder in a 64 KiB reservation):sync_rangesreturned0scanned slots (expected128) and left slot 2 unmirrored.4096) chunks only when the 64 KiBread_intofails preserves the normal 64 KiB fast path while mirroring committed 4 KiB pages.merge_rangesrecordspast_capon empty or inverted ranges (crates/victory-gpu/src/descriptor/host.rs):if last > capruns without checkingfirst < last, somerge_ranges(&[(70, 70), (80, 75)], 64)returns([], Some(74))instead of([], None)and triggers a spurious"title slot past the host heap"warning viaself.mirror(highest, ...).at(highest)suppresses that diagnostic if a mapped past-cap range ends in an unmapped tail page.)With the patch below applied on top of
f799496:sync_ranges_mirrors_committed_4k_page_beside_uncommitted_pageand themerge_rangesempty/inverted case) fail onf799496and pass with the patch.cargo test -p victory-gpu --lib --locked descriptor:: -- --skip dynamic_slots_are_held_until_released --test-threads=1: 24 passed, 0 failed (skipping only the pre-existing NVIDIA 1M heap-cap failure).cargo clippy -p victory-gpu --all-targets --locked -- -D warnings(default and--all-features) andrustfmt --edition 2024 --check: clean.Patch and regression tests against
f799496Synthetic tests only; AI-assisted review.
Imported from Marvisak/VIctory. Originally posted by MeMako on 2026-11-27T05:09:13Z.
Thanks for catching both edge cases and providing the repros! Pushed fixes in
63d630a:sync_ranges): Kept the 64 KiBwatch::PAGEfast path and added a 4 KiB (OS_PAGE)read_intofallback when a 64 KiB read fails, so committed 4 KiB OS pages next to uncommitted pages are still mirrored. Added yoursync_ranges_mirrors_committed_4k_page_beside_uncommitted_pageregression test.merge_ranges/past_cap): Guardedpast_capwithfirst < last && last > cap(added(70, 70), (80, 75)assertion tomerge_ranges_sorts_clamps_and_merges_adjacent_and_overlapping). Also added a fallback probe onfirst.max(cap)across past-cap spans whenat(highest)sits on an uncommitted tail page so mapped overflow still emits the past-cap warning.Verified with
cargo test -p victory-gpu --lib --locked -- --test-threads=1(234 passed, 0 failed, 1 ignored),cargo clippy --workspace --all-targets --locked -- -D warnings(default +--all-features),rustfmt --edition 2024 --checkon the modified ranges, andcargo run --locked -p xtask -- policy(191 files ok) on Win 11 / RX 9070 XT.Imported from Marvisak/VIctory. Originally posted by KainanP on 2026-11-27T12:31:13Z.
Contention numbers for the
SHADER_HEAPSwait in #3425, this PR (63d630a) against its base63bcca4:sync_heaps, RTX, 12 runsThe sync is no faster here, and the lock scope is unchanged, so title threads wait as long as before. For comparison, #3055 (same first commit
24618c9) was 7.6 ms on the same runs. No views were lost or stale. The fullvictory-gpusuite on RTX fails only the two tests thatmainalso fails here.Bench:
sync_contention_bench(#[ignore]d; commitf34bcfb8, cherry-picks onto any tree). A placed, write-watched view heap of 2^20 slots (the host heap caps it at 934,464 here). Each frame, one thread rewrites 200 random 64 KiB pages (50 changed records each) and runs onesync_heaps, while 5 title threads write a placed-buffer SRV every 20 µs into pages of their own. "Wait" is the title threads' time in view writes beyond the uncontended 2–3 µs, summed per frame. Release build, RTX 4060 Laptop, runs interleaved with the base, medians of 30 frames per run. The bench also checks that every view written before a sync is the slot's view address after it, and that every slot is right after a final quiet sync.AI use: Claude Code (Claude Opus 5.5).
Imported from Marvisak/VIctory. Originally posted by KainanP on 2026-11-27T13:06:22Z.
Follow-up to my contention numbers above, this time in the
sync_slotsshape #3425 reports (18.1 ms/frame for ~384k slots). It shows something the earlier run didn't.Bench:
sync_slots_benchonbench/sync-slots(f233390e, on top off34bcfb8). Each frame, 192 random 64 KiB pages (393,216 slots, the "384k slots" of #3425) of a 2^20-slot placed, write-watched view heap are written. 0, ~9,500 or ~85,000 records among them change, and onesync_heapsruns. Each shape runs without and with 5 title threads writing a view every 20 µs. It checks every changed slot's view address after each sync, and every slot at the end. RTX 4060 Laptop. Base63bcca4and the PRs ran interleaved (7 runs for the ~9.5k row, 3 for the others). Ratios are per-run against base. #3265, which doesn't touch the sync, gave ×0.81-1.04 in the same runs, so read anything within ~±15% as noise.sync_heapsWhen the pages are written but no record changed (the title copying the same tables in again), the sync takes ~1.8× as long as on base: 2.9 → 4.9 ms for 393k slots. With a realistic ~9,500 changed records it's even. Only with ~85,000 changed per frame is it ahead, and only partly beyond noise. My guess is the up-front
read_intoof the whole merged ranges, which copies every record once more before the diff, but I haven't profiled it. 0 lost and 0 stale slots in every run.For comparison, #3055 (which contains this PR's first commit) is ×0.63-0.82 in all six rows.
AI use: Claude Code (Claude Opus 5.5).
Imported from Marvisak/VIctory. Originally posted by passerbyyhx on 2026-11-29T16:22:18Z.
Ran
sync_ranges_merges_overlapping_and_out_of_order_rangesandsync_ranges_mirrors_committed_4k_page_beside_uncommitted_pageat63d630a0124a069d57b5d580fa7f054783b3ccdfon RTX 4090 Laptop (10de:2757) and WARP (1414:008c). Both tests passed on each adapter. Test-only instrumentation verified the D3D12 device LUID/vendor and required heap creation so an unavailable heap could not yield a passing early return. Scope is descriptor mirror correctness for these two cases; no frame-time or contention measurements.View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.