gpu: shadow: remember up to 16 whole-taken views under one lock, index carded copies, and cut per-refresh allocations #368

Open
github-bot wants to merge 3 commits from github-bot/gh-368 into main AGit
Owner

@⁠lucamzanon on GitHub · 2026-12-03 20:45 UTC · original
lucamzanon:xmem/7-shadow-copy → main · +1227 −203 · 1 files · 3 commits · open

Summary

Eliminates massive redundant per-frame CPU→GPU buffer re-copies and lock/allocation overhead in crates/victory-gpu/src/shadow.rs (the only file touched).

Root Causes & Changes

  1. 5b96671 — Remember up to 16 whole-taken views under one lock (Taken/Whole):
    • Previously ranged remembered only 2 whole-taken ranges (last + longest). Any buffer read through ≥3 views (e.g., the big heap copy refreshed in 14 ranges/frame) re-copied the unaligned end pages of views 3..14 every single frame, even when unmodified.
    • Now remembers up to 16 exact whole-taken ranges (preserving nested/overlapping views, dropping only subsumed ranges, evicting smallest / highest-address to prevent LRU thrash).
    • Merges the two nested locks (copied + ranged, previously taken 2–3× per refresh) into a single Taken lock, and reuses thread-local scratch buffers in copy_stale.
  2. 8e1368c — Address-indexed CARDED copies, enum Job, batched take, cached peek:
    • send_copied previously allocated a Vec<Arc> of every carded copy (Weak::upgrade = 2 atomic RMWs each) on every Step::Copy. Now kept sorted by start address with prefix-max reach for O(log N) lookup + short walk, copying outside the table lock.
    • wide_each/wide replaced ~18 heap allocations per call with an enum Job (zero per-thread boxing).
    • take batches per-page runs/dirty-lock/counters into thread-local scratch + 1 lock per taking.
    • peek at record time now uses and populates the per-thread FOUND cache.

Verification & Moving A/B/B/A Benchmarks (RX 9070 XT 16 GB / Ryzen 7 5700X, Linux RADV)

  • Unit tests: 22/22 shadow:: tests pass (11 new, including randomized model-check of Whole, eviction, CARDED table vs oracle, 4-view write-watch, and >16-view stress) + 2/2 host::refresh_tests. cargo check, cargo test --no-run (x86_64-pc-windows-msvc), and clippy --no-deps -p victory-gpu (0 lints in shadow.rs) clean.
  • Test setup: VICTORY_BENCH=rt, 2560x1440 → 4K FSR 4 Quality, no Frame Generation, repo-built Mesa 26.3.1 RADV + vkd3d-proton, 94,199 warm pipelines, interleaved A -> B -> B -> A with deterministic moving gameplay (diag + VICTORY_KEYS_FILE).
  • Visual parity: verified side-by-side on 4K screenshots for both scenes (identical geometry, lighting, water, UI; 0 crashes, 0 artifacts).

In-Game Moving A/B/B/A Results

Scene Baseline main (842767a) This PR (B) Delta Pair wins
Prison (3m x 4, moving) 24.50 fps (24.3 / 24.7), 1% low 11.85 29.95 fps (29.5 / 30.4), 1% low 14.75 +22.24% avg / +24.47% 1% low 2/2
Boat (4m x 4, moving) 27.40 fps (26.8 / 28.0), 1% low 9.90 32.50 fps (32.6 / 32.4), 1% low 10.45 +18.61% avg / +5.56% 1% low 2/2

HUD Telemetry Snapshot (Matched Boat Scene, ~2,540 draws/frame)

  • Transfers (MB/f up): 5.2 MB/f → 0.6 MB/f (-88% redundant upload traffic)
  • Copy prep: 2.3 ms/f → 1.7 ms/f (Prison: 8.3 ms/f → 3.2 ms/f, Transfers 29.2 → 5.3 MB/f)
  • GPU frame time: 34.5 ms → 30.4 ms (Hitches: 2 → 0)
