gpu/shadow: O(dirty) CopiedPages bitmask, lock-free mirrors, and AVX2 Shadow::take #192

Manually merged
github merged 2 commits from github-bot/gh-192 into gh-pr/192/base 2026-11-27 08:19:46 +00:00 AGit
Owner

@⁠Vladimir-Human on GitHub · 2026-11-27 07:43 UTC · original
Vladimir-Human:perf/copied-pages-odirty-avx2 → main · +1211 −138 · 1 files · 2 commits · merged 2026-11-27 08:14 UTC

Summary

Pure CPU-side optimization of crates/victory-gpu/src/shadow.rs (watch.rs untouched, zero visual change — exact byte-for-byte host-copy and copy-back parity):

  1. O(dirty) CopiedPages 64-page uncopied bitmask
    • Replaces Mutex<Vec<u64>> in Shadow::copied with Mutex<CopiedPages> (at: Vec<u64>, uncopied_bits: Vec<u64>, uncopied: usize).
    • Adds CopiedPages::plan_stale, stale_pages_in, has_stale_in, range_all_copied, and O(1) copied_count so Shadow::copy_stale, Shadow::stale_under_writes, Shadow::merge_under_writes, Shadow::nothing_new, and window_use skip initialized regions 64 pages at a time and run in O(dirty) time.
    • Preserves ranged coverage, (from, to, known) run splitting, by_parts 4 KiB partial-page splitting, landed, stale_pages, card/window/in-place paths, and copied -> ranged lock ordering while releasing self.copied before parts_written and take_all.
  2. Lock-free AtomicBool mirrors (has_pending, has_dirty, has_sent)
    • Adds Shadow::has_pending so read-only buffers and windows skip locking Shadow::pending across writes_pending, writes_pending_in, stale_under_writes, merge_under_writes, update, nothing_new, and send_copied.
    • Replaces Card::touched with Card::has_dirty and Card::has_sent (backed by SentRuns::is_empty()): card_dirty publishes has_sent (Release) before clearing has_dirty (Release) under dirty, prunes stale sent entries when !has_dirty && relay_on && has_sent, and lets card_merge_relay, land_card, and card_dirty_now skip locking on clean copies (has_dirty checked first, then has_sent).
  3. AVX2 Shadow::take (word_runs_avx2 / word_runs_put_avx2)
    • Extends word_runs_avx2 and word_runs_put_avx2 to handle unaligned prefixes, 256-byte + 32-byte AVX2 loops, 4-byte tails, and unaligned tails across all alignments.
    • Routes Shadow::take through take_chunk -> word_runs_put instead of scalar dword_runs, preserving upcheck, keeps, card_changed_runs, and SEND counters.
  4. Unit parity tests and opt-in release benchmark
    • Adds 7 unit parity tests in shadow::copied_and_take_tests (CopiedPages bitmask/word-boundary oracle, plan_stale with ranged + partial init oracle, stale_pages_in/has_stale_in oracle, has_pending mirror, has_dirty/has_sent mirror + 4-state card_merge_relay parity, word_runs/word_runs_put/take_chunk scalar vs AVX2 parity across all 4 alignments & 33 lengths, and end-to-end Shadow::take scalar oracle across alignments & multi-page spans) plus an #[ignore] release benchmark (bench_copied_pages_and_word_runs).

