Use pageable process memory for CPU-only GPU buffer mirrors #1823

Manually merged
github merged 3 commits from github-bot/gh-1823 into main 2026-11-29 08:20:37 +00:00 AGit
Owner

@⁠ihyajb on GitHub · 2026-11-29 00:28 UTC · original
ihyajb:perf/pageable-card-mirrors → main · +213 −66 · 4 files · 3 commits · merged 2026-11-29 08:16 UTC

Fixes #1815

What it changes

VICTORY_CARD_CPU_HEAP=1 gives the CPU mirror of a two-sided buffer ordinary pageable Windows memory. The GPU reads the submission’s immutable upload. Single-sided buffers, VICTORY_SEND_OWN=0, and the GPU upload checker retain their shared D3D12 resources. The switch defaults off. If the packed upload cannot be allocated, the fallback snapshots each affected shadow’s dirty ranges and retains those uploads through GPU retirement.

The original design is crossducking’s RAZDA4A-XEN 76b58130, carried by vix0e0e in VIctory-LITE e66dcc25 and adapted by advantyx in VIctyx 7f5497c8. This port adds the fallback and a byte-exact GPU readback regression test.

How it was tested

RTX 5070 12 GB, Windows 11, driver 621.40. The isolated test uses only the GPU library and synthetic data. It allocates eight persistent 32 MiB CPU mirrors, writes every byte, verifies a sentinel in each, and samples the process's DXGI nonlocal usage before allocation and while the mirrors are live. It checks the private-byte accounting again after release. Each measurement runs in a fresh process.

VICTORY_CARD_CPU_HEAP DXGI nonlocal before DXGI nonlocal with mirrors live Increase Private mirror bytes
0 22.96 MiB 284.74 MiB 261.78 MiB 0
1 22.96 MiB 22.96 MiB 0 MiB 256 MiB

Both orders (off/on, on/off) gave identical byte counts. With the switch on, Windows accounts for the mirror as ordinary process memory. The table measures DXGI accounting only.

Gameplay context. In the earlier paired comparison on upstream d4b5d517, both arms used the same 512 MiB upload segmentation. On Series S, 720p scene, DLSS Quality to 1080p, 2× DLSS FG and RT off, DXGI nonlocal usage at the engine's 240-FG-present checkpoint measured 6,540 MiB before and 4,572 MiB after. The two-minute settled samples averaged 26.52 and 27.04 base FPS at 4,172 and 4,131 draws/frame respectively. The evidence supports a shared-memory reduction; FPS remains inconclusive. The separate gameplay A/B on this exact branch stopped during the control run and produced no valid pair.

Reproduce the standalone measurement in PowerShell:

foreach ($setting in @('0','1','1','0')) {
    $env:VICTORY_CARD_CPU_HEAP = $setting
    cargo test --locked -p victory-gpu --lib shadow::land_tests::measure_cpu_mirror_nonlocal_usage -- --exact --ignored --nocapture --test-threads=1
}
Remove-Item Env:VICTORY_CARD_CPU_HEAP
  • Release build and staged asset-policy checks passed.
  • cargo test --locked -p victory-gpu passed (551 passed, 44 ignored). The suite includes a GPU readback of two partial dirty ranges with sentinel bytes between them and a CPU source changed before submission. The ignored DXGI measurement above was explicitly run four times.
  • No shader code changed. Both strict workspace Clippy configurations stop in unchanged victory-shader/src/emit/lower.rs (unused colour, manual checked division). The workspace test run reached the repository policy test, which rejects that same existing file at 667,523 bytes against a 655,360-byte limit.

Checked for overlap

  • Searched open PRs for the issue and touched files (shadow.rs, host.rs, host/send.rs, host/upcheck.rs), and checked the triage map in #1138. #1383, #1390 and #1391 concern oversized per-submission upload allocations. This PR changes who owns the persistent CPU-side copy.
**@⁠ihyajb** on GitHub · 2026-11-29 00:28 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/1823) `ihyajb:perf/pageable-card-mirrors` → `main` · +213 −66 · 4 files · 3 commits · merged 2026-11-29 08:16 UTC Fixes #1815 ## What it changes `VICTORY_CARD_CPU_HEAP=1` gives the CPU mirror of a two-sided buffer ordinary pageable Windows memory. The GPU reads the submission’s immutable upload. Single-sided buffers, `VICTORY_SEND_OWN=0`, and the GPU upload checker retain their shared D3D12 resources. The switch defaults off. If the packed upload cannot be allocated, the fallback snapshots each affected shadow’s dirty ranges and retains those uploads through GPU retirement. The original design is crossducking’s [RAZDA4A-XEN 76b58130](https://github.com/crossducking/RAZDA4A-XEN/commit/76b58130), carried by vix0e0e in [VIctory-LITE e66dcc25](https://github.com/vix0e0e/VIctory-LITE/commit/e66dcc25) and adapted by advantyx in [VIctyx 7f5497c8](https://github.com/advantyx/VIctyx/commit/7f5497c8e349e391764f24455718c3e77df22b5a). This port adds the fallback and a byte-exact GPU readback regression test. ## How it was tested **RTX 5070 12 GB, Windows 11, driver 621.40.** The isolated test uses only the GPU library and synthetic data. It allocates eight persistent 32 MiB CPU mirrors, writes every byte, verifies a sentinel in each, and samples the process's DXGI nonlocal usage before allocation and while the mirrors are live. It checks the private-byte accounting again after release. Each measurement runs in a fresh process. | `VICTORY_CARD_CPU_HEAP` | DXGI nonlocal before | DXGI nonlocal with mirrors live | Increase | Private mirror bytes | |---|---:|---:|---:|---:| | 0 | 22.96 MiB | 284.74 MiB | 261.78 MiB | 0 | | 1 | 22.96 MiB | 22.96 MiB | 0 MiB | 256 MiB | Both orders (off/on, on/off) gave identical byte counts. With the switch on, Windows accounts for the mirror as ordinary process memory. The table measures DXGI accounting only. **Gameplay context.** In the earlier paired comparison on upstream `d4b5d517`, both arms used the same 512 MiB upload segmentation. On Series S, 720p scene, DLSS Quality to 1080p, 2× DLSS FG and RT off, DXGI nonlocal usage at the engine's 240-FG-present checkpoint measured **6,540 MiB before** and **4,572 MiB after**. The two-minute settled samples averaged 26.52 and 27.04 base FPS at 4,172 and 4,131 draws/frame respectively. The evidence supports a shared-memory reduction; FPS remains inconclusive. The separate gameplay A/B on this exact branch stopped during the control run and produced no valid pair. **Reproduce the standalone measurement** in PowerShell: ```powershell foreach ($setting in @('0','1','1','0')) { $env:VICTORY_CARD_CPU_HEAP = $setting cargo test --locked -p victory-gpu --lib shadow::land_tests::measure_cpu_mirror_nonlocal_usage -- --exact --ignored --nocapture --test-threads=1 } Remove-Item Env:VICTORY_CARD_CPU_HEAP ``` - Release build and staged asset-policy checks passed. - `cargo test --locked -p victory-gpu` passed (551 passed, 44 ignored). The suite includes a GPU readback of two partial dirty ranges with sentinel bytes between them and a CPU source changed before submission. The ignored DXGI measurement above was explicitly run four times. - No shader code changed. Both strict workspace Clippy configurations stop in unchanged `victory-shader/src/emit/lower.rs` (unused `colour`, manual checked division). The workspace test run reached the repository policy test, which rejects that same existing file at 667,523 bytes against a 655,360-byte limit. ## Checked for overlap - [x] Searched open PRs for the issue and touched files (`shadow.rs`, `host.rs`, `host/send.rs`, `host/upcheck.rs`), and checked the triage map in #1138. #1383, #1390 and #1391 concern oversized per-submission upload allocations. This PR changes who owns the persistent CPU-side copy.
Credit crossducking/RAZDA4A-XEN 76b58130, vix0e0e/VIctory-LITE e66dcc25 and advantyx/VIctyx 7f5497c8. Preserve fallback dirty uploads through retirement and cover them with a GPU readback test.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-29 00:33:51 +00:00
Author
Owner

