gpu: vectorize merge_writeback with 64-bit word chunks #3079

Open
github-bot wants to merge 2 commits from github-bot/gh-3079 into main AGit
Owner

@⁠AdvaitPalve11 on GitHub · 2026-11-26 06:52 UTC · original
AdvaitPalve11:perf/gpu-shadow-writeback → main · +29 −1 · 1 files · 2 commits · open

Problem:

In console UMA-to-discrete shadow buffer synchronization (crates/victory-gpu/src/shadow.rs), merge_writeback is called after every GPU submission to scan altered title memory ranges and copy GPU writes back into title RAM.

Previously, merge_writeback iterated through all memory byte-by-byte in a scalar loop. In typical frames, over 95% of 8-byte words are identical (host_word == old_word), meaning the scalar byte loop spent significant CPU cycles doing branchless byte math over completely unchanged data.

Solution:
Process slices in 8-byte (u64) chunks using chunks_exact_mut(8).
Fast-path: When h_word == o_word, the GPU did not alter any byte in that 8-byte chunk. If h_word != t_word, the host buffer simply takes the title word, fast-skipping all 8 bytes in a single comparison without scalar loop overhead.
Fall-back: Run byte-level lane bitwise merging only on 8-byte chunks where alterations occurred, as well as on any trailing remainder bytes (< 8).
Verified against the existing test oracle writeback_merge_matches_bytewise_oracle across all test lengths [0, 1, 63, 64, 65, 193, 65536] and stride intervals with zero mismatches.