Verification

  • Visual impact: None — zero shader, descriptor, pipeline, or rendering changes; all copy/merge/diff paths verified for exact byte-for-byte parity against scalar oracles.
  • Asset policy & hygiene:
    • crates/victory-gpu/src/shadow.rs: 327,913 bytes (7,486 lines, < 640 KiB limit)
    • cargo run -p xtask --locked -- policy: asset policy: 303 files ok
    • cargo test -p xtask: 11 passed; 0 failed
    • git diff --check origin/main..HEAD: clean
  • Clippy (strict CI flags):
    • cargo clippy -p victory-gpu --all-targets --locked -- -D warnings: 0 warnings
    • cargo clippy -p victory-gpu --all-targets --all-features --locked -- -D warnings: 0 warnings
  • Tests (VICTORY_D3D12_DEBUG=1, --test-threads=1):
    • Default cargo test -p victory-gpu shadow::: 54 passed; 0 failed; 4 ignored
    • Diagnostics cargo test -p victory-gpu --features diagnostics shadow::: 54 passed; 0 failed; 4 ignored
    • Release cargo test -p victory-gpu --release --locked shadow::: 54 passed; 0 failed; 4 ignored
    • Host refresh tests: unchanged_ranges_are_known (1/1), only_what_differs_goes_up (1/1 default and 1/1 with VICTORY_SEND_CHANGED=1)
    • VICTORY_RELAY=1: shadow::copied_and_take_tests (7 passed; 0 failed; 1 ignored), shadow::land_tests (2 passed; 0 failed)
  • Release benchmark (bench_copied_pages_and_word_runs, x86_64 AVX2):
    • plan_stale (160 MiB / 2,560 pages, 4 dirty): 9.4 ns/call
    • 64 MiB Shadow::take diff: scalar 8.14 ms -> AVX2 word_runs_put 5.11 ms (1.59x faster, fused compare + copy)
**@⁠Vladimir-Human** on GitHub · 2026-11-27 07:43 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/192) `Vladimir-Human:perf/copied-pages-odirty-avx2` → `main` · +1211 −138 · 1 files · 2 commits · merged 2026-11-27 08:14 UTC ## Summary Pure CPU-side optimization of `crates/victory-gpu/src/shadow.rs` (`watch.rs` untouched, **zero visual change** — exact byte-for-byte host-copy and copy-back parity): 1. **`O(dirty)` `CopiedPages` 64-page uncopied bitmask** - Replaces `Mutex<Vec<u64>>` in `Shadow::copied` with `Mutex<CopiedPages>` (`at: Vec<u64>`, `uncopied_bits: Vec<u64>`, `uncopied: usize`). - Adds `CopiedPages::plan_stale`, `stale_pages_in`, `has_stale_in`, `range_all_copied`, and O(1) `copied_count` so `Shadow::copy_stale`, `Shadow::stale_under_writes`, `Shadow::merge_under_writes`, `Shadow::nothing_new`, and `window_use` skip initialized regions 64 pages at a time and run in `O(dirty)` time. - Preserves `ranged` coverage, `(from, to, known)` run splitting, `by_parts` 4 KiB partial-page splitting, `landed`, `stale_pages`, card/window/in-place paths, and `copied -> ranged` lock ordering while releasing `self.copied` before `parts_written` and `take_all`. 2. **Lock-free `AtomicBool` mirrors (`has_pending`, `has_dirty`, `has_sent`)** - Adds `Shadow::has_pending` so read-only buffers and windows skip locking `Shadow::pending` across `writes_pending`, `writes_pending_in`, `stale_under_writes`, `merge_under_writes`, `update`, `nothing_new`, and `send_copied`. - Replaces `Card::touched` with `Card::has_dirty` and `Card::has_sent` (backed by `SentRuns::is_empty()`): `card_dirty` publishes `has_sent` (`Release`) before clearing `has_dirty` (`Release`) under `dirty`, prunes stale `sent` entries when `!has_dirty && relay_on && has_sent`, and lets `card_merge_relay`, `land_card`, and `card_dirty_now` skip locking on clean copies (`has_dirty` checked first, then `has_sent`). 3. **AVX2 `Shadow::take` (`word_runs_avx2` / `word_runs_put_avx2`)** - Extends `word_runs_avx2` and `word_runs_put_avx2` to handle unaligned prefixes, 256-byte + 32-byte AVX2 loops, 4-byte tails, and unaligned tails across all alignments. - Routes `Shadow::take` through `take_chunk` -> `word_runs_put` instead of scalar `dword_runs`, preserving `upcheck`, `keeps`, `card_changed_runs`, and `SEND` counters. 4. **Unit parity tests and opt-in release benchmark** - Adds 7 unit parity tests in `shadow::copied_and_take_tests` (`CopiedPages` bitmask/word-boundary oracle, `plan_stale` with `ranged` + partial init oracle, `stale_pages_in`/`has_stale_in` oracle, `has_pending` mirror, `has_dirty`/`has_sent` mirror + 4-state `card_merge_relay` parity, `word_runs`/`word_runs_put`/`take_chunk` scalar vs AVX2 parity across all 4 alignments & 33 lengths, and end-to-end `Shadow::take` scalar oracle across alignments & multi-page spans) plus an `#[ignore]` release benchmark (`bench_copied_pages_and_word_runs`). ## Verification - **Visual impact:** None — zero shader, descriptor, pipeline, or rendering changes; all copy/merge/diff paths verified for exact byte-for-byte parity against scalar oracles. - **Asset policy & hygiene:** - `crates/victory-gpu/src/shadow.rs`: `327,913` bytes (`7,486` lines, `< 640 KiB` limit) - `cargo run -p xtask --locked -- policy`: `asset policy: 303 files ok` - `cargo test -p xtask`: **11 passed; 0 failed** - `git diff --check origin/main..HEAD`: clean - **Clippy (strict CI flags):** - `cargo clippy -p victory-gpu --all-targets --locked -- -D warnings`: **0 warnings** - `cargo clippy -p victory-gpu --all-targets --all-features --locked -- -D warnings`: **0 warnings** - **Tests (`VICTORY_D3D12_DEBUG=1`, `--test-threads=1`):** - Default `cargo test -p victory-gpu shadow::`: **54 passed; 0 failed; 4 ignored** - Diagnostics `cargo test -p victory-gpu --features diagnostics shadow::`: **54 passed; 0 failed; 4 ignored** - Release `cargo test -p victory-gpu --release --locked shadow::`: **54 passed; 0 failed; 4 ignored** - Host refresh tests: `unchanged_ranges_are_known` (**1/1**), `only_what_differs_goes_up` (**1/1** default and **1/1** with `VICTORY_SEND_CHANGED=1`) - `VICTORY_RELAY=1`: `shadow::copied_and_take_tests` (**7 passed; 0 failed; 1 ignored**), `shadow::land_tests` (**2 passed; 0 failed**) - **Release benchmark (`bench_copied_pages_and_word_runs`, x86_64 AVX2):** - `plan_stale` (160 MiB / 2,560 pages, 4 dirty): **9.4 ns/call** - 64 MiB `Shadow::take` diff: scalar `8.14 ms` -> AVX2 `word_runs_put` **5.11 ms** (**1.59x** faster, fused compare + copy)
Reduce CPU overhead in host-copy refresh and copy-back metadata paths without
changing rendering behavior:

- Replace the dense `Vec<u64>` scan in `Shadow::copied` with `CopiedPages`,
  pairing per-page timestamps with a 64-page-per-word uncopied bitmask so
  `Shadow::copy_stale`, `Shadow::stale_under_writes`, and
  `Shadow::merge_under_writes` run in O(dirty) time while preserving `ranged`
  coverage, 4 KiB partial-page splitting (`by_parts`), `landed`, and releasing
  `self.copied` before invoking memory copies (`take_all`).
- Add lock-free `AtomicBool` mirrors (`has_pending`, `has_dirty`, `has_sent`)
  to skip acquiring `pending`, `dirty`, and `sent` mutexes on read-only and
  clean copies; publish `has_sent` (Release) before clearing `has_dirty`
  (Release) under `dirty` so concurrent `card_merge_relay` and `land_card`
  readers checking `has_dirty` then `has_sent` never miss transitioning ranges.
- Extend AVX2 `word_runs_avx2` and `word_runs_put_avx2` to handle unaligned
  prefixes, 32-byte blocks, and tails across all alignments, and route
  `Shadow::take` through `take_chunk` -> `word_runs_put` instead of scalar
  `dword_runs`.
- Add parity tests covering `CopiedPages` vs dense `u64` oracles, lock-free
  mirror transitions, and `Shadow::take` / `word_runs` scalar vs AVX2 parity
  across alignments, tails, and multi-page boundaries, plus an opt-in release
  benchmark.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-27 07:47:26 +00:00
Author
Owner

@⁠efsebayern on GitHub · 2026-11-27 07:59 UTC · original · reviewed