**@⁠lucamzanon** on GitHub · 2026-12-03 20:45 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/368) `lucamzanon:xmem/7-shadow-copy` → `main` · +1227 −203 · 1 files · 3 commits · open ## Summary Eliminates massive redundant per-frame CPU→GPU buffer re-copies and lock/allocation overhead in `crates/victory-gpu/src/shadow.rs` (the only file touched). ### Root Causes & Changes 1. **`5b96671` — Remember up to 16 whole-taken views under one lock (`Taken`/`Whole`):** - Previously `ranged` remembered only **2** whole-taken ranges (last + longest). Any buffer read through ≥3 views (e.g., the big heap copy refreshed in 14 ranges/frame) re-copied the unaligned end pages of views 3..14 **every single frame**, even when unmodified. - Now remembers up to **16** exact whole-taken ranges (preserving nested/overlapping views, dropping only subsumed ranges, evicting smallest / highest-address to prevent LRU thrash). - Merges the two nested locks (`copied` + `ranged`, previously taken 2–3× per refresh) into a single `Taken` lock, and reuses thread-local scratch buffers in `copy_stale`. 2. **`8e1368c` — Address-indexed `CARDED` copies, enum `Job`, batched `take`, cached `peek`:** - `send_copied` previously allocated a `Vec<Arc>` of every carded copy (`Weak::upgrade` = 2 atomic RMWs each) on every `Step::Copy`. Now kept sorted by start address with prefix-max `reach` for O(log N) lookup + short walk, copying outside the table lock. - `wide_each`/`wide` replaced ~18 heap allocations per call with an enum `Job` (zero per-thread boxing). - `take` batches per-page runs/dirty-lock/counters into thread-local scratch + 1 lock per taking. - `peek` at record time now uses and populates the per-thread `FOUND` cache. ## Verification & Moving A/B/B/A Benchmarks (RX 9070 XT 16 GB / Ryzen 7 5700X, Linux RADV) - **Unit tests:** 22/22 `shadow::` tests pass (11 new, including randomized model-check of `Whole`, eviction, `CARDED` table vs oracle, 4-view write-watch, and >16-view stress) + 2/2 `host::refresh_tests`. `cargo check`, `cargo test --no-run` (`x86_64-pc-windows-msvc`), and `clippy --no-deps -p victory-gpu` (0 lints in `shadow.rs`) clean. - **Test setup:** `VICTORY_BENCH=rt`, 2560x1440 → 4K FSR 4 Quality, no Frame Generation, repo-built Mesa 26.3.1 RADV + vkd3d-proton, 94,199 warm pipelines, interleaved `A -> B -> B -> A` with deterministic moving gameplay (`diag` + `VICTORY_KEYS_FILE`). - **Visual parity:** verified side-by-side on 4K screenshots for both scenes (identical geometry, lighting, water, UI; 0 crashes, 0 artifacts). ### In-Game Moving A/B/B/A Results | Scene | Baseline `main` (`842767a`) | This PR (B) | Delta | Pair wins | |---|---:|---:|---:|---:| | **Prison** (`3m x 4`, moving) | `24.50 fps` (`24.3` / `24.7`), 1% low `11.85` | **`29.95 fps`** (`29.5` / `30.4`), 1% low **`14.75`** | **`+22.24%` avg / `+24.47%` 1% low** | **2/2** | | **Boat** (`4m x 4`, moving) | `27.40 fps` (`26.8` / `28.0`), 1% low `9.90` | **`32.50 fps`** (`32.6` / `32.4`), 1% low **`10.45`** | **`+18.61%` avg / `+5.56%` 1% low** | **2/2** | ### HUD Telemetry Snapshot (Matched Boat Scene, ~2,540 draws/frame) - **Transfers (`MB/f up`):** `5.2 MB/f` → **`0.6 MB/f`** (**-88% redundant upload traffic**) - **Copy prep:** `2.3 ms/f` → **`1.7 ms/f`** (Prison: `8.3 ms/f` → **`3.2 ms/f`**, Transfers `29.2` → **`5.3 MB/f`**) - **GPU frame time:** `34.5 ms` → **`30.4 ms`** (`Hitches: 2` → **`0`**)
A refresh of a range whose ends lie in pages no whole page of the range
holds could not say so per page, and copied its two ends again at every
refresh of the range, written or not, unless the range was remembered as
taken whole. Two were remembered, the last and the longest: that held a
buffer read through one view or two, but read through three or more,
every view but the longest copied its two ends again at each refresh.
(The big heap's copy alone is refreshed in fourteen ranges a frame.)

A copy now keeps up to sixteen ranges taken whole, each with the asking
it was taken at. A view inside another, or over its end, is remembered
with its own asking, and what lies around it stays known as of the
earlier one's; only a range inside one taken later is dropped, as that
says all it said and more. Past sixteen the smallest goes, of one size
the one highest in memory: with more views of a size than go round, those
above the rest are the ones left out, every frame, and not (the oldest
first) now one now another, all of them.

The pages and the ranges sit under one lock, taken, where there were two
with one inside the other: it was taken three times by a refresh that
copied and twice by one that only looked. And what copy_stale finds to
copy (the runs of pages, the pages taken before and written since, the
runs cut to the parts written) is kept per thread instead of being made
afresh for each of the thousands of refreshes a frame.
send_copied went through every copy in the card's memory for each of the
title's copies into its buffers' memory, thousands a frame: a Vec of all
of them, each held a moment (Weak::upgrade is two changes to two lines
of its own), and a range test apiece. The copies are kept in order of the
title memory they are of, with what each reaches over, so that a copy
into [dst, end) finds the few that hold any of it by a search and a
short walk back, holds them in a list kept per thread, and copies
outside the table's lock (a copy may wait for the card).

wide_each made two Arcs, a Vec and a Box for each thread's job, and wide
another Arc and a Box each: eighteen allocations a call for jobs that are
one closure over a counter. Jobs are an enum now: the numbers' work is
one Arc and the done count another, and nothing is boxed per thread.

take, of a copy in the card's memory, made two Vecs per page (the changed
runs, the dwords), took the card's dirty lock per page and added to four
counters per page. The runs are kept per thread, the lock is taken once
per taking and the counters added once.

