GPU: append only newly covered bytes to write snapshots #3209

Open
yumaste wants to merge 2 commits from upstream-pr/3211 into main
yumaste commented 2026-11-26 13:01:55 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by yumaste on 2026-11-26T13:01:55Z.


Problem

A submission can declare overlapping writes to the same large GPU shadow. Whenever the covered range grows, Shadow::writing allocates or takes another buffer and copies the previous snapshot into it along with the new bytes. Repeated extensions recopy the same data before any GPU work runs.

Change

Keep the captured bytes in one pooled buffer and index disjoint ranges into it. Each declaration appends only bytes that have not been captured. Growth reuses a suitable touched pool buffer when available and returns the old one. The first checkout uses the shadow's last captured size as a preference, so repeated submissions can start in a warm buffer that already fits. Refreshes still update the baseline where the CPU has supplied newer values before submission. During copy-back, contiguous pieces are compared in place. A piece stored in several fragments is assembled only when the GPU changed it.

Synthetic benchmark

Windows x64, Core Ultra 9 275HX, Rust 1.98.1 with -C opt-level=3. Captured from a synthetic 128 MiB buffer. Timed the capture and comparison kernels from main and this branch with independent warmed pools, alternating run order and reusing the snapshot across modeled submissions. Medians of 16 runs per variant. Comparison skips duplicate full pieces as the copy-back loop does. These figures exclude D3D12 queue execution, synchronization, and the actual writes to guest memory.

Ranges Capture before -> after Comparison before -> after
17 overlapping ranges growing from 32 to 96 MiB 56.93 -> 5.91 ms 11.40 -> 10.80 ms
8 disjoint 8 MiB ranges 3.67 -> 3.71 ms 7.67 -> 7.54 ms
One 112 MiB range 8.11 -> 7.79 ms 13.97 -> 13.70 ms
1,024 out-of-order 32-byte ranges followed by their full 64 MiB span 10.33 -> 8.57 ms 7.61 -> 7.03 ms
Same fragmented case, with changes in 25% of pages 8.24 -> 7.53 ms 4.78 -> 6.21 ms

For the first case, the declarations are [(32-i) MiB, (64+3*i) MiB) for i=0..=16. The old capture builds 1,088 MiB of snapshots to keep 96 MiB. On the warmed pool this change appends the 96 MiB once. The fragmented, modified case shows the cost of gathering the old bytes for a changed page.

Pool growth after review

This capture-only check creates a fresh snapshot per sample. The mixed pool starts with touched 32 B, 4 KiB, 8 MiB and 64 MiB buffers. The growing-overlap test seeds additional 32 MiB and 128 MiB buffers. Medians of nine interleaved runs, with process page faults measured during capture.

Initial pool and input Main First PR commit With pooled growth
Mixed, 32 B followed by an enclosing 64 MiB range 3.47 ms / 0 faults 16.64 ms / 16,417 faults 3.37 ms / 0 faults
Empty, same input 15.46 ms / 16,417 faults 16.67 ms / 16,417 faults 17.53 ms / 16,417 faults
Mixed, growing overlap 118.19 ms / 82,084 faults 35.10 ms / 41,045 faults 12.07 ms / 0 faults
Mixed, one 64 MiB range 3.82 ms / 0 faults 3.85 ms / 0 faults 3.81 ms / 0 faults

SnapshotBytes and the per-shadow diagnostics now count newly captured bytes. Before, they counted the whole rebuilt span, including earlier bytes copied again. These counters exclude pool transfers and should be compared only within the same implementation.

Validation

  • New test covers an overlap that fills a hole, preserves previously captured bytes, handles fragmented comparison, and updates the baseline on refresh.
  • WARP copy-back test covers a changed page split across captures and checks that a full page goes back once.
  • cargo test --locked -p victory-gpu --lib --features diagnostics -- --test-threads=1 under WARP: 247 passed, 1 ignored.
  • Clippy with all targets and features and warnings denied passed. cargo xtask policy passed.

Coordination claim. No game files used. AI-assisted (Codex).