I reviewed this on the PR head (db28bb8). cargo test -p victory-gpu --lib gave 463 passed, 0 failed, 43 ignored. cargo clippy -p victory-gpu --all-targets -- -D warnings was clean.

One concurrency concern in copy_stale (crates/victory-gpu/src/shadow.rs, around lines 5002-5041)

The old code held copied for the whole function, take_all included, so refreshes of one Shadow ran one at a time. Now plan_stale stamps the pages with at = now, and the lock is dropped before take_all copies the bytes. That leaves a window where the pages count as copied but the copy hasn't finished.

  1. Stale data. Thread A plans a refresh, drops the lock, and starts copying. Thread B calls update or nothing_new on an overlapping range during the copy. B sees write <= at and treats the range as current, so it can record or upload the shadow while A is still writing it.
  2. Concurrent writes. Two overlapping refreshes with different now both plan runs on the same pages. Both then take into self.data / held through raw pointers at the same time, which can tear bytes.

If update is never reached from two threads for the same shadow, this is moot. I didn't trace every caller of host.rs:9083. If it can be reached that way, holding copied across take_all, or adding a per-shadow "copy in flight" guard, would close the window.

Minor: card_dirty (around lines 1076-1081) now calls forget(fetched) on clean copies that have has_sent set, where before it only ran on touched ones. That widens an existing race with card_merge_relay when fetched_after < fetched; it doesn't add a new one.

Checked and looks correct:

  • CopiedPages: masks at lo%64 and hi%64, high bits of the last word kept zero, single-word ranges.
  • plan_stale fast and sparse paths, compared with the old dense loop.
  • stale_pages_in / has_stale_in.
  • The AVX2 path: runtime-detected, every load bounded by aligned_end <= n, scalar head and tail, output matches dword_runs for all four values of at & 3.
  • has_pending / has_dirty / has_sent: the Release/Acquire ordering is sound.

AI-assisted review (Claude Code).

**@⁠efsebayern** on GitHub · 2026-11-27 07:59 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/192#pullrequestreview-6085090162) · **reviewed** I reviewed this on the PR head (db28bb8). `cargo test -p victory-gpu --lib` gave 463 passed, 0 failed, 43 ignored. `cargo clippy -p victory-gpu --all-targets -- -D warnings` was clean. **One concurrency concern in `copy_stale`** (`crates/victory-gpu/src/shadow.rs`, around lines 5002-5041) The old code held `copied` for the whole function, `take_all` included, so refreshes of one `Shadow` ran one at a time. Now `plan_stale` stamps the pages with `at = now`, and the lock is dropped before `take_all` copies the bytes. That leaves a window where the pages count as copied but the copy hasn't finished. 1. **Stale data.** Thread A plans a refresh, drops the lock, and starts copying. Thread B calls `update` or `nothing_new` on an overlapping range during the copy. B sees `write <= at` and treats the range as current, so it can record or upload the shadow while A is still writing it. 2. **Concurrent writes.** Two overlapping refreshes with different `now` both plan runs on the same pages. Both then `take` into `self.data` / `held` through raw pointers at the same time, which can tear bytes. If `update` is never reached from two threads for the same shadow, this is moot. I didn't trace every caller of `host.rs:9083`. If it can be reached that way, holding `copied` across `take_all`, or adding a per-shadow "copy in flight" guard, would close the window. **Minor:** `card_dirty` (around lines 1076-1081) now calls `forget(fetched)` on clean copies that have `has_sent` set, where before it only ran on touched ones. That widens an existing race with `card_merge_relay` when `fetched_after < fetched`; it doesn't add a new one. **Checked and looks correct:** - `CopiedPages`: masks at `lo%64` and `hi%64`, high bits of the last word kept zero, single-word ranges. - `plan_stale` fast and sparse paths, compared with the old dense loop. - `stale_pages_in` / `has_stale_in`. - The AVX2 path: runtime-detected, every load bounded by `aligned_end <= n`, scalar head and tail, output matches `dword_runs` for all four values of `at & 3`. - `has_pending` / `has_dirty` / `has_sent`: the Release/Acquire ordering is sound. *AI-assisted review (Claude Code).*
Keep the page-state lock through the byte copy and range update. Preserve sent ranges for clean card copies.
Author
Owner