@⁠eleboucher on GitHub · 2026-11-29 01:41 UTC · original

On a 16 GB PC this PR fixes the shared-memory crash we get with the RT structure builder on.

Setup. RTX 4070 Ti SUPER 16 GB, Ryzen 7 9800X3D, 16 GB RAM, Windows 11 build 26300. Native 1440p, VICTORY_BVH_BUILDER=1 VICTORY_ACTIVATE_RAYS=1, diagnostics build. Base is main f9dfb76f + #1640 + #1700 (builder on 32 lanes), which merges clean with this PR and #477. Windows' shared-memory cap here is 7224 MB.

Without it. Each run of this base died at 2-10 min. Shared GPU memory reached 6.5-7.4 GB of 7224, then either a command list close failed with 0x8007000E or the device was removed. Settings tried without this PR, all with the builder on:

  • VICTORY_WINDOWS_BAR_MB=4608 / 6144, with and without TEXTURE_ROOM_PERCENT: died at 2-3 min.
  • WINDOW_KB=1024 WINDOW_TAILS=1 RT_FAULT_MB=384: died at 3 min.

With VICTORY_CARD_CPU_HEAP=1. The log shows CPU mirrors in pageable process memory private_mib=3483-3726. Shared memory stayed at 3.5-3.8 GB, and every leg was alive at 420 s:

leg 180 s 240 s 300 s 420 s shared
CARD_CPU_HEAP=1 10.8 fps 11.4 7.1 7.2 3.8 GB
+ #477 WINDOW_GROW=1 17.8 18.3 18.2 16.0 3.6 GB
+ RT_FAULT_MB=384 17.0 15.6 17.9 7.7 3.5 GB