<!-- greyfinch-sync:Marvisak/VIctory:issue:5510498491 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3211). Originally posted by [yumaste](https://github.com/yumaste) on 2026-11-26T13:01:55Z. --- ## Problem A submission can declare overlapping writes to the same large GPU shadow. Whenever the covered range grows, `Shadow::writing` allocates or takes another buffer and copies the previous snapshot into it along with the new bytes. Repeated extensions recopy the same data before any GPU work runs. ## Change Keep the captured bytes in one pooled buffer and index disjoint ranges into it. Each declaration appends only bytes that have not been captured. Growth reuses a suitable touched pool buffer when available and returns the old one. The first checkout uses the shadow's last captured size as a preference, so repeated submissions can start in a warm buffer that already fits. Refreshes still update the baseline where the CPU has supplied newer values before submission. During copy-back, contiguous pieces are compared in place. A piece stored in several fragments is assembled only when the GPU changed it. ## Synthetic benchmark Windows x64, Core Ultra 9 275HX, Rust 1.98.1 with `-C opt-level=3`. Captured from a synthetic 128 MiB buffer. Timed the capture and comparison kernels from `main` and this branch with independent warmed pools, alternating run order and reusing the snapshot across modeled submissions. Medians of 16 runs per variant. Comparison skips duplicate full pieces as the copy-back loop does. These figures exclude D3D12 queue execution, synchronization, and the actual writes to guest memory. | Ranges | Capture before -> after | Comparison before -> after | | --- | ---: | ---: | | 17 overlapping ranges growing from 32 to 96 MiB | 56.93 -> 5.91 ms | 11.40 -> 10.80 ms | | 8 disjoint 8 MiB ranges | 3.67 -> 3.71 ms | 7.67 -> 7.54 ms | | One 112 MiB range | 8.11 -> 7.79 ms | 13.97 -> 13.70 ms | | 1,024 out-of-order 32-byte ranges followed by their full 64 MiB span | 10.33 -> 8.57 ms | 7.61 -> 7.03 ms | | Same fragmented case, with changes in 25% of pages | 8.24 -> 7.53 ms | 4.78 -> 6.21 ms | For the first case, the declarations are `[(32-i) MiB, (64+3*i) MiB)` for `i=0..=16`. The old capture builds 1,088 MiB of snapshots to keep 96 MiB. On the warmed pool this change appends the 96 MiB once. The fragmented, modified case shows the cost of gathering the old bytes for a changed page. ### Pool growth after review This capture-only check creates a fresh snapshot per sample. The mixed pool starts with touched 32 B, 4 KiB, 8 MiB and 64 MiB buffers. The growing-overlap test seeds additional 32 MiB and 128 MiB buffers. Medians of nine interleaved runs, with process page faults measured during capture. | Initial pool and input | Main | First PR commit | With pooled growth | | --- | ---: | ---: | ---: | | Mixed, 32 B followed by an enclosing 64 MiB range | 3.47 ms / 0 faults | 16.64 ms / 16,417 faults | 3.37 ms / 0 faults | | Empty, same input | 15.46 ms / 16,417 faults | 16.67 ms / 16,417 faults | 17.53 ms / 16,417 faults | | Mixed, growing overlap | 118.19 ms / 82,084 faults | 35.10 ms / 41,045 faults | 12.07 ms / 0 faults | | Mixed, one 64 MiB range | 3.82 ms / 0 faults | 3.85 ms / 0 faults | 3.81 ms / 0 faults | `SnapshotBytes` and the per-shadow diagnostics now count newly captured bytes. Before, they counted the whole rebuilt span, including earlier bytes copied again. These counters exclude pool transfers and should be compared only within the same implementation. ## Validation - New test covers an overlap that fills a hole, preserves previously captured bytes, handles fragmented comparison, and updates the baseline on refresh. - WARP copy-back test covers a changed page split across captures and checks that a full page goes back once. - `cargo test --locked -p victory-gpu --lib --features diagnostics -- --test-threads=1` under WARP: 247 passed, 1 ignored. - Clippy with all targets and features and warnings denied passed. `cargo xtask policy` passed. [Coordination claim](https://github.com/Marvisak/VIctory/issues/1633#issuecomment-7192669459). No game files used. AI-assisted (Codex).
Dukestar69 commented 2026-11-26 13:07:21 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Dukestar69 on 2026-11-26T13:07:21Z.

Review: APPROVED


Verified on RTX 5090 & WARP against origin/main (63bcca4):

  • cargo test -p victory-gpu --lib shadow:: -- --test-threads=1: 11/11 passed on RTX 5090 and WARP (including overlapping_snapshots_keep_old_bytes_until_a_refresh).
  • cargo clippy -p victory-gpu --all-targets -- -D warnings: clean.
  • cargo xtask policy: 191 files ok.

Cleanly appends only newly covered byte ranges to write snapshots while keeping prior bytes intact until refresh.

Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).

<!-- greyfinch-sync:Marvisak/VIctory:review:6074650361 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3211#pullrequestreview-6074650361). Originally posted by [Dukestar69](https://github.com/Dukestar69) on 2026-11-26T13:07:21Z. **Review:** APPROVED --- Verified on RTX 5090 & WARP against `origin/main` (`63bcca4`): - `cargo test -p victory-gpu --lib shadow:: -- --test-threads=1`: 11/11 passed on RTX 5090 and WARP (including `overlapping_snapshots_keep_old_bytes_until_a_refresh`). - `cargo clippy -p victory-gpu --all-targets -- -D warnings`: clean. - `cargo xtask policy`: 191 files ok. Cleanly appends only newly covered byte ranges to write snapshots while keeping prior bytes intact until refresh. Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).
AurumCarlos commented 2026-11-26 13:08:10 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by AurumCarlos on 2026-11-26T13:08:10Z.