peek, at record time, took the table's lock and walked it for each of a
title's copies: it reads and fills the per-thread cache of answers that
find keeps.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-12-03 20:49:49 +00:00
Author
Owner

@⁠Kal0s-design on GitHub · 2026-12-04 03:10 UTC · original

Tested 8e1368c natively on Windows 11 (MSVC), real D3D12 with one NVIDIA desktop card plus WARP, against the merge base 842767a.

I think there's a regression in Shadow::take from the second commit. sends now collects (offset, len)

sends.push((at - start, n));                 // shadow.rs:2083
sends.push((at - start + a, len));           // shadow.rs:2089
...
self.card_changed_runs(sends.iter().copied());

but card_changed_runs takes (from, to) and drops anything where from >= to. Past the first page of a copy almost every run gets dropped, and in the first page the range marked is [offset, len) instead of [offset, offset + len). The CPU side gets the new bytes but they never go to the card side. This only hits copies with changes_only set, so the by_address ones (directory, arena, streamed structures in memory.rs) and anything after keep_stores. The PR's own tests don't reach it because Shadow::unbacked leaves changes_only off, so views_tests go through copy().

A small local test (not pushed) shows it. It makes an unbacked copy, calls keep_stores(), then take(start + 2*PAGE + 100, start + 2*PAGE + 300, false) and looks at card.dirty.

  • on this PR dirty comes back [] where [(2*PAGE+100, 2*PAGE+300)] is expected
  • on the merge base it passes
  • with (off, off + len) in both pushes it passes on this PR too, including a second check with one changed dword and known = true

The fix is just those two lines. I'd also suggest adding a keep_stores variant of the views test so this path is covered. Since part of the drop in MB/f up might come from these sends being lost, it would be worth measuring again after the fix.