**@⁠AdvaitPalve11** on GitHub · 2026-11-26 06:52 UTC · [original](https://github.com/Marvisak/VIctory/pull/3079) `AdvaitPalve11:perf/gpu-shadow-writeback` → `main` · +29 −1 · 1 files · 2 commits · open Problem: In console UMA-to-discrete shadow buffer synchronization (crates/victory-gpu/src/shadow.rs), merge_writeback is called after every GPU submission to scan altered title memory ranges and copy GPU writes back into title RAM. Previously, merge_writeback iterated through all memory byte-by-byte in a scalar loop. In typical frames, over 95% of 8-byte words are identical (host_word == old_word), meaning the scalar byte loop spent significant CPU cycles doing branchless byte math over completely unchanged data. Solution: Process slices in 8-byte (u64) chunks using chunks_exact_mut(8). Fast-path: When h_word == o_word, the GPU did not alter any byte in that 8-byte chunk. If h_word != t_word, the host buffer simply takes the title word, fast-skipping all 8 bytes in a single comparison without scalar loop overhead. Fall-back: Run byte-level lane bitwise merging only on 8-byte chunks where alterations occurred, as well as on any trailing remainder bytes (< 8). Verified against the existing test oracle writeback_merge_matches_bytewise_oracle across all test lengths [0, 1, 63, 64, 65, 193, 65536] and stride intervals with zero mismatches.
In console UMA-to-discrete shadow buffer synchronization, merge_writeback scans memory ranges byte-by-byte to merge GPU writes back to title RAM. For the majority of memory in typical frames, the GPU has not modified the contents (host_word == old_word).

- Process 8-byte chunks (u64) with chunks_exact_mut(8).

- Fast-skip unchanged 8-byte chunks in a single comparison, syncing host to title only when needed.

- Process byte-level lane logic only for altered 8-byte chunks and trailing remainder bytes.

- Matches writeback_merge_matches_bytewise_oracle across all lengths and strides.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 06:55:00 +00:00
Author
Owner

@⁠Dukestar69 on GitHub · 2026-11-26 06:55 UTC · original · reviewed

Tested locally merged onto origin/main (63bcca4) on Windows 11 x64 (Rust 1.98.1 MSVC, NVIDIA GeForce RTX 5090 + WARP):

  • cargo test -p victory-gpu shadow::tests -- --test-threads=1 (RTX 5090 & WARP): 9 passed, 0 failed on both.
  • cargo clippy -p victory-gpu --all-targets -- -D warnings: fails with 3 errors (clippy::chunks_exact_to_as_chunks on Rust 1.98.1):
error: using `chunks_exact_mut` with a constant chunk size
  --> crates\victory-gpu\src\shadow.rs:30:30
error: using `chunks_exact_mut` with a constant chunk size
  --> crates\victory-gpu\src\shadow.rs:31:29
error: using `chunks_exact` with a constant chunk size
  --> crates\victory-gpu\src\shadow.rs:32:28

Switching to as_chunks_mut::<8>() / as_chunks::<8>() will fix all three clippy errors and also eliminate the .try_into().unwrap() conversions.

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

**@⁠Dukestar69** on GitHub · 2026-11-26 06:55 UTC · [original](https://github.com/Marvisak/VIctory/pull/3079#pullrequestreview-6069733040) · **reviewed** Tested locally merged onto `origin/main` (`63bcca4`) on Windows 11 x64 (Rust 1.98.1 MSVC, NVIDIA GeForce RTX 5090 + WARP): - `cargo test -p victory-gpu shadow::tests -- --test-threads=1` (RTX 5090 & WARP): 9 passed, 0 failed on both. - `cargo clippy -p victory-gpu --all-targets -- -D warnings`: **fails with 3 errors** (`clippy::chunks_exact_to_as_chunks` on Rust 1.98.1): ``` error: using `chunks_exact_mut` with a constant chunk size --> crates\victory-gpu\src\shadow.rs:30:30 error: using `chunks_exact_mut` with a constant chunk size --> crates\victory-gpu\src\shadow.rs:31:29 error: using `chunks_exact` with a constant chunk size --> crates\victory-gpu\src\shadow.rs:32:28 ``` Switching to `as_chunks_mut::<8>()` / `as_chunks::<8>()` will fix all three clippy errors and also eliminate the `.try_into().unwrap()` conversions. Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).
Author
Owner

@⁠oni-swr on GitHub · 2026-11-26 07:02 UTC · original

Independent CPU-only verification of #3079 at 2371f8de832ab5e66ef0b2ed9ddb81e3f8bda941 against its exact parent 63bcca43c6a00a758510398fa43096ce7e4f7df0. This is the scope claimed in #1633. State and head were rechecked before and after the run: open, head unchanged. #1633 has no other claim on this PR. It is a synthetic scalar-oracle comparison only; it does not repeat the shadow suite or the clippy findings already on the PR.

Result: no difference found. The old and new merge_writeback produced identical title bytes, host bytes and returned flag in every case, and both matched an independent per-byte specification (a byte the GPU changed, host != old, takes the GPU value; otherwise the title/CPU byte stays; then host = title).

Method. Both functions were extracted verbatim from the two commits into a standalone harness, so no other code could differ. Every case ran on slices placed at byte offsets 0 to 7 inside guard-padded buffers filled with a sentinel. The guards and the old buffer were checked for stray writes. 4,452,170 of the new-implementation calls started at a non-8-aligned address.

Sweep Cases
Exhaustive: each lane's (old, host, title) in {0,1,2}³, lengths 0 to 4, 4 offsets 2,207,524
Lane states (untouched, GPU-only, CPU-only, both different, both equal), lengths 0 to 17 (word boundary and tails), offsets 0 to 7 3,188,281
Randomized mixed edits (dense and sparse, byte, word and run edits, simultaneous CPU-side edits that overlap and don't overlap, CPU copying the GPU's value), 22 lengths from 0 to 65,537 including 4096-byte pages 8,082
Fixed flag cases (no-op, CPU-only change, GPU equals CPU, conflict) 4

That is 5,403,891 comparisons in total.

Counters. The only observable output besides the bytes is the returned bool, which gates written += n and the write-back to title memory in the two callers. It matched in every case, including the false cases where the CPU changed bytes and the GPU didn't, and where the GPU wrote the value the CPU already held.

Control. Two deliberate mutations of the new function were both caught: making the fast path skip the host-takes-title copy, and dropping the tail remainder loop. The harness can fail.

Note, not a defect. The old loop used zip, which stops at the shortest of the three slices. The new remainder step pairs three separate remainders, so it would skip the tail bytes if the lengths ever differed. I did not test unequal lengths. Both callers in shadow.rs pass equal lengths (n for all three), so this can't happen today. A debug_assert_eq! on the lengths would make that contract explicit if the author wants it.

Environment. Windows 11, Rust 1.98.1, one scratch cargo project with CARGO_TARGET_DIR=D:\victory-3079-oracle-target, --locked -j 4. No D3D12, GPU, game files, dumps, shader names or hashes. The repo checkout was never modified and is clean at the parent commit. The target directory was removed and I confirmed that it no longer exists.

Disclosure. AI-assisted: Claude Code (Claude Sonnet 5.5) ran the verification, coordinated by Codex (gpt-6.2-sol). The author keeps ownership of the change; I have posted no competing PR.

**@⁠oni-swr** on GitHub · 2026-11-26 07:02 UTC · [original](https://github.com/Marvisak/VIctory/pull/3079#issuecomment-7185027840) Independent CPU-only verification of #3079 at `2371f8de832ab5e66ef0b2ed9ddb81e3f8bda941` against its exact parent `63bcca43c6a00a758510398fa43096ce7e4f7df0`. This is the scope claimed in https://git.gtahub.st/github/Marvisak--VIctory/issues/1633. State and head were rechecked before and after the run: open, head unchanged. #1633 has no other claim on this PR. It is a synthetic scalar-oracle comparison only; it does not repeat the shadow suite or the clippy findings already on the PR. **Result: no difference found.** The old and new `merge_writeback` produced identical title bytes, host bytes and returned flag in every case, and both matched an independent per-byte specification (a byte the GPU changed, `host != old`, takes the GPU value; otherwise the title/CPU byte stays; then host = title). **Method.** Both functions were extracted verbatim from the two commits into a standalone harness, so no other code could differ. Every case ran on slices placed at byte offsets 0 to 7 inside guard-padded buffers filled with a sentinel. The guards and the `old` buffer were checked for stray writes. 4,452,170 of the new-implementation calls started at a non-8-aligned address. | Sweep | Cases | |---|---| | Exhaustive: each lane's (old, host, title) in {0,1,2}³, lengths 0 to 4, 4 offsets | 2,207,524 | | Lane states (untouched, GPU-only, CPU-only, both different, both equal), lengths 0 to 17 (word boundary and tails), offsets 0 to 7 | 3,188,281 | | Randomized mixed edits (dense and sparse, byte, word and run edits, simultaneous CPU-side edits that overlap and don't overlap, CPU copying the GPU's value), 22 lengths from 0 to 65,537 including 4096-byte pages | 8,082 | | Fixed flag cases (no-op, CPU-only change, GPU equals CPU, conflict) | 4 | That is 5,403,891 comparisons in total. **Counters.** The only observable output besides the bytes is the returned `bool`, which gates `written += n` and the write-back to title memory in the two callers. It matched in every case, including the false cases where the CPU changed bytes and the GPU didn't, and where the GPU wrote the value the CPU already held. **Control.** Two deliberate mutations of the new function were both caught: making the fast path skip the host-takes-title copy, and dropping the tail remainder loop. The harness can fail. **Note, not a defect.** The old loop used `zip`, which stops at the shortest of the three slices. The new remainder step pairs three separate remainders, so it would skip the tail bytes if the lengths ever differed. I did not test unequal lengths. Both callers in `shadow.rs` pass equal lengths (`n` for all three), so this can't happen today. A `debug_assert_eq!` on the lengths would make that contract explicit if the author wants it. **Environment.** Windows 11, Rust 1.98.1, one scratch cargo project with `CARGO_TARGET_DIR=D:\victory-3079-oracle-target`, `--locked -j 4`. No D3D12, GPU, game files, dumps, shader names or hashes. The repo checkout was never modified and is clean at the parent commit. The target directory was removed and I confirmed that it no longer exists. **Disclosure.** AI-assisted: Claude Code (Claude Sonnet 5.5) ran the verification, coordinated by Codex (gpt-6.2-sol). The author keeps ownership of the change; I have posted no competing PR.
Author
Owner

@⁠fuzeofficlal on GitHub · 2026-11-26 08:00 UTC · original · requested changes

Tested locally on Windows 11 x64 (rustc 1.98.1, RTX 5090 + WARP):

  • cargo clippy -p victory-gpu --all-targets --locked -- -D warnings (default and --all-features): clean (as_chunks_mut::<8>() resolved the Rust 1.98.1 clippy lints and stays within workspace MSRV 1.88).
  • shadow::writeback_merge_matches_bytewise_oracle (1 passed) and shadow::tests (9 passed on RTX 5090, 9 passed on WARP with --features diagnostics); cargo xtask policy: 191 files ok.

However, benchmarking this change in release mode (rustc -C opt-level=3, allowing merge_writeback_bytes to inline) and inspecting the generated x86-64 assembly shows a regression across every workload, including the 0% and 5% dirty cases:

  • On main, LLVM already auto-vectorizes the branchless byte loop into a 32-byte/iteration SSE2 loop (movdqu/pxor/pcmpeqb/pandn/por, zero branches in the hot loop).
  • In this PR, the data-dependent if h_word == o_word branch disables auto-vectorization: the fast path runs scalar 8-byte cmpq/jne/je, and the dirty fallback unrolls merge_writeback_bytes into ~130 scalar shift/cmov instructions with heavy stack spilling (subq $136, %rsp).

Measured averages (64 KiB pages over 20,000 iterations; 193 B over 200,000 iterations, same-binary A/B):

Case main #3079 Speedup
64 KiB, 0% GPU dirty, 0% CPU dirty 1,942.5 ns 2,066.5 ns 0.94×
64 KiB, 0% GPU dirty, 100% CPU dirty 1,841.0 ns 2,459.2 ns 0.75×
64 KiB, 5% GPU dirty (contiguous) 1,969.3 ns 4,244.2 ns 0.46×
64 KiB, 5% words random GPU dirty 1,998.2 ns 4,469.5 ns 0.45×
64 KiB, 5% GPU dirty (every 20 B) 2,108.7 ns 19,114.4 ns 0.11×
64 KiB, 25% words random GPU dirty 2,180.0 ns 12,608.0 ns 0.17×
64 KiB, 50% words random GPU dirty 2,702.3 ns 22,743.9 ns 0.12×
64 KiB, 100% GPU dirty 5,169.0 ns 51,695.0 ns 0.10×
193 B unaligned (+3), 5% random GPU dirty 16.7 ns 31.8 ns 0.53×

Since merge_writeback is called on pages where host != old (or marked GPU-written pages), this makes the hot path 2×–10× slower in release builds. Recommend holding off on merging unless a revised implementation demonstrates an actual release speedup over main's auto-vectorized SSE2 loop (for example, keeping branchless byte-lane math intact on wider 16/32-byte chunks or verifying with a release benchmark that a coarse skip beats SSE2 without degrading dirty pages).

**@⁠fuzeofficlal** on GitHub · 2026-11-26 08:00 UTC · [original](https://github.com/Marvisak/VIctory/pull/3079#pullrequestreview-6070370109) · **requested changes** Tested locally on Windows 11 x64 (`rustc 1.98.1`, RTX 5090 + WARP): - `cargo clippy -p victory-gpu --all-targets --locked -- -D warnings` (default and `--all-features`): clean (`as_chunks_mut::<8>()` resolved the Rust 1.98.1 clippy lints and stays within workspace MSRV 1.88). - `shadow::writeback_merge_matches_bytewise_oracle` (1 passed) and `shadow::tests` (9 passed on RTX 5090, 9 passed on WARP with `--features diagnostics`); `cargo xtask policy`: 191 files ok. However, benchmarking this change in release mode (`rustc -C opt-level=3`, allowing `merge_writeback_bytes` to inline) and inspecting the generated x86-64 assembly shows a **regression across every workload**, including the 0% and 5% dirty cases: - On `main`, LLVM already auto-vectorizes the branchless byte loop into a 32-byte/iteration SSE2 loop (`movdqu`/`pxor`/`pcmpeqb`/`pandn`/`por`, zero branches in the hot loop). - In this PR, the data-dependent `if h_word == o_word` branch disables auto-vectorization: the fast path runs scalar 8-byte `cmpq`/`jne`/`je`, and the dirty fallback unrolls `merge_writeback_bytes` into ~130 scalar shift/cmov instructions with heavy stack spilling (`subq $136, %rsp`). Measured averages (64 KiB pages over 20,000 iterations; 193 B over 200,000 iterations, same-binary A/B): | Case | `main` | `#3079` | Speedup | |---|---:|---:|---:| | 64 KiB, 0% GPU dirty, 0% CPU dirty | 1,942.5 ns | 2,066.5 ns | 0.94× | | 64 KiB, 0% GPU dirty, 100% CPU dirty | 1,841.0 ns | 2,459.2 ns | 0.75× | | 64 KiB, 5% GPU dirty (contiguous) | 1,969.3 ns | 4,244.2 ns | 0.46× | | 64 KiB, 5% words random GPU dirty | 1,998.2 ns | 4,469.5 ns | 0.45× | | 64 KiB, 5% GPU dirty (every 20 B) | 2,108.7 ns | 19,114.4 ns | 0.11× | | 64 KiB, 25% words random GPU dirty | 2,180.0 ns | 12,608.0 ns | 0.17× | | 64 KiB, 50% words random GPU dirty | 2,702.3 ns | 22,743.9 ns | 0.12× | | 64 KiB, 100% GPU dirty | 5,169.0 ns | 51,695.0 ns | 0.10× | | 193 B unaligned (+3), 5% random GPU dirty | 16.7 ns | 31.8 ns | 0.53× | Since `merge_writeback` is called on pages where `host != old` (or marked GPU-written pages), this makes the hot path 2×–10× slower in release builds. Recommend holding off on merging unless a revised implementation demonstrates an actual release speedup over `main`'s auto-vectorized SSE2 loop (for example, keeping branchless byte-lane math intact on wider 16/32-byte chunks or verifying with a release benchmark that a coarse skip beats SSE2 without degrading dirty pages).
Author
Owner

@⁠Marvisak on GitHub · 2026-11-26 08:22 UTC · original

Automated triage for the maintainers.

Needs work. By my reading the new merge_writeback in shadow.rs is equivalent to the old one: an unchanged word leaves title alone and sets host to title, as before, and slicing to the shortest length keeps the old zip behaviour. The existing oracle test passes. CI: passing.

The PR is a performance change with no measurement, though. The old loop is branchless over three zipped byte slices, which LLVM normally vectorizes already. The new version adds a data-dependent branch per 8 bytes, so it could just as well be slower. Please add a before/after timing of copy_back from a release build, either from a run (the CompareUs counter in copystat) or from a micro-benchmark on realistic data. That would change the verdict. The "over 95 % of words identical" figure should also be backed by a measurement.


Generated by Claude Code

**@⁠Marvisak** on GitHub · 2026-11-26 08:22 UTC · [original](https://github.com/Marvisak/VIctory/pull/3079#issuecomment-7186513746) <!-- victory-triage v1 head=4077544bd868d17cf1bfe8a466668c3705b1fdc1 verdict=needs-work at=2026-11-26T08:18:02Z --> Automated triage for the maintainers. Needs work. By my reading the new `merge_writeback` in `shadow.rs` is equivalent to the old one: an unchanged word leaves title alone and sets host to title, as before, and slicing to the shortest length keeps the old `zip` behaviour. The existing oracle test passes. CI: passing. The PR is a performance change with no measurement, though. The old loop is branchless over three zipped byte slices, which LLVM normally vectorizes already. The new version adds a data-dependent branch per 8 bytes, so it could just as well be slower. Please add a before/after timing of `copy_back` from a release build, either from a run (the `CompareUs` counter in `copystat`) or from a micro-benchmark on realistic data. That would change the verdict. The "over 95 % of words identical" figure should also be backed by a measurement. --- _Generated by [Claude Code](https://claude.ai/code)_
Author
Owner

@⁠cloph-dsp on GitHub · 2026-11-26 10:53 UTC · original

Independent local verification of head 4077544 on Windows 11, Rust 1.100.0/MSVC:

  • cargo test --locked -p victory-gpu --lib shadow::writeback_merge_matches_bytewise_oracle — 1 passed, 0 failed.
  • git diff --check origin/main HEAD — clean.

CPU-only bytewise oracle test; no D3D12 device needed. Used a worktree-local CARGO_TARGET_DIR. Synthetic inputs only; no game assets or DRM material used. AI-assisted (Hy4 flash).

**@⁠cloph-dsp** on GitHub · 2026-11-26 10:53 UTC · [original](https://github.com/Marvisak/VIctory/pull/3079#issuecomment-7189979107) Independent local verification of head `4077544` on Windows 11, Rust 1.100.0/MSVC: - `cargo test --locked -p victory-gpu --lib shadow::writeback_merge_matches_bytewise_oracle` — 1 passed, 0 failed. - `git diff --check origin/main HEAD` — clean. CPU-only bytewise oracle test; no D3D12 device needed. Used a worktree-local `CARGO_TARGET_DIR`. Synthetic inputs only; no game assets or DRM material used. AI-assisted (Hy4 flash).
This pull request can be merged automatically.
You are not authorized to merge this pull request.
View command line instructions

Checkout

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

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-3079'
git switch 'github-bot/gh-3079'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-3079'
git switch 'github-bot/gh-3079'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-3079'
git switch 'main'
git merge --squash 'github-bot/gh-3079'
git switch 'main'
git merge --ff-only 'github-bot/gh-3079'
git switch 'main'
git merge 'github-bot/gh-3079'
git push origin 'main'
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/Marvisak--VIctory!3079
No description provided.