@⁠TaynanGT on GitHub · 2026-11-27 08:07 UTC · original

@⁠efsebayern Thanks for tracing the refresh order. I’ve kept the page-state lock through the byte copy and the range update, and preserved the sent ranges for clean card copies. @⁠Vladimir-Human, that adjustment is in c289a95 on this PR. The Windows diagnostics run passed 54 focused shadow tests. Review

**@⁠TaynanGT** on GitHub · 2026-11-27 08:07 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/192#issuecomment-7213175136) @⁠efsebayern Thanks for tracing the refresh order. I’ve kept the page-state lock through the byte copy and the range update, and preserved the sent ranges for clean card copies. @⁠Vladimir-Human, that adjustment is in `c289a95` on this PR. The Windows diagnostics run passed 54 focused shadow tests. [Review](https://git.gtahub.st/github/TaynanGT--Vice-Tay/pulls/192)
github-bot changed target branch from main to gh-pr/192/base 2026-11-27 08:19:45 +00:00
github manually merged commit c289a95b9b into gh-pr/192/base 2026-11-27 08:19:46 +00:00
Author
Owner

@⁠Garu667 on GitHub · 2026-11-27 08:22 UTC · original

An NVIDIA data point for this PR, on a CPU-bound card: RTX 3080 10 GB, i5-13600K. Diag build of main e939566, with and without this branch merged on top. -Machine 4070, Series S, prison cell, standing.

Each run started from a fresh copy of the same warmed cache and save, in ABBA order. FPS is the median of the last 18 frame lines (about 90 s):

Build FPS median lowest ms/frame preparing copies (in preparing)
main 15.1 14.7 66 47 17.2
+ #192 14.7 14.0 68 49 18.0
+ #192 15.0 13.9 67 48 18.5
main 14.8 13.9 68 51 19.1
  • Neutral on this scene: main averages 14.95 fps and #192 14.85, within the ±0.4 run-to-run spread.
  • No faults and no visible change in either build.
  • This scene may simply not be heavy on dirty-page tracking, so a gain could still show where pages change more: the open world, or driving. I can run that with this branch if it helps.

🤖 Generated with Claude Code

**@⁠Garu667** on GitHub · 2026-11-27 08:22 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/192#issuecomment-7213465505) An NVIDIA data point for this PR, on a CPU-bound card: RTX 3080 10 GB, i5-13600K. Diag build of main `e939566`, with and without this branch merged on top. `-Machine 4070`, Series S, prison cell, standing. Each run started from a fresh copy of the same warmed cache and save, in ABBA order. FPS is the median of the last 18 frame lines (about 90 s): | Build | FPS median | lowest | ms/frame | preparing | copies (in preparing) | |---|---:|---:|---:|---:|---:| | main | 15.1 | 14.7 | 66 | 47 | 17.2 | | + #192 | 14.7 | 14.0 | 68 | 49 | 18.0 | | + #192 | 15.0 | 13.9 | 67 | 48 | 18.5 | | main | 14.8 | 13.9 | 68 | 51 | 19.1 | - Neutral on this scene: main averages 14.95 fps and #192 14.85, within the ±0.4 run-to-run spread. - No faults and no visible change in either build. - This scene may simply not be heavy on dirty-page tracking, so a gain could still show where pages change more: the open world, or driving. I can run that with this branch if it helps. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Author
Owner

@⁠TaynanGT on GitHub · 2026-11-27 08:24 UTC · original

@⁠Garu667 Thanks for running the ABBA control. The 14.95 to 14.85 FPS difference is within the run spread in the cell, with the same visible output. Yes, a matched drive would be useful if you have one available. The copy time and dirty-page counts for that stretch would show whether it exercises the changed path more than the cell does.

**@⁠TaynanGT** on GitHub · 2026-11-27 08:24 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/192#issuecomment-7213499597) @⁠Garu667 Thanks for running the ABBA control. The 14.95 to 14.85 FPS difference is within the run spread in the cell, with the same visible output. Yes, a matched drive would be useful if you have one available. The copy time and dirty-page counts for that stretch would show whether it exercises the changed path more than the cell does.
Author
Owner