The rest looked fine to me.

  • Whole keeps the same meaning the two-slot ranged had. Nothing resets it outside copy_stale and nothing_new, same as before, so reused addresses behave as on main (not better, not worse). Eviction only costs recopies, never stale data, and an out-of-order now only makes it more conservative.
  • CARDED ordering with reach as a prefix max is correct, dead entries only make the walk a bit longer, and send_copied drops the table lock before copying like before. No new lock nesting that I could find.
  • peek through FOUND uses the same remember-under-read-lock and BUFFERS_CHANGED check as lookup.

Tests

  • the 11 new tests plus the changed parts test, 10 runs, all pass
  • shadow:: 5 runs each, 22/22 on the PR and 11/11 on base
  • full victory-gpu --lib with --test-threads=4, two runs each, 320 pass on the PR and 309 on base, with the same 5 failures on both (the two indirect::host_list_*, the two pipeline::host library loads, and the flaky watch::tests::the_rest_of_the_one_asking_has_a_number_of_its_own). Nothing new
  • clippy has no new warnings and nothing in shadow.rs

I didn't run any game here, so I can't say anything about the fps numbers.

AI-assisted: yes

**@⁠Kal0s-design** on GitHub · 2026-12-04 03:10 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/368#issuecomment-7399777162) Tested 8e1368c natively on Windows 11 (MSVC), real D3D12 with one NVIDIA desktop card plus WARP, against the merge base 842767a. I think there's a regression in `Shadow::take` from the second commit. `sends` now collects `(offset, len)` ```rust sends.push((at - start, n)); // shadow.rs:2083 sends.push((at - start + a, len)); // shadow.rs:2089 ... self.card_changed_runs(sends.iter().copied()); ``` but `card_changed_runs` takes `(from, to)` and drops anything where `from >= to`. Past the first page of a copy almost every run gets dropped, and in the first page the range marked is `[offset, len)` instead of `[offset, offset + len)`. The CPU side gets the new bytes but they never go to the card side. This only hits copies with `changes_only` set, so the `by_address` ones (directory, arena, streamed structures in memory.rs) and anything after `keep_stores`. The PR's own tests don't reach it because `Shadow::unbacked` leaves `changes_only` off, so `views_tests` go through `copy()`. A small local test (not pushed) shows it. It makes an unbacked copy, calls `keep_stores()`, then `take(start + 2*PAGE + 100, start + 2*PAGE + 300, false)` and looks at `card.dirty`. - on this PR dirty comes back `[]` where `[(2*PAGE+100, 2*PAGE+300)]` is expected - on the merge base it passes - with `(off, off + len)` in both pushes it passes on this PR too, including a second check with one changed dword and `known = true` The fix is just those two lines. I'd also suggest adding a `keep_stores` variant of the views test so this path is covered. Since part of the drop in MB/f up might come from these sends being lost, it would be worth measuring again after the fix. The rest looked fine to me. - `Whole` keeps the same meaning the two-slot `ranged` had. Nothing resets it outside `copy_stale` and `nothing_new`, same as before, so reused addresses behave as on main (not better, not worse). Eviction only costs recopies, never stale data, and an out-of-order `now` only makes it more conservative. - `CARDED` ordering with `reach` as a prefix max is correct, dead entries only make the walk a bit longer, and `send_copied` drops the table lock before copying like before. No new lock nesting that I could find. - `peek` through `FOUND` uses the same remember-under-read-lock and `BUFFERS_CHANGED` check as `lookup`. Tests - the 11 new tests plus the changed parts test, 10 runs, all pass - `shadow::` 5 runs each, 22/22 on the PR and 11/11 on base - full `victory-gpu --lib` with `--test-threads=4`, two runs each, 320 pass on the PR and 309 on base, with the same 5 failures on both (the two `indirect::host_list_*`, the two `pipeline::host` library loads, and the flaky `watch::tests::the_rest_of_the_one_asking_has_a_number_of_its_own`). Nothing new - clippy has no new warnings and nothing in shadow.rs I didn't run any game here, so I can't say anything about the fps numbers. AI-assisted: yes
Author
Owner