Commit. It stays at 32-34 GB (it includes the card's 14 GB) with 0.3-0.5 GB of RAM free. The mirrors still use RAM, but Windows can now trim them instead of failing at the shared cap.

Suggestion. Consider turning this on by default on < 24 GiB hosts, as #1640 does for its caches. A 10-minute pair with captures is queued; I'll add the result.

**@⁠eleboucher** on GitHub · 2026-11-29 01:41 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/1823#issuecomment-7248953773) On a 16 GB PC this PR fixes the shared-memory crash we get with the RT structure builder on. **Setup.** RTX 4070 Ti SUPER 16 GB, Ryzen 7 9800X3D, 16 GB RAM, Windows 11 build 26300. Native 1440p, `VICTORY_BVH_BUILDER=1 VICTORY_ACTIVATE_RAYS=1`, diagnostics build. Base is main f9dfb76f + #1640 + #1700 (builder on 32 lanes), which merges clean with this PR and #477. Windows' shared-memory cap here is 7224 MB. **Without it.** Each run of this base died at 2-10 min. Shared GPU memory reached 6.5-7.4 GB of 7224, then either a command list close failed with 0x8007000E or the device was removed. Settings tried without this PR, all with the builder on: - `VICTORY_WINDOWS_BAR_MB=4608` / `6144`, with and without `TEXTURE_ROOM_PERCENT`: died at 2-3 min. - `WINDOW_KB=1024 WINDOW_TAILS=1 RT_FAULT_MB=384`: died at 3 min. **With `VICTORY_CARD_CPU_HEAP=1`.** The log shows `CPU mirrors in pageable process memory private_mib=3483-3726`. Shared memory stayed at 3.5-3.8 GB, and every leg was alive at 420 s: | leg | 180 s | 240 s | 300 s | 420 s | shared | |---|---|---|---|---|---| | CARD_CPU_HEAP=1 | 10.8 fps | 11.4 | 7.1 | 7.2 | 3.8 GB | | + #477 `WINDOW_GROW=1` | 17.8 | 18.3 | 18.2 | 16.0 | 3.6 GB | | + `RT_FAULT_MB=384` | 17.0 | 15.6 | 17.9 | 7.7 | 3.5 GB | **Commit.** It stays at 32-34 GB (it includes the card's 14 GB) with 0.3-0.5 GB of RAM free. The mirrors still use RAM, but Windows can now trim them instead of failing at the shared cap. **Suggestion.** Consider turning this on by default on `< 24 GiB` hosts, as #1640 does for its caches. A 10-minute pair with captures is queued; I'll add the result.
Author
Owner

@⁠eleboucher on GitHub · 2026-11-29 02:12 UTC · original

The 10-minute pair finished, with captures: same base, VICTORY_CARD_CPU_HEAP=1 VICTORY_WINDOW_GROW=1, RT structure builder on.

start 180 s 300 s 420 s 600 s shared at 600 s
1 14.5 fps 12.3 12.9 13.9 3650 MB
2 12.3 fps 10.3 14.0 9.2 3466 MB
  • Both were alive at 600 s, with 0 device removals and 0 failed list closes.
  • Picture check against the same base without this PR (frames paired by content): 2 of 614 pairs flagged, within our same-build noise. Violet 0.00% in every frame.
  • Now CPU-bound: the submit thread works ~63 ms of a ~80 ms frame.
**@⁠eleboucher** on GitHub · 2026-11-29 02:12 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/1823#issuecomment-7249277194) The 10-minute pair finished, with captures: same base, `VICTORY_CARD_CPU_HEAP=1 VICTORY_WINDOW_GROW=1`, RT structure builder on. | start | 180 s | 300 s | 420 s | 600 s | shared at 600 s | |---|---|---|---|---|---| | 1 | 14.5 fps | 12.3 | 12.9 | 13.9 | 3650 MB | | 2 | 12.3 fps | 10.3 | 14.0 | 9.2 | 3466 MB | - Both were alive at 600 s, with 0 device removals and 0 failed list closes. - Picture check against the same base without this PR (frames paired by content): 2 of 614 pairs flagged, within our same-build noise. Violet 0.00% in every frame. - Now CPU-bound: the submit thread works ~63 ms of a ~80 ms frame.
Author
Owner

@⁠upipibi on GitHub · 2026-11-29 02:37 UTC · original

Test report for #1823 (head 6b85f68d), merged --no-ff onto main 0338ec6c. Synthetic tests only: no title run, no
game files.

Setup: RTX 3070 8 GB, driver 616.56, Windows 11 (10.0.26100), rustc 1.98.1. WARP runs use
VICTORY_D3D12_WARP=1 with --features diagnostics. Every run logged the GPU and driver from nvidia-smi before
it started. A temporary print (not committed) showed the host device on "NVIDIA GeForce RTX 3070" for the hardware
runs and on "Microsoft Basic Render Driver" for the WARP runs.

host::upcheck::tests::private_upload_fallback_snapshots_only_dirty_bytes: 3/3 pass on hardware, 3/3 on WARP.
It reaches the device: it records the fallback's copies into a host list, runs it to the fence, and reads the
destination back.

Negative control: in snapshot_private_ranges, the dirty bytes are not copied into the fallback upload. The test
fails on hardware and on WARP at upcheck.rs:690:

  • got [204, 204, 0, 0, 0, 204, 204, 204, 204, 0, 0, 0, 0, 204, 204, 204];
  • expected [204, 204, 2, 3, 4, 204, 204, 204, 204, 9, 10, 11, 12, 204, 204, 204].

So the test catches a fallback that does not send the CPU's bytes. It also shows that only the two dirty ranges are
written.

shadow::land_tests::measure_cpu_mirror_nonlocal_usage (--ignored, one fresh process per setting, in the
PR's order 0, 1, 1, 0, hardware only):

VICTORY_CARD_CPU_HEAP DXGI nonlocal before With eight 32 MiB mirrors live Increase Private mirror bytes
0 22.77 MiB 284.54 MiB 261.78 MiB 0
1 22.77 MiB 22.77 MiB 0 MiB 256 MiB

Both runs of each setting gave the same bytes. The increase with the switch off and the zero increase with it on
match the PR's table on the RTX 5070 exactly. Only the starting point differs, by 0.19 MiB.

cargo test -p victory-gpu --lib --locked

Run PR Main 0338ec6c
default 590 passed, 0 failed, 45 ignored 589 passed, 0 failed, 44 ignored
--features diagnostics 644 passed, 0 failed, 45 ignored 643 passed, 0 failed, 44 ignored

The extra passed test is the upcheck test; the extra ignored one is the measurement. The suites ran with my
temporary probe as one more ignored test; it is subtracted here.

Not tested: the effect in a title.

Tested with the help of Claude Code (Claude Opus 5.5).

**@⁠upipibi** on GitHub · 2026-11-29 02:37 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/1823#issuecomment-7249547576) Test report for #1823 (head 6b85f68d), merged `--no-ff` onto main 0338ec6c. Synthetic tests only: no title run, no game files. **Setup:** RTX 3070 8 GB, driver 616.56, Windows 11 (10.0.26100), rustc 1.98.1. WARP runs use `VICTORY_D3D12_WARP=1` with `--features diagnostics`. Every run logged the GPU and driver from `nvidia-smi` before it started. A temporary print (not committed) showed the host device on "NVIDIA GeForce RTX 3070" for the hardware runs and on "Microsoft Basic Render Driver" for the WARP runs. **`host::upcheck::tests::private_upload_fallback_snapshots_only_dirty_bytes`: 3/3 pass on hardware, 3/3 on WARP.** It reaches the device: it records the fallback's copies into a host list, runs it to the fence, and reads the destination back. **Negative control:** in `snapshot_private_ranges`, the dirty bytes are not copied into the fallback upload. The test fails on hardware and on WARP at `upcheck.rs:690`: - got `[204, 204, 0, 0, 0, 204, 204, 204, 204, 0, 0, 0, 0, 204, 204, 204]`; - expected `[204, 204, 2, 3, 4, 204, 204, 204, 204, 9, 10, 11, 12, 204, 204, 204]`. So the test catches a fallback that does not send the CPU's bytes. It also shows that only the two dirty ranges are written. **`shadow::land_tests::measure_cpu_mirror_nonlocal_usage`** (`--ignored`, one fresh process per setting, in the PR's order 0, 1, 1, 0, hardware only): | `VICTORY_CARD_CPU_HEAP` | DXGI nonlocal before | With eight 32 MiB mirrors live | Increase | Private mirror bytes | |---|---:|---:|---:|---:| | 0 | 22.77 MiB | 284.54 MiB | 261.78 MiB | 0 | | 1 | 22.77 MiB | 22.77 MiB | 0 MiB | 256 MiB | Both runs of each setting gave the same bytes. The increase with the switch off and the zero increase with it on match the PR's table on the RTX 5070 exactly. Only the starting point differs, by 0.19 MiB. **`cargo test -p victory-gpu --lib --locked`** | Run | PR | Main 0338ec6c | |---|---|---| | default | 590 passed, 0 failed, 45 ignored | 589 passed, 0 failed, 44 ignored | | `--features diagnostics` | 644 passed, 0 failed, 45 ignored | 643 passed, 0 failed, 44 ignored | The extra passed test is the upcheck test; the extra ignored one is the measurement. The suites ran with my temporary probe as one more ignored test; it is subtracted here. Not tested: the effect in a title. *Tested with the help of Claude Code (Claude Opus 5.5).*
Author
Owner

@⁠pickles976 on GitHub · 2026-11-29 03:30 UTC · original

Linux/Wine follow-through on the RTX 4060 Laptop 8 GiB / 16 GiB host: I backported the private-mirror mechanism from 6b85f68d5cc6e014fd5bc878397ae355fdb3017b onto our older rendered Wine-support stack, rather than replacing its renderer with current main. Exact local implementation: 057bdd79, based on Wine PR #1226 plus a separate completed-send-pool cap. This is not an exact-head #1823 test.

Three isolated checks pass on physical NVIDIA hardware, Wine 11 / Linux 6.17 / NVIDIA 590.48.1 / stock assertion-enabled vkd3d-proton 2576c0b4adfae4a:

  • Production private mirror: real title allocation/lookup yields no CPU-side D3D12 resource; 4 MiB private counter rises and returns to zero after release; partial refresh/send GPU readback and untouched sentinels pass (0.85 s).
  • Fallback-copy helper: dirty byte ranges are snapshotted before source mutation; GPU readback preserves those bytes and untouched sentinels (0.59 s). This is not actual packed-upload OOM injection or an end-to-end failed-retirement test.
  • Existing 128 KiB disk-backed alias/GPU-copy fixture still passes all-word checks across three CPU-update/writeback rounds (0.71 s). Native imports of disk-backed title memory remain disabled.

A guarded title observation at 2026-11-29 02:47:08 UTC reached an actual captured cutscene with characters, geometry and colour. The capture remains local. Logical private mirrors reached about 1004 MiB; this is not residency. All 320 independent persistent-NVML memory queries completed, with max native query time 451 ms, and the original nvidia-smi safety guard remained active. The run stopped on global GPU use 6005 MiB at317.53 s, not a telemetry timeout or title crash. Kernel interval had no entries; no cgroup OOM. Minimum available RAM3737.7 MiB, scope peak9216 MiB with452 cap events. Earlier configurations did encounter telemetry deadlines; different input/cache/progress conditions prohibit claiming this patch alone fixed them.

Performance is still poor: eight high-draw host reports had median2.25 FPS/460.1 ms per frame, with253 ms preparing and164.35 ms copying/refreshing101.15 MB. These are overlapping host counters, not GPU timestamps or a matched A/B. Scene-aligned I/O-full pressure remained roughly18–19%; controllable gameplay, native30 FPS and long-run stability are unverified.

Useful implementation detail: this older fork already used CPU WRITE_BACK for shared buffers, so I am not attributing a CPU cache-mode speedup to VirtualAlloc. The current benefit under investigation is ownership/pageability and reduced driver-managed host memory, not disappearance of the mirror bytes. Our next controlled setting is the existing80% texture-admission line, with unchanged resolution, rendering exclusions, native-import prohibition and all safety limits.

**@⁠pickles976** on GitHub · 2026-11-29 03:30 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/1823#issuecomment-7250087558) Linux/Wine follow-through on the RTX 4060 Laptop 8 GiB / 16 GiB host: I backported the private-mirror mechanism from `6b85f68d5cc6e014fd5bc878397ae355fdb3017b` onto our older rendered Wine-support stack, rather than replacing its renderer with current main. Exact local implementation: [057bdd79](https://github.com/pickles976/VIctory-NVIDIA/commit/057bdd79ddefcb680fd1cc6386556301a6eee549), based on Wine PR #1226 plus a separate completed-send-pool cap. This is not an exact-head #1823 test. Three isolated checks pass on physical NVIDIA hardware, Wine 11 / Linux 6.17 / NVIDIA 590.48.1 / stock assertion-enabled vkd3d-proton `2576c0b4adfae4a`: - Production private mirror: real title allocation/lookup yields no CPU-side D3D12 resource; 4 MiB private counter rises and returns to zero after release; partial refresh/send GPU readback and untouched sentinels pass (0.85 s). - Fallback-copy helper: dirty byte ranges are snapshotted before source mutation; GPU readback preserves those bytes and untouched sentinels (0.59 s). This is not actual packed-upload OOM injection or an end-to-end failed-retirement test. - Existing 128 KiB disk-backed alias/GPU-copy fixture still passes all-word checks across three CPU-update/writeback rounds (0.71 s). Native imports of disk-backed title memory remain disabled. A guarded title observation at 2026-11-29 02:47:08 UTC reached an actual captured cutscene with characters, geometry and colour. The capture remains local. Logical private mirrors reached about 1004 MiB; this is not residency. All 320 independent persistent-NVML memory queries completed, with max native query time 451 ms, and the original nvidia-smi safety guard remained active. The run stopped on **global GPU use 6005 MiB** at317.53 s, not a telemetry timeout or title crash. Kernel interval had no entries; no cgroup OOM. Minimum available RAM3737.7 MiB, scope peak9216 MiB with452 cap events. Earlier configurations did encounter telemetry deadlines; different input/cache/progress conditions prohibit claiming this patch alone fixed them. Performance is still poor: eight high-draw host reports had median2.25 FPS/460.1 ms per frame, with253 ms preparing and164.35 ms copying/refreshing101.15 MB. These are overlapping host counters, not GPU timestamps or a matched A/B. Scene-aligned I/O-full pressure remained roughly18–19%; controllable gameplay, native30 FPS and long-run stability are unverified. Useful implementation detail: this older fork already used CPU WRITE_BACK for shared buffers, so I am not attributing a CPU cache-mode speedup to VirtualAlloc. The current benefit under investigation is ownership/pageability and reduced driver-managed host memory, not disappearance of the mirror bytes. Our next controlled setting is the existing80% texture-admission line, with unchanged resolution, rendering exclusions, native-import prohibition and all safety limits.
Author
Owner

@⁠ArturoWolff on GitHub · 2026-11-29 06:55 UTC · original · edited 2026-11-29 07:14 UTC

Independent Linux/Proton validation of the exact #1823 diff (6b85f68d5cc6e014fd5bc878397ae355fdb3017b) applied to 568c5e5d2b19f97a9e5562c0e6923581eb6fa360. All four receiving files were byte-identical to the PR base, so the diff applied unchanged. Credits to the authors and original implementation lineage documented in the PR.

RTX 4060 desktop 8 GB, 16 GB system RAM, NVIDIA 620.73.04, GE-Proton11-14 / vkd3d-proton 3.2.0 (cae8353ed7959c4+), locked MSVC release test build. Separate fresh prefixes and processes, physical NVIDIA adapter enumerated, VICTORY_SEND_OWN=1 VICTORY_UPCOPY_CHECK=0; no title data mounted.

VICTORY_CARD_CPU_HEAP Nonlocal before (bytes) Nonlocal live (bytes) Increase (MiB) Private mirror bytes
0 34,816,000 336,805,888 288 0
1 34,816,000 34,816,000 0 268,435,456

shadow::land_tests::measure_cpu_mirror_nonlocal_usage: both explicit ignored invocations passed, including retained sentinels and release accounting (1.11 / 1.09 s). host::upcheck::tests::private_upload_fallback_snapshots_only_dirty_bytes also returned one passed test in 0.87 s with D3D12 backend initialization logged; the existing test has an early return if host creation fails, so I do not claim a separately instrumented no-skip witness. All three Windows child exits and outer exits were 0, no guard stop or kernel fault.

This independently supports the DXGI nonlocal accounting effect under our Proton backend. It does not mean 288 MiB of physical host RAM disappears, and does not by itself establish physical memory savings in a title. Our recent ordinary game runs have severe host pressure, including a separately confirmed kernel OOM (#628), so the next title comparison needs adequate initial headroom and matched settings/cache conditions.

Subsequent title startup comparison (same candidate executable, fresh prefixes and external caches, same retained game-generated profile, requested RT/effects unchanged):

VICTORY_CARD_CPU_HEAP Starting available RAM Peak cgroup memory.peak Max sampled cgroup swap Max physical zram Outcome
1 9.68 GiB 8.55 GiB 9.63 GiB 5.48 GiB Black screen, exit 5
0 10.01 GiB 8.16 GiB 9.09 GiB 5.68 GiB Black screen, observer failure stopped scope early

The enabled arm logged 174 MiB of private mirrors; the disabled arm did not. Both scopes retired, no floor stop or confirmed kernel OOM/Xid in either interval. The control's observer failed and the run ended earlier, so this is not a valid matched pair for peak memory or FPS. Both runs still failed to reach visible gameplay. Our synthetic DXGI accounting observation stands; this title startup evidence does not establish a real host-RAM reduction, a ray-tracing correctness improvement, or a startup fix. I am retaining the diagnostic result rather than promoting the candidate on the basis of the synthetic test.

AI assistance: Hermes Agent, working on behalf of ArturoWolff. (GPT 6.2 Sol High).

**@⁠ArturoWolff** on GitHub · 2026-11-29 06:55 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/1823#issuecomment-7252155128) · edited 2026-11-29 07:14 UTC Independent Linux/Proton validation of the exact #1823 diff (`6b85f68d5cc6e014fd5bc878397ae355fdb3017b`) applied to `568c5e5d2b19f97a9e5562c0e6923581eb6fa360`. All four receiving files were byte-identical to the PR base, so the diff applied unchanged. Credits to the authors and original implementation lineage documented in the PR. RTX 4060 desktop 8 GB, 16 GB system RAM, NVIDIA 620.73.04, GE-Proton11-14 / vkd3d-proton 3.2.0 (`cae8353ed7959c4+`), locked MSVC release test build. Separate fresh prefixes and processes, physical NVIDIA adapter enumerated, `VICTORY_SEND_OWN=1 VICTORY_UPCOPY_CHECK=0`; no title data mounted. | `VICTORY_CARD_CPU_HEAP` | Nonlocal before (bytes) | Nonlocal live (bytes) | Increase (MiB) | Private mirror bytes | | --- | ---: | ---: | ---: | ---: | | 0 | 34,816,000 | 336,805,888 | 288 | 0 | | 1 | 34,816,000 | 34,816,000 | 0 | 268,435,456 | `shadow::land_tests::measure_cpu_mirror_nonlocal_usage`: both explicit ignored invocations passed, including retained sentinels and release accounting (1.11 / 1.09 s). `host::upcheck::tests::private_upload_fallback_snapshots_only_dirty_bytes` also returned one passed test in 0.87 s with D3D12 backend initialization logged; the existing test has an early return if host creation fails, so I do not claim a separately instrumented no-skip witness. All three Windows child exits and outer exits were 0, no guard stop or kernel fault. This independently supports the DXGI nonlocal accounting effect under our Proton backend. It does **not** mean 288 MiB of physical host RAM disappears, and does not by itself establish physical memory savings in a title. Our recent ordinary game runs have severe host pressure, including a separately confirmed kernel OOM (#628), so the next title comparison needs adequate initial headroom and matched settings/cache conditions. **Subsequent title startup comparison (same candidate executable, fresh prefixes and external caches, same retained game-generated profile, requested RT/effects unchanged):** | `VICTORY_CARD_CPU_HEAP` | Starting available RAM | Peak cgroup `memory.peak` | Max sampled cgroup swap | Max physical zram | Outcome | | --- | ---: | ---: | ---: | ---: | --- | | 1 | 9.68 GiB | 8.55 GiB | 9.63 GiB | 5.48 GiB | Black screen, exit 5 | | 0 | 10.01 GiB | 8.16 GiB | 9.09 GiB | 5.68 GiB | Black screen, observer failure stopped scope early | The enabled arm logged 174 MiB of private mirrors; the disabled arm did not. Both scopes retired, no floor stop or confirmed kernel OOM/Xid in either interval. The control's observer failed and the run ended earlier, so this is **not a valid matched pair for peak memory or FPS**. Both runs still failed to reach visible gameplay. Our synthetic DXGI accounting observation stands; this title startup evidence does not establish a real host-RAM reduction, a ray-tracing correctness improvement, or a startup fix. I am retaining the diagnostic result rather than promoting the candidate on the basis of the synthetic test. AI assistance: Hermes Agent, working on behalf of ArturoWolff. (GPT 6.2 Sol High).
github manually merged commit f5fa635f5f into main 2026-11-29 08:20:37 +00:00
Author
Owner

@⁠NotADonky43 on GitHub · 2026-11-29 10:10 UTC · original

Follow-up to the pageable mirror: for private 64 MiB RT arenas only, avoid allocating the second full mirror rather than changing its memory class. Opt in with VICTORY_RT_SPARSE_STAGE=1. Keep one CPU reference, store 4 KiB pending edits, compare final values at publication, and use existing immutable uploads/fallback. Explicit resends remain full. The directory, title-owned windows, and upcheck are unchanged.

Two candidate openings on the cumulative port omitted 832 and 1,088 MiB of persistent staging capacity; pending payload peaks were 107.5 and 109.8 MiB. These are allocator payloads, not net system savings. Overall private peaks and shared peaks varied in opposite directions across the two pairs. Original shaders, warmed pipelines, 4 GiB BAR, RTX 5070 Ti. No FPS or image parity claim. The focused native readback test on current main plus this patch passed with both SEND_OWN=1 and 0, covering adjacent GPU data, reversion, resends and later CPU preparation.

Source-only patch against 829188e9; our fork push based on this main was blocked by workflow scope.

Patch with native regression (git apply)
diff --git a/crates/victory-gpu/src/host/send.rs b/crates/victory-gpu/src/host/send.rs
index b9bb2575..985a17d6 100644
--- a/crates/victory-gpu/src/host/send.rs
+++ b/crates/victory-gpu/src/host/send.rs
@@ -666,3 +666,38 @@ mod tests {
         assert_eq!(actual, expected, "changed words and untouched neighbors");
     }
 }
+
+/// A partial CPU update after the card has written the neighbouring word must
+/// not restore the old CPU value; a reverted edit must not send that word either.
+#[test]
+#[ignore = "requires an isolated D3D12 host and VICTORY_RT_SPARSE_STAGE=1"]
+fn sparse_rt_arena_preserves_gpu_neighbours_and_snapshot_order() {
+    let host = host().expect("D3D12 host");
+    let n = 64 << 20;
+    let at = crate::upload::reserve(n).unwrap();
+    let s = crate::shadow::private_arena(at as u64, n as u64).unwrap();
+    assert!(s.sparse_arena() && s.card_sides().unwrap().0.is_none());
+    let mut rig = crate::inplace::Rig::new(&host.device).unwrap();
+    let submit = || host.card_before(&[], &Default::default(), false).unwrap();
+    let finish = |plan| unsafe {
+        let fence: ID3D12Fence = host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
+        host.queue().Signal(&fence, 1).unwrap();
+        fence.SetEventOnCompletion(1, HANDLE::default()).unwrap();
+        assert_eq!(fence.GetCompletedValue(),1);
+        host.card_done(plan);
+    };
+    s.edit_arena(0, &[1u8;4096]); s.resend(0,4096); s.update(at,n); finish(submit());
+    let mut expected = vec![1u8;4096];
+    rig.store(&s.buffer, 4, &[0x99;4]).unwrap(); expected[4..8].fill(0x99);
+    s.edit_arena(0,&[7;4]); s.edit_arena(4,&[88;4]); s.edit_arena(4,&[1;4]);
+    s.edit_arena(64,&[11;512]); s.update(at,n);
+    let first=submit();
+    // Prepare the next CPU version while the first upload can still be live.
+    s.edit_arena(0,&[0x44;4]); s.update(at,n); finish(first);
+    expected[..4].fill(7); expected[64..576].fill(11);
+    assert_eq!(rig.fetch(&s.buffer,0,4096).unwrap(),expected);
+    finish(submit()); expected[..4].fill(0x44);
+    assert_eq!(rig.fetch(&s.buffer,0,4096).unwrap(),expected);
+    s.resend(4,8); s.update(at,n); finish(submit()); expected[4..8].fill(1);
+    assert_eq!(rig.fetch(&s.buffer,0,4096).unwrap(),expected);
+}
diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs
index b6f93925..3f2eef64 100644
--- a/crates/victory-gpu/src/memory.rs
+++ b/crates/victory-gpu/src/memory.rs
@@ -601,7 +601,7 @@ impl Memory {
         // write told: the kernel is not asked about 64 MiB for each list
         // that brings the arenas up to date.
         crate::watch::own(at, ARENA as usize);
-        let Some(n) = crate::shadow::by_address(at as u64, ARENA).and_then(|s| self.number(s)) else {
+        let Some(n) = crate::shadow::private_arena(at as u64, ARENA).and_then(|s| self.number(s)) else {
             failed(1);
             crate::watch::disown(at);
             // SAFETY: the reservation just made, which nothing else knows of.
@@ -810,6 +810,7 @@ impl Memory {
                 let from = (page * PAGE) as usize + piece;
                 // (Pages that are not there read as zeros.)
                 crate::host::copy_mapped(title.as_mut_ptr(), from as *const u8, PIECE, false);
+                if shadow.sparse_arena() { self.stats.changed += shadow.edit_arena(base + piece, &title) as u64; continue; }
                 // SAFETY: a page of an arena of ours, under the mutex.
                 let ours = unsafe { std::slice::from_raw_parts_mut((held.at + piece) as *mut u8, PIECE) };
                 let changed = merge(&title, ours, never);
@@ -925,6 +926,7 @@ impl Memory {
             let n = (PIECE - at % PIECE).min(to - at);
             crate::host::copy_mapped(title.as_mut_ptr(), (page as usize * PAGE as usize + at) as *const u8, n, false);
             // SAFETY: a page of an arena of ours, under the mutex.
+            if shadow.sparse_arena() { shadow.edit_arena(base + at, &title[..n]); at += n; continue; }
             let ours = unsafe { std::slice::from_raw_parts_mut((held.at + at) as *mut u8, n) };
             if *ours != title[..n] {
                 ours.copy_from_slice(&title[..n]);
@@ -1058,6 +1060,9 @@ impl Memory {
         }
         let frames = self.frame.wrapping_sub(frame).max(1) as f64;
         let s = std::mem::take(&mut self.stats);
+        if self.arenas.first().is_some_and(|a| self.copies[a.0].sparse_arena()) {
+            tracing::info!(omitted_bytes=self.arenas.len() as u64 * ARENA, pending_peak_bytes=crate::shadow::arena_edit_peak(), "RT arena staging capacity");
+        }
         let (on_card, spilled, most) = crate::shadow::arena_bytes();
         let ms = |(_, nanos): (u64, u64)| nanos as f64 / 1e6 / frames;
         let calls = |(calls, _): (u64, u64)| calls as f64 / frames;
diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs
index 0c572f4e..795e8aaa 100644
--- a/crates/victory-gpu/src/shadow.rs
+++ b/crates/victory-gpu/src/shadow.rs
@@ -15,6 +15,8 @@
 //! descriptors, buffer views in tables); buffers read through directly
 //! indexed heaps keep what their first use copied.
 
+mod arena_edits;
+pub(crate) fn arena_edit_peak() -> usize { arena_edits::peak() }
 use std::collections::BTreeMap;
 use std::sync::atomic::{AtomicU8, AtomicU64, AtomicUsize, Ordering};
 use std::sync::{Arc, Mutex, RwLock};
@@ -35,6 +37,7 @@ pub(crate) struct Shadow {
     /// The bytes of `buffer`, once asked.
     width: std::sync::OnceLock<u64>,
     pub(crate) buffer: ID3D12Resource,
+    arena_edits: Option<Box<arena_edits::Edits>>,
     data: *mut u8,
     gpu: u64,
     /// Where the title buffer starts and how long it is.
@@ -129,6 +132,8 @@ pub(crate) struct Shadow {
 /// shadow's CPU mirror can use pageable process memory. Single-sided buffers
 /// and the upload checker still need a D3D12 resource.
 enum CardCpu {
+    /// Uses Memory’s private arena as the last published CPU version.
+    Arena,
     Shared(ID3D12Resource),
     Private { address: usize, size: u64 },
 }
@@ -155,7 +160,7 @@ impl CardCpu {
     }
 
     fn shared(&self) -> Option<&ID3D12Resource> {
-        match self { Self::Shared(buffer) => Some(buffer), Self::Private { .. } => None }
+        match self { Self::Shared(buffer) => Some(buffer), Self::Private { .. } | Self::Arena => None }
     }
 }
 
@@ -5154,7 +5159,7 @@ impl Shadow {
     /// kernel would refuse (and with it the ranges asked about together).
     pub(crate) fn asked_ahead(&self) -> bool {
         let watched = self.watched.load(Ordering::Relaxed);
-        watched != NOT_WATCHED && (watched != GUARDED || !crate::watch::light())
+        !self.sparse_arena() && watched != NOT_WATCHED && (watched != GUARDED || !crate::watch::light())
     }
 
     /// The copy's own number (see the field).
@@ -5260,6 +5265,7 @@ impl Shadow {
             width: Default::default(),
             buffer,
             data,
+            arena_edits: None,
             gpu,
             start,
             len,
@@ -6191,6 +6197,7 @@ impl Shadow {
     }
 
     fn update_ranges(&self, address: usize, len: usize) -> usize {
+        if self.sparse_arena() { return self.publish_arena_edits(address, len); }
         // In place: the card reads title memory itself.
         if self.place.is_some() {
             return 0;
@@ -6232,6 +6239,7 @@ impl Shadow {
     /// nothing, and knows it without asking anything
     /// (`crate::watch::nothing_new`). `false` if it would have to ask.
     pub(crate) fn nothing_new(&self, address: usize, len: usize) -> bool {
+        if let Some(e) = &self.arena_edits { return e.empty(); }
         if self.place.is_some() {
             return true;
         }
@@ -6775,6 +6783,7 @@ impl Shadow {
 
     /// Offsets `[from, to)` go up again whole, as the CPU's side has them.
     pub(crate) fn resend(&self, from: usize, to: usize) {
+        if let Some(e) = &self.arena_edits { e.force(from,to); return; }
         self.card_changed(from, to);
     }
 
@@ -8203,6 +8212,15 @@ pub(crate) fn small_buffer_in(address: u64, len: u64, most: u64) -> bool {
 /// the only place that has it. The CPU's side holds the bytes as they were
 /// last taken, and only dwords that changed since go up.
 pub(crate) fn by_address(start: u64, len: u64) -> Option<Arc<Shadow>> {
+    by_address_inner(start, len, false)
+}
+
+/// Only the private zeroed allocation owned by Memory, never title bytes.
+pub(crate) fn private_arena(start: u64, len: u64) -> Option<Arc<Shadow>> {
+    by_address_inner(start, len, !crate::host::upcheck::on() && std::env::var_os("VICTORY_RT_SPARSE_STAGE").is_some_and(|v| v == "1"))
+}
+
+fn by_address_inner(start: u64, len: u64, sparse: bool) -> Option<Arc<Shadow>> {
     let host = host()?;
     if !cards() || !host.card_ready() {
         return None;
@@ -8210,7 +8228,7 @@ pub(crate) fn by_address(start: u64, len: u64) -> Option<Arc<Shadow>> {
     // At most `arena_card_most` on the card's own memory, and while the card has room for it
     // ([`crate::resource::card_copy_fits`]); past that the side shaders see is in the PC's memory.
     let room = host.video_memory().is_none_or(|[budget, used, ..]| crate::resource::card_copy_fits(budget, used, len));
-    let (staging, data) = CardCpu::allocate(len)?;
+    let (staging, data) = if sparse { (CardCpu::Arena, start as *mut u8) } else { CardCpu::allocate(len)? };
     let on_card = if room && take_under(&ARENA_CARD_BYTES, len, arena_card_most()) {
         let made = host.uav_buffer(len);
         if made.is_none() {
@@ -8234,6 +8252,7 @@ pub(crate) fn by_address(start: u64, len: u64) -> Option<Arc<Shadow>> {
     // SAFETY: a live buffer.
     let gpu = unsafe { buffer.GetGPUVirtualAddress() };
     let mut shadow = Shadow::new(buffer, data, gpu, start, len);
+    shadow.arena_edits = sparse.then(Box::default);
     shadow.window = true;
     shadow.changes_only.store(true, Ordering::Relaxed);
     shadow.card = Some(Card {
diff --git a/crates/victory-gpu/src/shadow/arena_edits.rs b/crates/victory-gpu/src/shadow/arena_edits.rs
new file mode 100644
index 00000000..70ccbbf4
--- /dev/null
+++ b/crates/victory-gpu/src/shadow/arena_edits.rs
@@ -0,0 +1,63 @@
+//! Copy-on-write input for the memory manager's private RT arenas. The low CPU
+//! allocation is the last published CPU version (not a mirror of GPU writes).
+//! Recording only edits pending chunks. Submission alone publishes them and
+//! uploads through the ordinary fenced, immutable send path.
+use super::*;
+const CHUNK: usize = 4096;
+static LIVE: AtomicUsize = AtomicUsize::new(0);
+static HIGH: AtomicUsize = AtomicUsize::new(0);
+pub(super) fn peak() -> usize { HIGH.load(Ordering::Relaxed) }
+#[derive(Default)]
+struct Pending { chunks: BTreeMap<usize, Box<[u8]>>, force: Vec<(usize,usize)> }
+#[derive(Default)]
+pub(super) struct Edits(Mutex<Pending>);
+impl Edits {
+    pub(super) fn empty(&self) -> bool {
+        let p=self.0.lock().unwrap_or_else(|e|e.into_inner());
+        p.chunks.is_empty() && p.force.is_empty()
+    }
+    pub(super) fn force(&self, from:usize,to:usize) {
+        let mut p=self.0.lock().unwrap_or_else(|e|e.into_inner());
+        push_dirty_runs(&mut p.force, [(from,to)]);
+    }
+}
+impl Drop for Edits { fn drop(&mut self) { LIVE.fetch_sub(self.0.get_mut().unwrap_or_else(|e|e.into_inner()).chunks.len()*CHUNK, Ordering::Relaxed); } }
+impl Shadow {
+    pub(crate) fn sparse_arena(&self)->bool { self.arena_edits.is_some() }
+    pub(crate) fn edit_arena(&self, at:usize, bytes:&[u8])->usize {
+        let mut pending=self.arena_edits.as_ref().unwrap().0.lock().unwrap_or_else(|e|e.into_inner());
+        let base=at/CHUNK*CHUNK; let off=at-base;
+        assert!(off+bytes.len()<=CHUNK && base+CHUNK<=self.len as usize);
+        // SAFETY: the private arena is live, and its only writer holds this lock.
+        let published=unsafe{std::slice::from_raw_parts(self.data.add(base),CHUNK)};
+        let current=pending.chunks.get(&base).map_or(published,|b|&**b);
+        if &current[off..off+bytes.len()]==bytes { return 0; }
+        let chunk=pending.chunks.entry(base).or_insert_with(||{
+            let n=LIVE.fetch_add(CHUNK,Ordering::Relaxed)+CHUNK; HIGH.fetch_max(n,Ordering::Relaxed); published.into()
+        });
+        chunk[off..off+bytes.len()].copy_from_slice(bytes); bytes.len()
+    }
+    pub(super) fn publish_arena_edits(&self,address:usize,len:usize)->usize {
+        let (lo,hi)=self.inside(address,len);
+        if hi<=lo { return 0; }
+        let mut pending=self.arena_edits.as_ref().unwrap().0.lock().unwrap_or_else(|e|e.into_inner());
+        let mut runs=Vec::new();
+        for (&base, data) in pending.chunks.range(lo/CHUNK*CHUNK..hi) {
+            let a=lo.max(base); let b=hi.min(base+CHUNK);
+            // SAFETY: this is an exclusively CPU-owned arena. This lock excludes
+            // pending writers; the submission thread finishes all refreshes before staging.
+            let dest=unsafe{std::slice::from_raw_parts_mut(self.data.add(a),b-a)};
+            let src=&data[a-base..b-base];
+            for (off,n) in word_runs(a,src,dest) {
+                dest[off..off+n].copy_from_slice(&src[off..off+n]);runs.push((a+off,a+off+n));
+            }
+        }
+        let count=pending.chunks.len();pending.chunks.retain(|&base,_| base<lo || base+CHUNK>hi);
+        LIVE.fetch_sub((count-pending.chunks.len())*CHUNK,Ordering::Relaxed);
+        for (a,b) in std::mem::take(&mut pending.force) {
+            if b<=lo || a>=hi {pending.force.push((a,b));continue}
+            runs.push((a.max(lo),b.min(hi))); if a<lo {pending.force.push((a,lo))} if b>hi {pending.force.push((hi,b))}
+        }
+        let runs=joined(runs);let count=runs.iter().map(|(a,b)|b-a).sum(); self.card_changed_runs(runs.into_iter());count
+    }
+}

**@⁠NotADonky43** on GitHub · 2026-11-29 10:10 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/1823#issuecomment-7254261508) Follow-up to the pageable mirror: for private 64 MiB RT arenas only, avoid allocating the second full mirror rather than changing its memory class. Opt in with VICTORY_RT_SPARSE_STAGE=1. Keep one CPU reference, store 4 KiB pending edits, compare final values at publication, and use existing immutable uploads/fallback. Explicit resends remain full. The directory, title-owned windows, and upcheck are unchanged. Two candidate openings on the cumulative port omitted 832 and 1,088 MiB of persistent staging capacity; pending payload peaks were 107.5 and 109.8 MiB. These are allocator payloads, not net system savings. Overall private peaks and shared peaks varied in opposite directions across the two pairs. Original shaders, warmed pipelines, 4 GiB BAR, RTX 5070 Ti. No FPS or image parity claim. The focused native readback test on current main plus this patch passed with both SEND_OWN=1 and 0, covering adjacent GPU data, reversion, resends and later CPU preparation. Source-only patch against 829188e9; our fork push based on this main was blocked by workflow scope. <details><summary>Patch with native regression (git apply)</summary> ```diff diff --git a/crates/victory-gpu/src/host/send.rs b/crates/victory-gpu/src/host/send.rs index b9bb2575..985a17d6 100644 --- a/crates/victory-gpu/src/host/send.rs +++ b/crates/victory-gpu/src/host/send.rs @@ -666,3 +666,38 @@ mod tests { assert_eq!(actual, expected, "changed words and untouched neighbors"); } } + +/// A partial CPU update after the card has written the neighbouring word must +/// not restore the old CPU value; a reverted edit must not send that word either. +#[test] +#[ignore = "requires an isolated D3D12 host and VICTORY_RT_SPARSE_STAGE=1"] +fn sparse_rt_arena_preserves_gpu_neighbours_and_snapshot_order() { + let host = host().expect("D3D12 host"); + let n = 64 << 20; + let at = crate::upload::reserve(n).unwrap(); + let s = crate::shadow::private_arena(at as u64, n as u64).unwrap(); + assert!(s.sparse_arena() && s.card_sides().unwrap().0.is_none()); + let mut rig = crate::inplace::Rig::new(&host.device).unwrap(); + let submit = || host.card_before(&[], &Default::default(), false).unwrap(); + let finish = |plan| unsafe { + let fence: ID3D12Fence = host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + host.queue().Signal(&fence, 1).unwrap(); + fence.SetEventOnCompletion(1, HANDLE::default()).unwrap(); + assert_eq!(fence.GetCompletedValue(),1); + host.card_done(plan); + }; + s.edit_arena(0, &[1u8;4096]); s.resend(0,4096); s.update(at,n); finish(submit()); + let mut expected = vec![1u8;4096]; + rig.store(&s.buffer, 4, &[0x99;4]).unwrap(); expected[4..8].fill(0x99); + s.edit_arena(0,&[7;4]); s.edit_arena(4,&[88;4]); s.edit_arena(4,&[1;4]); + s.edit_arena(64,&[11;512]); s.update(at,n); + let first=submit(); + // Prepare the next CPU version while the first upload can still be live. + s.edit_arena(0,&[0x44;4]); s.update(at,n); finish(first); + expected[..4].fill(7); expected[64..576].fill(11); + assert_eq!(rig.fetch(&s.buffer,0,4096).unwrap(),expected); + finish(submit()); expected[..4].fill(0x44); + assert_eq!(rig.fetch(&s.buffer,0,4096).unwrap(),expected); + s.resend(4,8); s.update(at,n); finish(submit()); expected[4..8].fill(1); + assert_eq!(rig.fetch(&s.buffer,0,4096).unwrap(),expected); +} diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index b6f93925..3f2eef64 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -601,7 +601,7 @@ impl Memory { // write told: the kernel is not asked about 64 MiB for each list // that brings the arenas up to date. crate::watch::own(at, ARENA as usize); - let Some(n) = crate::shadow::by_address(at as u64, ARENA).and_then(|s| self.number(s)) else { + let Some(n) = crate::shadow::private_arena(at as u64, ARENA).and_then(|s| self.number(s)) else { failed(1); crate::watch::disown(at); // SAFETY: the reservation just made, which nothing else knows of. @@ -810,6 +810,7 @@ impl Memory { let from = (page * PAGE) as usize + piece; // (Pages that are not there read as zeros.) crate::host::copy_mapped(title.as_mut_ptr(), from as *const u8, PIECE, false); + if shadow.sparse_arena() { self.stats.changed += shadow.edit_arena(base + piece, &title) as u64; continue; } // SAFETY: a page of an arena of ours, under the mutex. let ours = unsafe { std::slice::from_raw_parts_mut((held.at + piece) as *mut u8, PIECE) }; let changed = merge(&title, ours, never); @@ -925,6 +926,7 @@ impl Memory { let n = (PIECE - at % PIECE).min(to - at); crate::host::copy_mapped(title.as_mut_ptr(), (page as usize * PAGE as usize + at) as *const u8, n, false); // SAFETY: a page of an arena of ours, under the mutex. + if shadow.sparse_arena() { shadow.edit_arena(base + at, &title[..n]); at += n; continue; } let ours = unsafe { std::slice::from_raw_parts_mut((held.at + at) as *mut u8, n) }; if *ours != title[..n] { ours.copy_from_slice(&title[..n]); @@ -1058,6 +1060,9 @@ impl Memory { } let frames = self.frame.wrapping_sub(frame).max(1) as f64; let s = std::mem::take(&mut self.stats); + if self.arenas.first().is_some_and(|a| self.copies[a.0].sparse_arena()) { + tracing::info!(omitted_bytes=self.arenas.len() as u64 * ARENA, pending_peak_bytes=crate::shadow::arena_edit_peak(), "RT arena staging capacity"); + } let (on_card, spilled, most) = crate::shadow::arena_bytes(); let ms = |(_, nanos): (u64, u64)| nanos as f64 / 1e6 / frames; let calls = |(calls, _): (u64, u64)| calls as f64 / frames; diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 0c572f4e..795e8aaa 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -15,6 +15,8 @@ //! descriptors, buffer views in tables); buffers read through directly //! indexed heaps keep what their first use copied. +mod arena_edits; +pub(crate) fn arena_edit_peak() -> usize { arena_edits::peak() } use std::collections::BTreeMap; use std::sync::atomic::{AtomicU8, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, RwLock}; @@ -35,6 +37,7 @@ pub(crate) struct Shadow { /// The bytes of `buffer`, once asked. width: std::sync::OnceLock<u64>, pub(crate) buffer: ID3D12Resource, + arena_edits: Option<Box<arena_edits::Edits>>, data: *mut u8, gpu: u64, /// Where the title buffer starts and how long it is. @@ -129,6 +132,8 @@ pub(crate) struct Shadow { /// shadow's CPU mirror can use pageable process memory. Single-sided buffers /// and the upload checker still need a D3D12 resource. enum CardCpu { + /// Uses Memory’s private arena as the last published CPU version. + Arena, Shared(ID3D12Resource), Private { address: usize, size: u64 }, } @@ -155,7 +160,7 @@ impl CardCpu { } fn shared(&self) -> Option<&ID3D12Resource> { - match self { Self::Shared(buffer) => Some(buffer), Self::Private { .. } => None } + match self { Self::Shared(buffer) => Some(buffer), Self::Private { .. } | Self::Arena => None } } } @@ -5154,7 +5159,7 @@ impl Shadow { /// kernel would refuse (and with it the ranges asked about together). pub(crate) fn asked_ahead(&self) -> bool { let watched = self.watched.load(Ordering::Relaxed); - watched != NOT_WATCHED && (watched != GUARDED || !crate::watch::light()) + !self.sparse_arena() && watched != NOT_WATCHED && (watched != GUARDED || !crate::watch::light()) } /// The copy's own number (see the field). @@ -5260,6 +5265,7 @@ impl Shadow { width: Default::default(), buffer, data, + arena_edits: None, gpu, start, len, @@ -6191,6 +6197,7 @@ impl Shadow { } fn update_ranges(&self, address: usize, len: usize) -> usize { + if self.sparse_arena() { return self.publish_arena_edits(address, len); } // In place: the card reads title memory itself. if self.place.is_some() { return 0; @@ -6232,6 +6239,7 @@ impl Shadow { /// nothing, and knows it without asking anything /// (`crate::watch::nothing_new`). `false` if it would have to ask. pub(crate) fn nothing_new(&self, address: usize, len: usize) -> bool { + if let Some(e) = &self.arena_edits { return e.empty(); } if self.place.is_some() { return true; } @@ -6775,6 +6783,7 @@ impl Shadow { /// Offsets `[from, to)` go up again whole, as the CPU's side has them. pub(crate) fn resend(&self, from: usize, to: usize) { + if let Some(e) = &self.arena_edits { e.force(from,to); return; } self.card_changed(from, to); } @@ -8203,6 +8212,15 @@ pub(crate) fn small_buffer_in(address: u64, len: u64, most: u64) -> bool { /// the only place that has it. The CPU's side holds the bytes as they were /// last taken, and only dwords that changed since go up. pub(crate) fn by_address(start: u64, len: u64) -> Option<Arc<Shadow>> { + by_address_inner(start, len, false) +} + +/// Only the private zeroed allocation owned by Memory, never title bytes. +pub(crate) fn private_arena(start: u64, len: u64) -> Option<Arc<Shadow>> { + by_address_inner(start, len, !crate::host::upcheck::on() && std::env::var_os("VICTORY_RT_SPARSE_STAGE").is_some_and(|v| v == "1")) +} + +fn by_address_inner(start: u64, len: u64, sparse: bool) -> Option<Arc<Shadow>> { let host = host()?; if !cards() || !host.card_ready() { return None; @@ -8210,7 +8228,7 @@ pub(crate) fn by_address(start: u64, len: u64) -> Option<Arc<Shadow>> { // At most `arena_card_most` on the card's own memory, and while the card has room for it // ([`crate::resource::card_copy_fits`]); past that the side shaders see is in the PC's memory. let room = host.video_memory().is_none_or(|[budget, used, ..]| crate::resource::card_copy_fits(budget, used, len)); - let (staging, data) = CardCpu::allocate(len)?; + let (staging, data) = if sparse { (CardCpu::Arena, start as *mut u8) } else { CardCpu::allocate(len)? }; let on_card = if room && take_under(&ARENA_CARD_BYTES, len, arena_card_most()) { let made = host.uav_buffer(len); if made.is_none() { @@ -8234,6 +8252,7 @@ pub(crate) fn by_address(start: u64, len: u64) -> Option<Arc<Shadow>> { // SAFETY: a live buffer. let gpu = unsafe { buffer.GetGPUVirtualAddress() }; let mut shadow = Shadow::new(buffer, data, gpu, start, len); + shadow.arena_edits = sparse.then(Box::default); shadow.window = true; shadow.changes_only.store(true, Ordering::Relaxed); shadow.card = Some(Card { diff --git a/crates/victory-gpu/src/shadow/arena_edits.rs b/crates/victory-gpu/src/shadow/arena_edits.rs new file mode 100644 index 00000000..70ccbbf4 --- /dev/null +++ b/crates/victory-gpu/src/shadow/arena_edits.rs @@ -0,0 +1,63 @@ +//! Copy-on-write input for the memory manager's private RT arenas. The low CPU +//! allocation is the last published CPU version (not a mirror of GPU writes). +//! Recording only edits pending chunks. Submission alone publishes them and +//! uploads through the ordinary fenced, immutable send path. +use super::*; +const CHUNK: usize = 4096; +static LIVE: AtomicUsize = AtomicUsize::new(0); +static HIGH: AtomicUsize = AtomicUsize::new(0); +pub(super) fn peak() -> usize { HIGH.load(Ordering::Relaxed) } +#[derive(Default)] +struct Pending { chunks: BTreeMap<usize, Box<[u8]>>, force: Vec<(usize,usize)> } +#[derive(Default)] +pub(super) struct Edits(Mutex<Pending>); +impl Edits { + pub(super) fn empty(&self) -> bool { + let p=self.0.lock().unwrap_or_else(|e|e.into_inner()); + p.chunks.is_empty() && p.force.is_empty() + } + pub(super) fn force(&self, from:usize,to:usize) { + let mut p=self.0.lock().unwrap_or_else(|e|e.into_inner()); + push_dirty_runs(&mut p.force, [(from,to)]); + } +} +impl Drop for Edits { fn drop(&mut self) { LIVE.fetch_sub(self.0.get_mut().unwrap_or_else(|e|e.into_inner()).chunks.len()*CHUNK, Ordering::Relaxed); } } +impl Shadow { + pub(crate) fn sparse_arena(&self)->bool { self.arena_edits.is_some() } + pub(crate) fn edit_arena(&self, at:usize, bytes:&[u8])->usize { + let mut pending=self.arena_edits.as_ref().unwrap().0.lock().unwrap_or_else(|e|e.into_inner()); + let base=at/CHUNK*CHUNK; let off=at-base; + assert!(off+bytes.len()<=CHUNK && base+CHUNK<=self.len as usize); + // SAFETY: the private arena is live, and its only writer holds this lock. + let published=unsafe{std::slice::from_raw_parts(self.data.add(base),CHUNK)}; + let current=pending.chunks.get(&base).map_or(published,|b|&**b); + if &current[off..off+bytes.len()]==bytes { return 0; } + let chunk=pending.chunks.entry(base).or_insert_with(||{ + let n=LIVE.fetch_add(CHUNK,Ordering::Relaxed)+CHUNK; HIGH.fetch_max(n,Ordering::Relaxed); published.into() + }); + chunk[off..off+bytes.len()].copy_from_slice(bytes); bytes.len() + } + pub(super) fn publish_arena_edits(&self,address:usize,len:usize)->usize { + let (lo,hi)=self.inside(address,len); + if hi<=lo { return 0; } + let mut pending=self.arena_edits.as_ref().unwrap().0.lock().unwrap_or_else(|e|e.into_inner()); + let mut runs=Vec::new(); + for (&base, data) in pending.chunks.range(lo/CHUNK*CHUNK..hi) { + let a=lo.max(base); let b=hi.min(base+CHUNK); + // SAFETY: this is an exclusively CPU-owned arena. This lock excludes + // pending writers; the submission thread finishes all refreshes before staging. + let dest=unsafe{std::slice::from_raw_parts_mut(self.data.add(a),b-a)}; + let src=&data[a-base..b-base]; + for (off,n) in word_runs(a,src,dest) { + dest[off..off+n].copy_from_slice(&src[off..off+n]);runs.push((a+off,a+off+n)); + } + } + let count=pending.chunks.len();pending.chunks.retain(|&base,_| base<lo || base+CHUNK>hi); + LIVE.fetch_sub((count-pending.chunks.len())*CHUNK,Ordering::Relaxed); + for (a,b) in std::mem::take(&mut pending.force) { + if b<=lo || a>=hi {pending.force.push((a,b));continue} + runs.push((a.max(lo),b.min(hi))); if a<lo {pending.force.push((a,lo))} if b>hi {pending.force.push((hi,b))} + } + let runs=joined(runs);let count=runs.iter().map(|(a,b)|b-a).sum(); self.card_changed_runs(runs.into_iter());count + } +} ``` </details>
This discussion has been locked. Commenting is limited to contributors.
No reviewers
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.

Dependencies

No dependencies set

Reference
github/trustno1-coder--VIctory-NVIDIA!1823
No description provided.