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

Open
AdvaitPalve11 wants to merge 2 commits from upstream-pr/3079 into main
AdvaitPalve11 commented 2026-11-26 06:52:36 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by AdvaitPalve11 on 2026-11-26T06:52:36Z.


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.

<!-- greyfinch-sync:Marvisak/VIctory:issue:6621231168 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3079). Originally posted by [AdvaitPalve11](https://github.com/AdvaitPalve11) on 2026-11-26T06:52:36Z. --- 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.
Dukestar69 commented 2026-11-26 07:01:41 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Dukestar69 on 2026-11-26T06:55:03Z.

Review: COMMENTED


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).

<!-- greyfinch-sync:Marvisak/VIctory:review:6069733040 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3079#pullrequestreview-6069733040). Originally posted by [Dukestar69](https://github.com/Dukestar69) on 2026-11-26T06:55:03Z. **Review:** COMMENTED --- 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).
fuzeofficlal commented 2026-11-26 08:03:03 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by fuzeofficlal on 2026-11-26T08:00:05Z.

Review: CHANGES_REQUESTED


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).

<!-- greyfinch-sync:Marvisak/VIctory:review:6070370109 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3079#pullrequestreview-6070370109). Originally posted by [fuzeofficlal](https://github.com/fuzeofficlal) on 2026-11-26T08:00:05Z. **Review:** CHANGES_REQUESTED --- 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).
oni-swr commented 2026-11-26 08:03:11 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by oni-swr on 2026-11-26T07:02:08Z.


Independent CPU-only verification of #3079 at 2371f8de832ab5e66ef0b2ed9ddb81e3f8bda941 against its exact parent 63bcca43c6a00a758510398fa43096ce7e4f7df0. This is the scope claimed in https://github.com/Marvisak/VIctory/issues/1633#issuecomment-7184977054. 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.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7185027840 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3079#issuecomment-7185027840). Originally posted by [oni-swr](https://github.com/oni-swr) on 2026-11-26T07:02:08Z. --- Independent CPU-only verification of #3079 at `2371f8de832ab5e66ef0b2ed9ddb81e3f8bda941` against its exact parent `63bcca43c6a00a758510398fa43096ce7e4f7df0`. This is the scope claimed in https://github.com/Marvisak/VIctory/issues/1633#issuecomment-7184977054. 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.
Marvisak commented 2026-11-26 09:06:06 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Marvisak on 2026-11-26T08:22:21Z.


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

<!-- greyfinch-sync:Marvisak/VIctory:comment:7186513746 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3079#issuecomment-7186513746). Originally posted by [Marvisak](https://github.com/Marvisak) on 2026-11-26T08:22:21Z. --- <!-- 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)_
cloph-dsp commented 2026-11-26 11:04:04 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by cloph-dsp on 2026-11-26T10:53:38Z.


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).

<!-- greyfinch-sync:Marvisak/VIctory:comment:7189979107 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3079#issuecomment-7189979107). Originally posted by [cloph-dsp](https://github.com/cloph-dsp) on 2026-11-26T10:53:38Z. --- 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 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/3079:upstream-pr/3079'
git switch 'upstream-pr/3079'

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/3079'
git switch 'upstream-pr/3079'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3079'
git switch 'upstream-pr/3079'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3079'
git switch 'main'
git merge --squash 'upstream-pr/3079'
git switch 'main'
git merge --ff-only 'upstream-pr/3079'
git switch 'main'
git merge 'upstream-pr/3079'
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!3077
No description provided.