@⁠lucamzanon on GitHub · 2026-12-04 04:45 UTC · original

Great catch @⁠Kal0s-design — thank you!

Fixed both lines in 30150dd ((at - start, at - start + n) and (at - start + a, at - start + a + len)) and added take_marks_dirty_end_offsets_after_keep_stores covering both the whole-page and changed-dword paths.

Re-ran the full moving A/B/B/A (VICTORY_BENCH=rt, 1440p → 4K FSR 4 Quality, no FG, RX 9070 XT / Ryzen 7 5700X) on 30150dd vs 842767a — you were spot on that the huge +18%/+22% earlier was mostly from the dropped changes_only sends:

Scene Baseline 842767a (A) Post-fix 30150dd (B) Delta Pair wins
Prison (3m x 4, moving) 24.90 fps (25.2 / 24.6), 1% low 11.50 25.85 fps (24.8 / 26.9), 1% low 11.30 +3.82% avg / -1.74% 1% low 1/2
Boat (4m x 4, moving) 27.70 fps (28.2 / 27.2), 1% low 10.00 27.65 fps (27.4 / 27.9), 1% low 9.90 -0.18% avg / -1.00% 1% low 1/2

Zero crashes on all 8 runs. At 4K RT (heavily GPU-bound on RX 9070 XT), Prison still shows a real +3.8% uplift while Boat is neutral.

**@⁠lucamzanon** on GitHub · 2026-12-04 04:45 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/368#issuecomment-7401599881) Great catch @⁠Kal0s-design — thank you! Fixed both lines in `30150dd` (`(at - start, at - start + n)` and `(at - start + a, at - start + a + len)`) and added `take_marks_dirty_end_offsets_after_keep_stores` covering both the whole-page and changed-dword paths. Re-ran the full moving A/B/B/A (`VICTORY_BENCH=rt`, 1440p → 4K FSR 4 Quality, no FG, RX 9070 XT / Ryzen 7 5700X) on `30150dd` vs `842767a` — you were spot on that the huge `+18%/+22%` earlier was mostly from the dropped `changes_only` sends: | Scene | Baseline `842767a` (A) | Post-fix `30150dd` (B) | Delta | Pair wins | |---|---:|---:|---:|---:| | **Prison** (`3m x 4`, moving) | `24.90 fps` (`25.2` / `24.6`), 1% low `11.50` | **`25.85 fps`** (`24.8` / `26.9`), 1% low `11.30` | **`+3.82%` avg** / `-1.74%` 1% low | 1/2 | | **Boat** (`4m x 4`, moving) | `27.70 fps` (`28.2` / `27.2`), 1% low `10.00` | `27.65 fps` (`27.4` / `27.9`), 1% low `9.90` | `-0.18%` avg / `-1.00%` 1% low | 1/2 | Zero crashes on all 8 runs. At 4K RT (heavily GPU-bound on RX 9070 XT), Prison still shows a real `+3.8%` uplift while Boat is neutral.
Author
Owner

@⁠Luxuride on GitHub · 2026-12-04 12:20 UTC · original

The only PR in this batch with both a measured win and a model-checked test suite — worth the rebase.

What I verified:

  • The locking, specifically, because you now have three tables: the orders are taken → card.dirty (crates/victory-gpu/src/shadow.rs:2149) and CARDED → card.dirty (shadow.rs:482-507), card_dirty never takes taken while holding card.dirty, and send_copied copies outside the CARDED lock via SENDING. No cycle, no defect found.
  • Job::Each with an atomic cursor and a Left count/Condvar, splitting long runs into 256 KiB parts through wide_each, is a good way to keep the wide path without per-item boxes.

