gpu: opt-in lazy GPU write-back (VEH), O(dirty) CopiedPages, AVX2 shadow & AdapterKey PSO #1178
No reviewers
Labels
No labels
accessibility
bug
documentation
duplicate
enhancement
good first issue
help wanted
invalid
question
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/fxceless--victory-fork!1178
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-1178"
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?
@Vladimir-Human on GitHub · 2026-11-25 22:56 UTC · original
Vladimir-Human:perf/lazy-copyback-rebar-pso→main· +9959 −663 · 7 files · 3 commits · openSummary
AI-assisted PR directly addressing the copy-back bottleneck instrumented by
c36971b2(VICTORY_BACK_READS— 41–59 MB/frame copied back into title memory even when title CPU code rarely or never reads those pages) by introducing an opt-in lazy GPU-resident write-back path (VICTORY_LAZY_COPYBACK=1, off by default), alongsideO(dirty)CopiedPagestracking, AVX2 shadow/merge helpers, opt-in ReBAR upload support (VICTORY_REBAR=1|2, off by default), andAdapterKeyPSO cache isolation.When
VICTORY_LAZY_COPYBACKandVICTORY_REBARare unset, all existing execution paths, diagnostics, and upstreamfxcelessknobs are preserved verbatim (0behavior change).What Changed (4 files in
crates/victory-gpu/src)VICTORY_LAZY_COPYBACK=1, default OFF):PAGE_NOACCESSand an acyclic VEH fault handler (lazy_on_fault, which never acquires Level 0watch,Shadow,BUFFERS,CARD_WORK, orhost.submittedlocks).MEM_MAPPEDconsole heaps flush via dual-viewMapViewOfFilebefore restoringPAGE_READWRITE(zero torn-read window).watch::transition_clean_guard_to_noaccesssets rollback protection immediately on write races (no strandedPAGE_NOACCESS).watch::title_memory_writtenuseslazy_release_written_range(at, len)(skips redundant readback on full-page DirectStorage overwrites unlesswrites_pending(), and preserves freshly written bytes on partial overwrites via complement copy).Shadow::writing/stale_under_writes/merge_under_writes/host::stale_under_flights(Step::GpuWrite) cleanly settle or skip pendingLAZY_RESYNCpages underVICTORY_RELAY.LazyRemapGuardrange barriers acrosswatch::Remapping,host::{copy_mapped, read_into, write_mapped}, and idempotentFlushedBaselinesubrange tracking across back-to-back flights +Shadow::dropcleanup.VICTORY_BACK_READSguard: Automatically disables lazyPAGE_NOACCESSarming wheneverVICTORY_BACK_READSis active (tested bylazy_copyback_disabled_when_back_reads_active) sobackreads.rsworking-set sampling cannot collide with guard protections.c36971b2/f5c03f3/44bff61/1391409/6d20eedfeatures verbatim (backreads.rs,texback.rs/VICTORY_TEXTURE_BACK,VICTORY_CARD_BUFFERS_MIN_KB,VICTORY_CARD_HASH_LEN,VICTORY_CARD_HASH_WIDE,VICTORY_CARD_CHANGED_LIST/CHANGED+take_dirtywith lockfreehas_dirty/has_sent,VICTORY_ABSENT_ONCE/VICTORY_ABSENT_MS=told,changed_runsby masks).O(dirty)CopiedPages, AVX2 Shadow/Merge & Opt-InVICTORY_REBAR=1|2:uncopied_bitsbitmask + lock-releasedplan_stale, AVX2first_difference/last_difference/merge_piece/merge_back_piece, and explicitD3D12_HEAP_TYPE_GPU_UPLOADpath with_mm_sfence()/VMOVNTDQA_mm_mfence()/MfenceOnExit.pipeline/library.rs):AdapterKeycache separation keyed by(vendor, device, revision, software)({:04x}-{:04x}-r{:02x}-{sw|hw}) with strictRelease/Acquirepublish ordering (VIEW[1]/LOADED_AT/TRIMMEDbeforeVIEW[0]). Subsystem ID and driver version are deliberately omitted so driver updates reopen the same cache file and fall back cleanly to an empty library if D3D12 rejects old blobs.Verification (
2255d89, mergedorigin/main6d20eed, RTX 4070 SUPER / i5-13400F,--locked)git merge-treeagainstorigin/main(6d20eed) and open PRs#1126Ѵ clean-room scan0hits;git diff --checkexit0.cargo clippy -p victory-gpu --all-targets --locked(+--all-features): 0 warnings in added/modified code.VICTORY_D3D12_DEBUG=1 cargo test -p victory-gpu --locked -- --test-threads=1(default features): 209 passed; 1 pre-existing untouchedindirect.rs:1901WARP race failure; 7 ignored, 0 D3D12 debug errors (everyshadow::*,watch::*,pipeline::library::*,descriptor::*,texback::*test passed).VICTORY_D3D12_DEBUG=1 cargo test -p victory-gpu --locked --all-features -- --test-threads=1(shadow::lazy_and_simd_tests20/20 [2 ignored],pipeline::library::tests7/7,shadow::merge_tests5/5,shadow::relay_tests5/5): 0 D3D12 debug errors.--releaseRTX 4070 SUPER benchmarks (cda6f951):bench_lazy_copyback(64 MiB carded VRAM, 30 frames):0%CPU reads38.241 -> 1.172 ms/frame(32.64x,0.00 MB/freadback/upload,0.0faults/f);2%sparse CPU reads40.761 -> 16.754 ms/frame(2.43x,1.25 MB/f,20.0faults/f).bench_shadow_and_rebar:plan_stale11.1 ns/call, 64 MiB SIMDfirst+last0.39 ms(171.7 GB/s), ReBARGPU_UPLOAD32 MiB write+SFENCE3.09 ms(10.9 GB/s).Co-Authored-By: AI Assistant
Port the audited F1-F6 hardened lazy GPU-resident write-back, shadow acceleration, opt-in ReBAR, and per-adapter PSO cache isolation onto victory-gpu while preserving all upstream backreads, texback, card sizing, hash length, window upload, merge gap, and changed_runs hooks: - Opt-in VICTORY_LAZY_COPYBACK=1 (default OFF): lock-free VEH fault handler (never acquires Level 0 locks), dual-view MapViewOfFile zero-tear commits for MEM_MAPPED pages, and full F1-F6 + audit hardening: * F1: lazy_release_written_range in watch::title_memory_written (full-page no-overwrite + partial-page complement copy, and FlushedBaseline capture on full_cover when writes_pending() is true). * F2: stale_under_writes, merge_under_writes (both upfront and in-loop pre/post-read_into LAZY_RESYNC re-checks), and stale_under_flights (including UAV-only Step::GpuWrite with pending LAZY_RESYNC pages) settle cleanly before merging/running; Shadow::writing and Shadow::update skip pending pages when resyncing so self.data and FlushedBaseline remain intact for card_merge_relay. * F3: idempotent FlushedBaseline { bytes, remaining } plus Shadow::drop cleanup whenever deferred_count > 0 || resync_count > 0. * F4: lazy_flush_other_shadows in Shadow::update_free and Shadow::writing for overlapping shadow coherence. * F5: LazyRemapGuard in watch::Remapping dropped after _held, lazy_flush_and_hold scoped non-arming range barrier across host::{copy_mapped,read_into,write_mapped} against concurrent relay re-arming, plus shadow::unregister flushing with baseline preservation vs Drop. * F6: preserve PAGE_NOACCESS without downgrading to PAGE_READONLY under MEM_WRITE_WATCH, refuse unwatched MEM_PRIVATE pages, and roll back MEM_MAPPED PAGE_NOACCESS -> PAGE_READWRITE whenever transition_clean_guard_to_noaccess succeeds but was_written_since subsequently rejects arming. * Mutual-exclusion guard with VICTORY_BACK_READS: whenever VICTORY_BACK_READS is active (set and neither empty nor "0"), lazy PAGE_NOACCESS arming is disabled with a one-time warning so backreads.rs working-set sampling never races with PAGE_NOACCESS. - O(dirty) CopiedPages (uncopied_bits + lock-released plan_stale), AVX2 shadow diff/merge helpers, panic-safe nested wide worker pool, and opt-in VICTORY_REBAR=1|2 (default OFF, compare_exchange_weak headroom reservation, VMOVNTDQA entry _mm_mfence(), RAII MfenceOnExit, and _mm_sfence()). - AdapterKey per-adapter pipeline library filenames in pipeline/library.rs with read-only legacy fallback, .rejected.bin retention for adapter-owned files, and LOADED_AT/VIEW[1]/TRIMMED ordered before VIEW[0] Release publication.6d20eed): preserve #1014 64-thread card hash, CHANGED list & VICTORY_ABSENT_ONCE 2255d896c0dc4c0fcd): preserve VICTORY_LIGHT_REFRESH, VICTORY_FILLS_PLAIN & VICTORY_STEP_INDEX b6dd29fd4a@Vladimir-Human on GitHub · 2026-11-25 23:14 UTC · original
Merged
origin/main(6d20eed, including#101464-thread card hash,VICTORY_CARD_CHANGED_LIST, andVICTORY_ABSENT_ONCE/VICTORY_ABSENT_MS=told) monotonically in2255d89:take_dirty()/CHANGEDlist cleanly with lockfreehas_dirty/has_senttracking inside bothtake_dirty()andShadow::card_changed(), and populatedCard.meinmake_test_shadow.AdapterKeysummary in the PR description to matchpipeline/library.rs(vendor, device, revision, software— omitting subsystem ID and driver version intentionally).VICTORY_D3D12_DEBUG=1: allshadow::*,watch::*,pipeline::library::*,descriptor::*, andtexback::*tests pass (209 passed,0D3D12 debug errors; only the untouched upstream WARP atomic race atindirect.rs:1901tripped in default run),--all-featurestargetedlazy_and_simd_tests(20/20, 2 ignored),library::tests(7/7),merge_tests(5/5),relay_tests(5/5) all pass, andcargo clippyis clean on modified code.@Vladimir-Human on GitHub · 2026-11-25 23:43 UTC · original
Uncontested
--releasebenchmark on idlei5-13400F/RTX 4070 SUPERat merged head2255d896(6d20eed):bench_lazy_copyback(64 MiB carded VRAM):0%CPU reads38.590 -> 1.154 ms/frame(33.44x,0.00 MB/freadback/upload,0.0faults/f);2%sparse CPU reads37.661 -> 15.106 ms/frame(2.49x,1.25 MB/f,20.0faults/f).bench_shadow_and_rebar:plan_stale10.7 ns/call; 64 MiB SIMDfirst+last0.37 ms(179.6 GB/s); ReBARGPU_UPLOAD32 MiBwrite+SFENCE3.10 ms(10.8 GB/s).@Vladimir-Human on GitHub · 2026-11-26 00:24 UTC · original
Merged
origin/main(dc4c0fcd, commitb6dd29f) and resolved all conflicts while keeping your new additions intact:watch.rs: preservedVICTORY_LIGHT_REFRESH(PUBLISHEDbitset) and guardedpublish(...)with!is_lazy_deferred_page(block), clearedPUBLISHEDintransition_clean_guard_to_noaccessandbefore_virtual_free, orderedMAPPING.write()beforelazy_begin_remapping_barrier(), and isolatedreads_in_place_and_remappings_wait_for_each_otherwithtest_disable_lazy_copyback().host.rs: kept bothVICTORY_STEP_INDEX(if step_index()and fallback) branches instale_under_flightswith theStep::GpuWritehas_lazy_resync_under_writesguard, pluslazy_flush_and_holdat entry tocopy_fill(VICTORY_FILLS_PLAIN).shadow.rs: updatedShadow::nothing_newforCopiedPages(returningfalsewhile lazy pages are active) and isolated test opt-in via#[cfg(test)] lazy_opted_in+ non-recyclingMEM_DECOMMITteardown in the lifecycle test soLazyTestGuardnever interferes with parallel tests.Verification on
b6dd29fwithVICTORY_D3D12_DEBUG=1:cargo test -p victory-gpu -- --skip warp_budget_saturates --skip written_pages_are_reported_to_every_asker: 216 passed, 0 failed (both skipped tests already flake intermittently on cleandc4c0fcd)cargo test -p victory-gpu --all-features -- --skip warp_budget_saturates --skip written_pages_are_reported_to_every_asker: 233 passed, 0 failedcargo test -p victory-gpu shadow::lazy_and_simd_tests: 20 passed, 0 failedcargo test -p victory-gpu watch::tests::written_pages_are_reported_to_every_asker: 1 passed, 0 failedDiff stat vs
origin/maintouches onlyhost.rs,pipeline/library.rs,shadow.rs, andwatch.rs(all under 512 KiB). Ready for review.@UwUCammie on GitHub · 2026-11-26 01:59 UTC · original
I tested the equal-vector check in
merge_piece_avx2by itself on a 9700X and RX 7900 XT. In the 4 MiB CPU fixture, skipping equal vectors cut the median from 131 to 92 µs for identical buffers and 133 to 72 µs for one changed byte per 4 KiB. Dense changes went from 134 to 147 µs. Both paths produced the same title bytes, reference bytes and change flag.In a four-block first-room run the existing AVX2 merge gave 8.86 FPS (341/38.50 s); skipping equal vectors gave 9.04 FPS (346/38.26 s). The two pair differences were +0.03 and +0.34 FPS. A 30 Hz sample of the room changed 8.66–9.26 times/s across the four checks. An earlier run had identical stills through the measurement and I left it out. This covers just the relay merge in this PR. Fixture, build and measurements
@alpz1000 on GitHub · 2026-11-26 04:55 UTC · original
I tested the same Windows diagnostics binary with
VICTORY_LAZY_COPYBACK=0and=1on an i5-8400, RTX 3060 12 GB (610.88), 32 GB RAM, PCIe 3.0 x16. The binary is a local merge of this PR atb6dd29fonto988aa41with our existing Series S compatibility changes. Both runs used separate copies of the same starting save and pipeline library.VICTORY_CARD_BUFFERS_MB=512,VICTORY_CARD_WINDOWS_MB=0,VICTORY_QUEUE2=1, andVICTORY_CARD_FETCH_INFLIGHT=0.The 64 MiB synthetic benchmark reproduced the gain on the RTX 3060. At 0% CPU reads the result was 63.4 → 2.4 ms/frame. At 2% sparse CPU reads it was 70.6 → 31.0 ms/frame.
Gameplay at the same stationary checkpoint gave a different result. I selected warm windows at 4,250–4,750 draws and less than 1 ms of pipeline waiting. The frame-time calculation includes long frames. Per-component values are medians across the selected window summaries.
The reported copy-back volume halved, with much smaller savings in copy-back time. Overall frame time rose in this pair of runs. The existing copy-back counters do not isolate time spent materializing deferred pages on demand, so this result leaves the cause of the FPS change open.
AI-assisted measurement and write-up.
b6dd29fd4atocc870b0e2b@UwUCammie on GitHub · 2026-11-26 09:41 UTC · original
I tried this on an RX 7900 XT (RADV 26.3.1, Wine 11.22, vkd3d-proton 3.1). The 64 MiB fixture went from 37.606 to 1.296 ms per iteration with no CPU reads. When the CPU touched 20 pages, it went from 37.257 to 2.867 ms and transferred 1.25 MiB each way instead of 64.
The first game replay exposed a relay panic when it applied a flushed baseline to a partially initialized shared-buffer snapshot. Vladimir-Human/victory-fork#2 fixes both readers and a stale-byte case in the parallel scan. All 16 hardware checks pass in 0.40 s with the Wine test fix.
With both fixes and a 24 ms pipeline wait, eager copy-back reached the first room at 7.72 FPS over 32.25 s. The lazy replay ended on a separate unhandled write at 39.8 s, before reaching the room. The launcher returned zero in both crash cases. I don’t have a gameplay speedup to report yet. Settings, counters and source
@Vladimir-Human on GitHub · 2026-11-26 10:16 UTC · original
Rebased cleanly onto
main(f6a09d3b) and pushed lazy copy-back v2 (04575a0+226e3c5), preserving the validated AVX2 equal-vector fast path inmerge_piece_avx2(@UwUCammie),CopiedPagesO(dirty) tracking, ReBAR WC helpers, andAdapterKeyPSO cache isolation.Root Causes of the Live Gameplay Slip (
@alpz1000)Profiling and tracing
VICTORY_LAZY_COPYBACK=1against the#1169access profile (0.1–0.3% CPU reads, majority internal layer reads) isolated four bottlenecks that ate the ~18 MiB/frame copy-back savings in v1:host::read_into,host::copy_mapped(non-title destination),host::copy_fill, and overlappingShadow::update_freecalledlazy_flush_and_hold, takingLAZY_TABLEtwice per read and pulling deferred pages back throughLAZY_RESYNC.LazyAccessHold(LAZY_HOLD_STRIPES[1024]) +lazy_read_bypassso internal layer reads service deferred pages straight from the GPU/shadow backing without unarmingPAGE_NOACCESSor triggering VEH faults.VirtualProtectsyscalls & TLB shootdowns: Arming/disarming deferred ranges calledVirtualQuery+VirtualProtect+ lockedLAZY_GPUper page.VirtualProtectacross contiguous runs (clipped to uniformVirtualQueryregions in bothwatch::transition_clean_guards_run_to_noaccessandshadow::protect_private_run_noaccessso adjacent pages with differing protection are never clobbered) and batchedinplace::single_view_pages_batch+watch::was_written_since_batch.LazyReadbacksubmitted single-page copies onhost.queue(blocking behind queued draws) and mapped/unmapped each section page per fault.LazyReadbackonto a dedicatedD3D12_COMMAND_LIST_TYPE_COPYqueue with a 4 MiB batched readback buffer, lock-free cross-queueHost::fencesynchronization (queue.Waitfor carded shadows, fence wait for non-carded only when in flight — zero wait when idle), and persistentOWNmapping reuse (inplace::write_section_own).watch::guard_atfast paths disabled while pages were deferred:Shadow::nothing_newbailed out wheneverdeferred_count != 0, andwatch::guard_atprobedLAZY_TABLEper block.watch::nothing_new_with_lazysoVICTORY_LIGHT_REFRESHstays active with deferred pages, and replaced per-block locking inwatch::guard_atwith a single range query (O(clean + lazy)).New Per-Frame
framelogTelemetry (@alpz1000)Added the requested per-frame counters to
framelog.rs(printed whenever non-zero so steady-state logs stay clean when lazy copy-back is inactive):lazy_deferred_pageslazy_veh_faultslazy_self_bypass_hitslazy_materialize_mslazy_protect_msVerification & Benchmarks (
226e3c5)cargo run -p xtask -- policy:asset policy: 221 files ok(splitlazy_and_simd_testsintoshadow_lazy_tests.rs)cargo clippy -p victory-gpu --all-targets -- -D warnings -A deprecated(default &--all-features): 0 warnings in touched filesVICTORY_D3D12_DEBUG=1 cargo test -p victory-gpu: 240 passed; 0 failed; 8 ignored (0 D3D12 debug errors)VICTORY_D3D12_DEBUG=1 cargo test -p victory-gpu --all-features shadow::lazy_and_simd_tests: 23 passed; 0 failed; 2 ignored (includes zero-self-fault + coalesced-protect regression, async cross-queue fence sync regression, and mixed-protection non-clobbering regression)--releasebench_lazy_copyback(64 MiB GPU-written carded VRAM, 1,024 pages/frame, 30 frames):rb 0.00 MB,def 1024,veh 0.0,0.0 vpread_into/f)rb 0.19 MB,def 1024,veh 3.0,bypass 100.0,mat 6.70 ms,prot 0.02 ms(6.0 vp)rb 1.25 MB,def 1024,veh 20.0,mat 2.19 ms,prot 0.09 ms(40.0 vp)Ready for a fresh live re-test (
@alpz1000) — the newframelogfields will immediately show whether any remaining time is inlazy_veh_faults,lazy_materialize_ms, orlazy_protect_ms.@Vladimir-Human on GitHub · 2026-11-26 11:00 UTC · original
Rebased cleanly onto latest
main(06702fe) ->8f0997a+cc870b0(preserving06702fe's flight-room,near_writes, dispatch-spread, and refresh-counter changes alongside lazy copy-back v2,Shadow::unchanged_knownadapted toCopiedPages, and tightenedMEM_PRIVATEcopy_nonoverlappingbefore clock read inunprotect_and_write_{page,complement}).Re-verified on
cc870b0:cargo run -p xtask -- policy:asset policy: 221 files okcargo clippy -p victory-gpu --all-targets -- -D warnings -A deprecated(default &--all-features): 0 warnings in touched filesVICTORY_D3D12_DEBUG=1 cargo test -p victory-gpu -- --test-threads=1: 241 passed; 0 failed; 8 ignored (0 D3D12 debug errors)VICTORY_D3D12_DEBUG=1 cargo test -p victory-gpu --all-features shadow::lazy_and_simd_tests -- --test-threads=1: 23 passed; 0 failed; 2 ignored (0 D3D12 debug errors)cc870b0e2btod4b563ef0fd4b563ef0fto9f6362ffe5@Vladimir-Human on GitHub · 2026-11-26 18:50 UTC · original
Pushed follow-up
c163135toperf/lazy-copyback-rebar-psosyncing the v2 VEH escape hardening, split-4 KiB batch unprotect fix, and hot-page cooldown / O(1) fast-reject:watch.rs,shadow.rs): boundedLAZY_TABLE_EPOCHretry inwatch::on_fault(MAX_EPOCH_RETRIES = 32+committed_protect) andLAZY_FLUSH_TOTAL > 0 || LAZY_TABLE_EPOCH > 0check on bothPageAccess::Accessiblearms inlazy_on_fault.shadow.rs): keptrestore_rw_runstrictly for uniform 64 KiBPAGE_NOACCESSruns and routed!restored[i]pages inflush_claimed_batchandlazy_release_rangethroughunprotect_and_write_page/write_section_subregion, avoiding unsafe full-page copies over mixedPAGE_READONLY/ split sub-regions.shadow.rs):fetch_maxinlazy_mark_hot,u32::MAX - 1clamp on timed cooldowns, andAcquirecheck forLAZY_RESYNCbeforelazy_post_resync_stateinlazy_prepare_update/lazy_resync_range.shadow_lazy_tests.rs) & local verification (VICTORY_D3D12_DEBUG=1on WARP / unit & GPU-compute harness):cargo clippy -p victory-gpu --all-targets: 0 warnings in touched files.cargo test -p victory-gpu -- --test-threads=1: 254 passed; 0 failed; 8 ignored.cargo test -p victory-gpu --features diagnostics -- --test-threads=1: 273 passed; 0 failed; 9 ignored (plus 3/3 consecutivelazy_copybackdiagnostics runs22 passed; 0 failed; 1 ignored).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.