@⁠Vladimir-Human on GitHub · 2026-11-27 08:33 UTC · original

Thank you @efsebayern for catching the copy_stale lock release window and the clean-copy sent prune in card_dirty, and thank you @TaynanGT for fixing both cleanly in c289a95 before merge! We backported the exact same hardening to our open PRs sharing CopiedPages / card_dirty.

Thank you as well @Garu667 for the RTX 3080 ABBA run — glad to see zero faults and neutral frame time within run-to-run spread in the static interior scene, and agreed that high-churn traversal / streaming scenes are where dirty-page tracking and AVX2 Shadow::take carry measurable weight.

**@⁠Vladimir-Human** on GitHub · 2026-11-27 08:33 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/192#issuecomment-7213666521) Thank you `@efsebayern` for catching the `copy_stale` lock release window and the clean-copy `sent` prune in `card_dirty`, and thank you `@TaynanGT` for fixing both cleanly in `c289a95` before merge! We backported the exact same hardening to our open PRs sharing `CopiedPages` / `card_dirty`. Thank you as well `@Garu667` for the RTX 3080 ABBA run — glad to see zero faults and neutral frame time within run-to-run spread in the static interior scene, and agreed that high-churn traversal / streaming scenes are where dirty-page tracking and AVX2 `Shadow::take` carry measurable weight.
Author
Owner

@⁠Garu667 on GitHub · 2026-11-27 08:35 UTC · original

Follow-up in the open world, same machine and builds. Each run started from a fresh copy of the same open-world save. I walked the same loop around a house, played by hand, about 90 s in the world each:

Build FPS median p10 preparing by draws: 4-6k / 6-8k / 8k+
main 12.0 7.6 60 ms 13.9 / 12.2 / 9.9
+ #192 12.1 8.2 58 ms 13.3 / 11.9 / 10.9

Neutral here too, within noise. Preparation is about 2 ms lower with the branch, but that's not significant on two runs. No faults.

🤖 Generated with Claude Code

**@⁠Garu667** on GitHub · 2026-11-27 08:35 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/192#issuecomment-7213692425) Follow-up in the open world, same machine and builds. Each run started from a fresh copy of the same open-world save. I walked the same loop around a house, played by hand, about 90 s in the world each: | Build | FPS median | p10 | preparing | by draws: 4-6k / 6-8k / 8k+ | |---|---:|---:|---:|---| | main | 12.0 | 7.6 | 60 ms | 13.9 / 12.2 / 9.9 | | + #192 | 12.1 | 8.2 | 58 ms | 13.3 / 11.9 / 10.9 | Neutral here too, within noise. Preparation is about 2 ms lower with the branch, but that's not significant on two runs. No faults. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Author
Owner

@⁠TaynanGT on GitHub · 2026-11-27 08:38 UTC · original

@⁠Vladimir-Human Thanks for carrying both changes over to the ports. Keeping the page lock through the copy and preserving the sent ranges on clean copies gives those branches the same refresh behaviour as the merged revision here.

**@⁠TaynanGT** on GitHub · 2026-11-27 08:38 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/192#issuecomment-7213764976) @⁠Vladimir-Human Thanks for carrying both changes over to the ports. Keeping the page lock through the copy and preserving the sent ranges on clean copies gives those branches the same refresh behaviour as the merged revision here.
Author
Owner

@⁠TaynanGT on GitHub · 2026-11-27 08:39 UTC · original

@⁠Garu667 Thanks for doing the house loop from the same save. The whole-run result is neutral on that pair: 12.0 to 12.1 FPS, with preparation at 60 and 58 ms. This adds a traversal check with both runs completing cleanly.

**@⁠TaynanGT** on GitHub · 2026-11-27 08:39 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/192#issuecomment-7213765760) @⁠Garu667 Thanks for doing the house loop from the same save. The whole-run result is neutral on that pair: 12.0 to 12.1 FPS, with preparation at 60 and 58 ms. This adds a traversal check with both runs completing cleanly.
This discussion has been locked. Commenting is limited to contributors.
No description provided.