Two things to fix before it goes in:

  1. A length where an end belonged. Commit 3 fixes commit 2 pushing (at - start, n) into a dirty-range list that expects an end — at both the whole-page and the dword-run paths — and the regression test only covers those two. (offset, end) pairs cross four layers in shadow.rs; a newtype or an assertion on the invariant is what stops the next one. Your own history is the argument.
  2. Whole eviction is unconditional. WHOLE_MOST = 16 with insert dropping subsumed ranges and evicting the smallest: a title cycling through 17+ whole-taken views per frame silently goes back to over-copying. That is an acceptable answer, but it should be written down where the constant is, not discovered.

Also: 1210 lines in one file, three commits that each say something different — ask the maintainer to land them as-is rather than squashed.

173 behind, no conflict.

**@⁠Luxuride** on GitHub · 2026-12-04 12:20 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/368#issuecomment-7411294314) The only PR in this batch with both a measured win and a model-checked test suite — worth the rebase. What I verified: - The locking, specifically, because you now have three tables: the orders are `taken → card.dirty` (`crates/victory-gpu/src/shadow.rs:2149`) and `CARDED → card.dirty` (`shadow.rs:482-507`), `card_dirty` never takes `taken` while holding `card.dirty`, and `send_copied` copies outside the `CARDED` lock via `SENDING`. No cycle, no defect found. - `Job::Each` with an atomic cursor and a `Left` count/Condvar, splitting long runs into 256 KiB parts through `wide_each`, is a good way to keep the wide path without per-item boxes. Two things to fix before it goes in: 1. **A length where an end belonged.** Commit 3 fixes commit 2 pushing `(at - start, n)` into a dirty-range list that expects an end — at both the whole-page and the dword-run paths — and the regression test only covers those two. `(offset, end)` pairs cross four layers in `shadow.rs`; a newtype or an assertion on the invariant is what stops the next one. Your own history is the argument. 2. **`Whole` eviction is unconditional.** `WHOLE_MOST = 16` with `insert` dropping subsumed ranges and evicting the smallest: a title cycling through 17+ whole-taken views per frame silently goes back to over-copying. That is an acceptable answer, but it should be written down where the constant is, not discovered. Also: 1210 lines in one file, three commits that each say something different — ask the maintainer to land them as-is rather than squashed. 173 behind, no conflict.
github-bot force-pushed github-bot/gh-368 from 30150dd9bb to 1d068d7422 2026-12-04 13:03:52 +00:00 Compare
Author
Owner

@⁠lucamzanon on GitHub · 2026-12-04 12:57 UTC · original

Thanks @⁠Luxuride! Rebased onto main (0fd7614, keeping all 3 commits separate as suggested) and updated commit 3 (1d068d7) with both items:

  1. Added debug_assert!(from <= to && to <= len) inside card_changed_runs so any (offset, len) mistake or out-of-bounds range panics immediately in debug/tests instead of being silently dropped.
  2. Documented the unconditional smallest-range eviction policy directly on WHOLE_MOST = 16.

Re-verified 23/23 shadow:: tests under Wine (debug build, with the new debug_assert! active) and 0 clippy warnings in shadow.rs.

**@⁠lucamzanon** on GitHub · 2026-12-04 12:57 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/368#issuecomment-7412153013) Thanks @⁠Luxuride! Rebased onto `main` (`0fd7614`, keeping all 3 commits separate as suggested) and updated commit 3 (`1d068d7`) with both items: 1. Added `debug_assert!(from <= to && to <= len)` inside `card_changed_runs` so any `(offset, len)` mistake or out-of-bounds range panics immediately in debug/tests instead of being silently dropped. 2. Documented the unconditional smallest-range eviction policy directly on `WHOLE_MOST = 16`. Re-verified 23/23 `shadow::` tests under Wine (debug build, with the new `debug_assert!` active) and 0 clippy warnings in `shadow.rs`.
This pull request can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/368/head:github-bot/gh-368'
git switch 'github-bot/gh-368'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-368'
git switch 'github-bot/gh-368'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-368'
git switch 'github-bot/gh-368'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-368'
git switch 'main'
git merge --squash 'github-bot/gh-368'
git switch 'main'
git merge --ff-only 'github-bot/gh-368'
git switch 'main'
git merge 'github-bot/gh-368'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.