gpu: lock-free refresh checks, single-lock scoped pool, and zero-clone card_dirty #1094
No reviewers
Labels
No labels
AMD
audio
bug
confirmed
crash
cutscene
dlss
documentation
duplicate
enhancement
fixed-on-main
frame-generation
good first issue
help wanted
input
INTEL
invalid
lighting
linux-proton
memory
needs-info
needs-logs
needs-rebase
NVIDIA
performance
pr-diagnostics
pr-docs
pr-feature
pr-fix
pr-performance
pr-refactor
pr-tests
question
RAYTRACING
rendering
report
series-s
shaders
spam
startup
upstream
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/trustno1-coder--VIctory-NVIDIA!1094
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-1094"
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?
@Bazovsky on GitHub · 2026-11-28 13:11 UTC · original
Bazovsky:pr/lockfree-refresh-pool→main· +764 −154 · 6 files · 3 commits · closed without mergingWhat is now true
Eliminates lock contention, per-flush heap allocations, and redundant range cloning on the
victory-submitcritical path (no new user switches; preserves all existingVICTORY_*behavior):watch.rs:PageEpochstable (WRITTEN_EPOCHS, 128 TiB coverage, specialized single-page fast path, plainReleasestore under the exclusiveJOURNALwrite lock) mirroringJournal::written.is_kept()(mirroringJournal::kept), reusableahead_snapshot_into(&mut Vec<_>), and zero-locknothing_new_with/ zero-allocnothing_new_single.shadow.rs:Shadow::copied: Mutex<Vec<u64>>andranged: Mutex<[(usize, usize, u64); 2]>withcopy_lock: Mutex<()>+copied: Box<[AtomicU64]>+ SeqLockranged+pending_len: AtomicUsize— shrinkingShadowwhile makingShadow::nothing_new_withcompletely lock-free on the common (no pending shader writes) path.wide_each_scopedsharingWorkers::queue(0 heap allocations vs ~21 inwide_each, 0 exit locks for non-last helpers, safe inline fallback if nested).Mutex<Done>allocations inShadow::merge_under_writeswith unique-indexSlots.Arc<Vec<(usize, usize)>>inSentRunsand returns it fromcard_dirty(), avoiding cloning tens of thousands of dirty ranges per submission.host.rs,host/send.rs,host/upcheck.rs:rangesand lockingJOURNALinask_ahead/ask_ahead_donewhenwatch::is_kept()(VICTORY_ASK_ONCE=1) is already true.Batch::ahead_snapacross flushes, dispatchesrefresh_front/flush_all/refresh_ahead/fill/refresh_texturesviawide_each_scoped(grain1after no-op filtering, grain8for large mixed flushes), and batchesFLUSHES[2]atomic updates once per chunk instead of once per no-op.land.rs:state.lock()inland::Poolwith a lock-freeAtomicUsizework counter (1 lock on batch entry/exit instead of 2 locks per item).Relation to open PRs
Complements #126 (
VICTORY_WIDE_CHUNK): rather than adding a chunk-size knob on top of the allocatingwide_each+ lockednothing_new, this removes the locks innothing_new(JOURNAL,Shadow::pending/copied/ranged), removes per-flush heap allocations inWorkers, and removes thecard_dirtyrange clone and per-itemland::Poollocking.Does not change
watch::writesor theguardslock contention tracked in #795: this PR takes locks off unchanged-rangenothing_newchecks, theWorkers/land::Pooldispatch loops, andcard_dirtycloning, while guarded ranges that missnothing_newstill go throughwatch::writes.Measured on
x86-64-v3fat-LTO build, identical 90 s intro sequence (VICTORY_KEYS=10:Enter,13:Enter), steady 3D seconds in DLSS frames 100..1800 (<80 ms).A/B with stable V-Cache placement (eliminating dual-CCD migration noise) —
MEASUREDvictory-submitrefreshes/stepsOn pure
main(63b902f) + PR 1 (post-warmup matched heavy street scene, ~3,300 draws):refreshesdropped from7.25 ms → 6.40 ms(−11.7%) andstepsfrom10.95 ms → 10.10 ms, with indoor shots reaching16.1 ms(62 fps,refreshes = 4.5 ms).CI / Tests
cargo run --locked -p xtask -- policy:294 files okcargo xwin clippy --locked -p victory-gpu --all-targets -- -D warnings: 0 warnings (and 0 warnings in touched files under--all-features)victory-gpu(455 passed, 0 failed, including new unit testswatch::parts_tests::page_epochs_checks_single_and_multi_page_rangesandshadow::wide_tests::wide_each_scoped_visits_every_index_once_and_handles_nesting),victory-hle(188 passed, 0 failed)@jptorres96 on GitHub · 2026-11-28 13:38 UTC · original
Ran this on Windows at
befdec4(base63b902f), since CI does not run on fork PRs until approved. Ryzen 5 5600X, RTX 4080 SUPER, Windows build 26300, rustc 1.98.1.cargo test --locked -p victory-gpu --lib -- --test-threads=1: 455 passed, 0 failed, 37 ignored, including the newpage_epochs_checks_single_and_multi_page_ranges.cargo clippy -p victory-gpu --all-targets [--all-features] -- -D warnings: clean in both builds once the pre-existingmanual_is_multiple_ofatdescriptor.rs:1234is allowed. The workspace-wide run stops on errors that are already onmain(emit/mod.rs:2768,gameinput.rs:1372), none in files this PR touches.Read through the lock-free parts. I found nothing wrong in:
PageEpochsagainstJournal::written:noteis the only writer ofwrittenand nothing removes from it, so the mirror stays complete.ranged != 0 || all takencheck followed by thewrittenscan;pending_len, which is stored underpending's lock at all three mutation sites;land::Pool's shared counter.runningstill fences one batch from the next, and theidlewakeup can't be lost in either order.One nit, in the
rangedSeqLock writer (shadow.rs~4693).seq + 1is stored withReleaseand then the slots withRelaxed.Releaseorders what comes before the store, so the slot stores may move ahead of the odd sequence number. The usual form isstore(seq + 1, Relaxed); fence(Release);before the slot stores. On x86 the hardware keeps stores in order, so this only matters if the compiler reorders them, but it costs nothing.On #795. I ran the synthetic probe from there (
probe-795, cherry-picked on top of this PR, diagnostics build). It timeswatch::writesper range, which this PR doesn't change, and the numbers matchmain:mainThis PR comes out about 14% higher, a little above the ~10% spread between runs on
main. From a single run I wouldn't call that a regression. So this PR takes locks off thenothing_newchecks and the pools. The contention in #795 is in asking guarded ranges, and it is still there. That isn't a flaw in the PR, but it may be worth saying in the description, since the two read alike.Synthetic only: no game files.
@Bazovsky on GitHub · 2026-11-28 14:48 UTC · original
Thanks for testing this on Windows and auditing the lock-free paths, @jptorres96!
4acfbbbswitching the SeqLock writer inShadow::copy_stale(shadow.rs) toself.ranged_seq.store(seq + 1, Ordering::Relaxed); std::sync::atomic::fence(Ordering::Release);before the slot stores, matching the standard writer-side barrier.watch::writesor theguardslock contention tracked in #795.@POMXARK on GitHub · 2026-11-28 14:58 UTC · original
Tested this PR in a 20-minute 1440p DLSS Quality + MFG 4x A/B run on Ryzen 7 5700X (8C/16T) + RTX 5080 (16 GB) + 32 GB RAM (
VICTORY_WAIT_RESIDENT=0,VICTORY_RELAY=2,VICTORY_CARD_STEPS=2,VICTORY_THIN=1,VICTORY_JOIN_COPIES=1,VICTORY_JOIN_PARTS=8,VICTORY_LAND_SKIP=1).Integration Notes
watch.rs3-levelPageEpochs,shadow.rsSeqLockranged+ zero-allocwide_each_scoped+Slots<Done>+Arccard_dirty,land.rslock-freePool,host.rs/send.rs/upcheck.rs).O(log n)binary search on sortedaheadranges insidenothing_new_with/nothing_new_single.self.copied[idx].store(now, Ordering::Release)afterself.take_all(runs)completes inShadow::copy_stale(rather than beforetake_all) so a concurrent lock-free reader cannot observenowbefore the copy bytes land.Unit Tests & Stability
cargo test -p victory-gpu --lib -- watch:: shadow:: land:: host:: --test-threads=4(WARP): 219/219 PASS (3.17 s), includingpage_epochs_checks_single_and_multi_page_rangesandwide_each_scoped_visits_every_index_once_and_handles_nesting.DeviceRemoved/DEVICE_HUNG, 0 guest exceptions, 0 bake stalls, 0GPU>=50ms, 0F>=500ms, visually clean output throughout.20-Minute A/B Results (vs prior lock-free
JournalRead+wide_chunks(32)baseline)ALL 3DFPS (p50 / mean)ALL 3DPrep /copies(p50)submitting preprefreshes(p50 / p90)submitting prepsteps(p50)1s frame_times(med / p95 / p99)1k–4kdraws/frame (p50 /copies)4k–7kdraws/frame (p50 /copies)7k–10kdraws/frame (p50 /copies)>=10kdraws/frame (p50 / mean)Takeaway: Clear, measurable win even on top of an already lock-free
copied+JournalReadbaseline — eliminating the per-chunkJOURNALread lock,BTreeMaplookups, andwide()heap allocations cutrefreshesby 4.9 ms (-21.7%) and pushedALL 3Dmedian from13.9to14.7 FPS. Suggest movingself.copied[...].store(now, Release)afterself.take_all(runs)incopy_stalefor strict lock-free reader ordering.@KruIN689 on GitHub · 2026-11-28 16:43 UTC · original
In-game comparison, as #1138 asked ("not yet compared in the game").
Setup:
63b902f, and of this PR's head (4acfbbb, on63b902f).VICTORY_KEYS_FILE), then stands still for 4 minutes.63b902f#163b902f#263b902f#3No difference I can measure in the game. Run-to-run spread is about ±3 fps, even standing at the same spot: traffic and pedestrians change the bytes copied a frame (51–71 MB). So any effect of the size the synthetic benchmark found (−9 to −11% of no-op refresh time, about 1 ms here) is inside the noise. The refresh time on the submitting thread overlaps between the two builds.
No errors, no device removal, no hangs in the three runs with this PR.
Not tested: walking or driving (more refresh work per frame), other CPUs, and the other PRs on this path.
AI use: Claude Code (Claude Opus 5.5) built both, ran and scripted the sessions, read the logs, and drafted this comment. I read it before posting.
@hasekenmustafa-ctrl on GitHub · 2026-11-28 18:35 UTC · original
I ported this onto a downstream branch based on
63b902fand looked at the ordering point POMXARK raised. The head (4acfbbb) still stores the stamp before the copy, and I think that is a real race.The race, in
Shadow::copy_stale:self.copied[page - base].store(now, Ordering::Release)happens inside the page walk, beforeself.take_all(runs)copies that page.nothing_new_with/nothing_new_singlenow readcopiedwithoutcopy_lock.copiedmutex, andcopy_staleheld it throughtake_all.Fix: collect the pages to stamp during the walk, and store them after
take_allreturns.take_all's helpers are joined throughwide's mutex, so their writes happen-before the Release store.That is the only store of a
nowstamp ahead of its bytes that I found.merge_under_writesand the publish path store after their bytes.Measured in game, walking. Setup:
play-nvidia.ps1defaults: Series X, 1440p, DLSS Quality, frame generation off.VICTORY_KEYS_FILEdrives the same 240 s walk after a 30 s settle.On this CPU the saving doesn't reach the frame. That fits KruIN689's standing runs on a 9950X3D and POMXARK's larger gain on a 5700X with ~58 ms preparing. There were 0 crashes and 0 device removals in about an hour with the change.
AI use: Claude Code (Claude Opus 5.5) did the port, the review of the ordering and the fix, drove and measured the runs, and wrote this comment.
@Bazovsky on GitHub · 2026-11-28 18:39 UTC · original
Thanks @POMXARK, @hasekenmustafa-ctrl, and @KruIN689 for auditing the ordering and running in-game A/B tests across different CPUs!
Fix pushed (
be4e568)self.copied[i].store(now, Ordering::Release)inShadow::copy_stale(shadow.rs) until afterself.take_all(runs)returns, collecting whole-page indices instamp: Vec<usize>during the walk. Becausetake_all'swide_eachjoins throughworkers.queue's mutex before returning, all worker writes happen-before theReleasestore, which synchronizes with lock-freeAcquireloads innothing_new_with/nothing_new_single.self.copiedwriters (merge_under_writesandlanded) — both already publish after bytes are in place.be4e568:cargo run --locked -p xtask -- policy:294 files okcargo xwin clippy --locked -p victory-gpu --all-targets(default &--all-features): 0 warnings (with-A clippy::manual-is-multiple-of)victory-gpu --lib): 455 passed, 0 failedExtended measurements & composability (Ryzen 9 9950X3D + RTX 5090, 1440p SDR DLSS Quality, FG OFF)
All runs below use identical 90 s warm-cache intro sequences (
VICTORY_KEYS=10:Enter,13:Enter), steady 3D seconds in DLSS frames100..1800(<80 ms), with CCD0 V-Cache placement from #1093 active to eliminate cross-CCD jitter:Submit thrPrep totalref/stepsThin transCPU-summax DLSS(90 s)main(63b902f,CACHE_CORES=0)P2d_DEBLOAT)P2d_ZNVER5)ahead+ 64-stripemerging+ AVX2word_runs+ L0 write-backHostList::scratch)Across all independent measurements so far, the
refreshesCPU saving is consistent and scales with how CPU-bound the submission thread is:refreshes22.6 → 17.7 ms (−21.7%),ALL 3Dp50+5.8%,>=10kdraws+52.5%refreshes8.32 → 7.43 ms (−11%),copies10.1 → 9.0 ms,preparing21.6 → 20.9 msrefreshes7.80 → 6.80 ms (−12.8%),Prep25.00 → 22.70 ms, frame median25.90 → 24.20 ms (+7.0%)refreshesmean11.9 → 11.4 ms, within ±3 fps traffic/pedestrian spread0 crashes and 0 device removals across 15+ full runs with #1094 active.
github-bot referenced this pull request2026-11-28 18:45:43 +00:00
@Rafa7046 on GitHub · 2026-11-28 19:22 UTC · original
Measured on a scripted run, RT off,
mainate7d8150with only this PR merged.Setup: Ryzen 9 9950X3D, RTX 5080, Series X, 1440p, DLSS Performance, frame generation off. The script plays the prologue cutscenes, then stands one minute on Jason's boat. Four sessions of plain
mainran the same afternoon, interleaved with the others.main, 4 sessionsBoth sessions are above all four references on median and boat fps, and below them on preparing time. That is about +1.9 fps median and +2.4 fps on the boat (+6%).
It was the only one of the thread/refresh PRs I measured this way that came out above the references. Each of the others, alone on the same
main, stayed inside the references' spread or below it:VICTORY_WIDE_CHUNK=8: 32.6 fps on the boat, clearly worse.#1093 is in its own thread.
Measurements prepared with an AI assistant (Claude Code); the runs were played on my machine.
@trustno1-coder on GitHub · 2026-11-28 19:22 UTC · original
Thanks for this. I'm closing it without merging because it conflicts with the current main in several places (main has moved a lot since it was opened, with about 100 pull requests merged today), and I can't resolve that safely on your behalf. If you'd still like it in, please rebase it on the current main and open a new pull request.
Pull request closed