Review: COMMENTED


Nice change. Capturing each byte once, with spans pointing into one buffer, is a much better shape than rebuilding the union on every extension, and the 62 → 6.6 ms on the growing-overlap case is the pattern that matters. I went through capture, covers, changed_piece and refresh:

  • capture walks the gaps correctly: it skips covered spans, inserts or extends at i, and only merges into the previous span when it is adjacent both in address and in the buffer, so a span's bytes always stay contiguous. The total stored is exactly the union of the declared ranges.
  • changed_piece relies on covers having been checked (it indexes self.spans[first] directly). copy_back_or_not does check it first, so that holds. A debug_assert!(self.covers(start, end)) at the top would document it.
  • refresh is equivalent to the old sync_before loop.

One concern, about the pool:

Growing the capture buffer bypasses the pool. capture takes a pooled buffer only when capacity() == 0, sized for the first declaration (pooled(host.len())). pooled returns the smallest pooled buffer that fits. So when a small range is declared first and a large one later (32-byte ranges then their 64 MiB span, in your fragmented case), the later extend_from_slice makes the Vec reallocate through the global allocator. That copies everything captured so far into fresh pages, and frees the old buffer instead of returning it to the pool. Fresh pages are exactly what POOL exists to avoid ("a page fault per 4 KiB touched", per give_back's comment). The old code asked the pool for the full union size on every growth.

The benchmark probably doesn't show this because the pools were warmed with large buffers, so even a 32-byte request got a big one. In a real frame, the pool also holds the smaller snapshots that earlier shadows gave back. Something like this would keep growth on pooled memory:

let need = host.len(); // an upper bound on what this call appends
if self.bytes.capacity() - self.bytes.len() < need {
    let mut grown = pooled(self.bytes.len() + need);
    grown.extend_from_slice(&self.bytes);
    let old = std::mem::replace(&mut self.bytes, grown);
    if old.capacity() != 0 {
        give_back(old);
    }
}

This would replace the capacity() == 0 check, and it costs one copy per growth, as before. A benchmark row with a cold-ish pool of mixed sizes (or a first declaration much smaller than the later ones) would show whether it matters.

A minor note: SnapshotBytes/copystat::snapshot now count only newly captured bytes, not the bytes copied to rebuild a segment. That's the more useful number, but diagnostics totals before and after this change aren't comparable, which might be worth a line in the description.

<!-- greyfinch-sync:Marvisak/VIctory:review:6074661193 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3211#pullrequestreview-6074661193). Originally posted by [AurumCarlos](https://github.com/AurumCarlos) on 2026-11-26T13:08:10Z. **Review:** COMMENTED --- Nice change. Capturing each byte once, with spans pointing into one buffer, is a much better shape than rebuilding the union on every extension, and the 62 → 6.6 ms on the growing-overlap case is the pattern that matters. I went through `capture`, `covers`, `changed_piece` and `refresh`: - `capture` walks the gaps correctly: it skips covered spans, inserts or extends at `i`, and only merges into the previous span when it is adjacent both in address *and* in the buffer, so a span's bytes always stay contiguous. The total stored is exactly the union of the declared ranges. - `changed_piece` relies on `covers` having been checked (it indexes `self.spans[first]` directly). `copy_back_or_not` does check it first, so that holds. A `debug_assert!(self.covers(start, end))` at the top would document it. - `refresh` is equivalent to the old `sync_before` loop. One concern, about the pool: **Growing the capture buffer bypasses the pool.** `capture` takes a pooled buffer only when `capacity() == 0`, sized for the *first* declaration (`pooled(host.len())`). `pooled` returns the *smallest* pooled buffer that fits. So when a small range is declared first and a large one later (32-byte ranges then their 64 MiB span, in your fragmented case), the later `extend_from_slice` makes the `Vec` reallocate through the global allocator. That copies everything captured so far into fresh pages, and frees the old buffer instead of returning it to the pool. Fresh pages are exactly what `POOL` exists to avoid ("a page fault per 4 KiB touched", per `give_back`'s comment). The old code asked the pool for the full union size on every growth. The benchmark probably doesn't show this because the pools were warmed with large buffers, so even a 32-byte request got a big one. In a real frame, the pool also holds the smaller snapshots that earlier shadows gave back. Something like this would keep growth on pooled memory: ```rust let need = host.len(); // an upper bound on what this call appends if self.bytes.capacity() - self.bytes.len() < need { let mut grown = pooled(self.bytes.len() + need); grown.extend_from_slice(&self.bytes); let old = std::mem::replace(&mut self.bytes, grown); if old.capacity() != 0 { give_back(old); } } ``` This would replace the `capacity() == 0` check, and it costs one copy per growth, as before. A benchmark row with a cold-ish pool of mixed sizes (or a first declaration much smaller than the later ones) would show whether it matters. A minor note: `SnapshotBytes`/`copystat::snapshot` now count only newly captured bytes, not the bytes copied to rebuild a segment. That's the more useful number, but diagnostics totals before and after this change aren't comparable, which might be worth a line in the description.
yumaste commented 2026-11-26 14:01:50 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by yumaste on 2026-11-26T13:12:56Z.


The mixed-pool case reproduced the regression. With a touched 64 MiB buffer available, the first version still incurred 16,417 process page faults when a 32-byte declaration was followed by a 64 MiB one. ebd01cd grows from the pool when possible and brings that back to zero on the same input (16.64 -> 3.37 ms). It uses the last captured size as the next submission's initial checkout preference. I added the debug assertion and updated the PR with warmed/mixed/empty-pool results and the change in diagnostic counters. All 247 GPU tests pass under WARP.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7193031448 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3211#issuecomment-7193031448). Originally posted by [yumaste](https://github.com/yumaste) on 2026-11-26T13:12:56Z. --- The mixed-pool case reproduced the regression. With a touched 64 MiB buffer available, the first version still incurred 16,417 process page faults when a 32-byte declaration was followed by a 64 MiB one. `ebd01cd` grows from the pool when possible and brings that back to zero on the same input (16.64 -> 3.37 ms). It uses the last captured size as the next submission's initial checkout preference. I added the debug assertion and updated the PR with warmed/mixed/empty-pool results and the change in diagnostic counters. All 247 GPU tests pass under WARP.
rezioliver-collab commented 2026-11-27 02:59:14 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by rezioliver-collab on 2026-11-27T02:59:14Z.


I extended the fragmented 64 MiB case on an Apple M1. I captured 1,024 out-of-order 32-byte ranges followed by the enclosing range, then flipped one byte on each selected 64 KiB page. Both revisions found exactly the selected pages and recovered every original byte on those pages.

Pages changed Byte offset 200, base → PR Last byte of page, base → PR
0% 6.13 → 5.05 ms 6.19 → 5.53 ms
25% 5.56 → 5.00 ms 5.98 → 5.52 ms
50% 5.11 → 4.94 ms 6.04 → 5.98 ms
100% 3.51 → 4.09 ms 6.22 → 6.47 ms

These are medians for capture plus comparison of the enclosing range, with independent warmed pools and 12 alternating pairs (base 63bcca43, PR ebd01cdd). At 50% the PR won 6/12 pairs at either offset. At 100% with the early byte it won 0/12, then 2/12 in a separate repeat. Gathering each changed page can outweigh the capture savings in that layout. The timing excludes guest writes and separate copy-backs of the small declarations.

AI-assisted with Codex.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7208602354 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3211#issuecomment-7208602354). Originally posted by [rezioliver-collab](https://github.com/rezioliver-collab) on 2026-11-27T02:59:14Z. --- I extended the fragmented 64 MiB case on an Apple M1. I captured 1,024 out-of-order 32-byte ranges followed by the enclosing range, then flipped one byte on each selected 64 KiB page. Both revisions found exactly the selected pages and recovered every original byte on those pages. | Pages changed | Byte offset 200, base → PR | Last byte of page, base → PR | | ---: | ---: | ---: | | 0% | 6.13 → 5.05 ms | 6.19 → 5.53 ms | | 25% | 5.56 → 5.00 ms | 5.98 → 5.52 ms | | 50% | 5.11 → 4.94 ms | 6.04 → 5.98 ms | | 100% | 3.51 → 4.09 ms | 6.22 → 6.47 ms | These are medians for capture plus comparison of the enclosing range, with independent warmed pools and 12 alternating pairs (base `63bcca43`, PR `ebd01cdd`). At 50% the PR won 6/12 pairs at either offset. At 100% with the early byte it won 0/12, then 2/12 in a separate repeat. Gathering each changed page can outweigh the capture savings in that layout. The timing excludes guest writes and separate copy-backs of the small declarations. AI-assisted with Codex.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/3211:upstream-pr/3211'
git switch 'upstream-pr/3211'

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.

git switch 'main'
git merge --no-ff 'upstream-pr/3211'
git switch 'upstream-pr/3211'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3211'
git switch 'upstream-pr/3211'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3211'
git switch 'main'
git merge --squash 'upstream-pr/3211'
git switch 'main'
git merge --ff-only 'upstream-pr/3211'
git switch 'main'
git merge 'upstream-pr/3211'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
Marvisak/VIctory!3209
No description provided.