GPU: AVX2 fast-path for merge_piece, first_difference, and last_difference #1

Open
altuux wants to merge 2 commits from upstream-pr/1 into main
altuux commented 2026-11-25 15:10:03 +00:00 (Migrated from github.com)

Imported from DexNom/VIctory. Originally posted by altuux on 2026-11-25T15:10:03Z.


Summary

Adds runtime-dispatched AVX2 (32 bytes/iter) fast paths to merge_piece, first_difference, and last_difference in crates/victory-gpu/src/shadow.rs (zero new dependencies, existing scalar/u64 fallbacks preserved):

  1. merge_piece (AVX2 + skip-unchanged fast path): Skips reading/writing title and avoids dirtying held cachelines on untouched 32-byte blocks (now == held), reducing DRAM traffic from 5 streams to 2 streams on untouched spans.
  2. first_difference & last_difference (AVX2 32 B/iter): Scans 32 bytes per iteration via _mm256_cmpeq_epi8 + _mm256_movemask_epi8 + trailing_zeros/leading_zeros.
  3. Unit tests: Extended difference_tests to cover 31/32/33/64/65/97-byte boundaries and added merge_piece_matches_scalar_across_lengths verifying bit-for-bit agreement with merge_piece_scalar across lengths 0..4096, including overlapping CPU+GPU writes to the same byte.

Benchmark notes (i5-12400)

  • merge_piece speedup depends strongly on change density inside the [first..=last] span:
    • Unchanged / very sparse spans: up to ~1.5× faster on a fully unchanged cached 64 KiB span (~1.2× at 1% changes, ~1.06× in cold RAM).
    • Dense / 50%-modified spans: roughly neutral to slightly slower (~10% overhead from the skip branch vs LLVM's branchless SSE2 auto-vectorization).
  • first_difference / last_difference: up to ~1.5–2× faster on long matching prefixes/suffixes; neutral when a difference appears early.
<!-- greyfinch-sync:DexNom/VIctory:issue:5493982476 --> Imported from [DexNom/VIctory](https://github.com/DexNom/VIctory/pull/1). Originally posted by [altuux](https://github.com/altuux) on 2026-11-25T15:10:03Z. --- ### Summary Adds runtime-dispatched AVX2 (32 bytes/iter) fast paths to `merge_piece`, `first_difference`, and `last_difference` in `crates/victory-gpu/src/shadow.rs` (zero new dependencies, existing scalar/`u64` fallbacks preserved): 1. **`merge_piece` (AVX2 + skip-unchanged fast path)**: Skips reading/writing `title` and avoids dirtying `held` cachelines on untouched 32-byte blocks (`now == held`), reducing DRAM traffic from 5 streams to 2 streams on untouched spans. 2. **`first_difference` & `last_difference` (AVX2 32 B/iter)**: Scans 32 bytes per iteration via `_mm256_cmpeq_epi8` + `_mm256_movemask_epi8` + `trailing_zeros`/`leading_zeros`. 3. **Unit tests**: Extended `difference_tests` to cover 31/32/33/64/65/97-byte boundaries and added `merge_piece_matches_scalar_across_lengths` verifying bit-for-bit agreement with `merge_piece_scalar` across lengths `0..4096`, including overlapping CPU+GPU writes to the same byte. ### Benchmark notes (i5-12400) - `merge_piece` speedup depends strongly on change density inside the `[first..=last]` span: - Unchanged / very sparse spans: up to **~1.5× faster** on a fully unchanged cached 64 KiB span (~1.2× at 1% changes, ~1.06× in cold RAM). - Dense / 50%-modified spans: roughly neutral to slightly slower (~10% overhead from the skip branch vs LLVM's branchless SSE2 auto-vectorization). - `first_difference` / `last_difference`: up to **~1.5–2× faster** on long matching prefixes/suffixes; neutral when a difference appears early.
itsonewi commented 2026-11-25 16:14:19 +00:00 (Migrated from github.com)

Imported from DexNom/VIctory. Originally posted by itsonewi on 2026-11-25T16:14:19Z.

Review: COMMENTED


Checked the SIMD paths against the scalar ones they replace in crates/victory-gpu/src/shadow.rs on main, and they are equivalent - including the part that is easiest to get wrong.

  • _mm256_blendv_epi8(v_n, v_t, eq) takes v_t where the bytes are equal and v_n where they differ, which is exactly the scalar (*t & !wrote) | (*n & wrote) for wrote = 0xff when n != h. The skipped all-equal chunk is a no-op for both slices: title would be stored its own value and held its own value.
  • diff_acc |= xor(merged, v_t) is the scalar's differs |= merged ^ *t, so the returned bool keeps meaning "title changed", not "the GPU wrote something".
  • first_difference_avx2: movemask bit k is byte k, so (!mask).trailing_zeros() gives the first differing byte, and the i + 32 <= len bound means no bit can come from beyond the slice - the classic false positive of a masked tail is not there.
  • last_difference_avx2 is symmetric: highest differing byte is 31 - (!mask).leading_zeros() on the reversed walk, the rposition tail runs first so ordering is kept, and while i >= 32 { i -= 32 } cannot underflow.
  • is_x86_feature_detected! plus #[target_feature(enable = "avx2")] on an unsafe fn is the right shape, and the loads are loadu, so no alignment requirement leaks into the callers.

Nit, not a bug: let len = now.len().min(held.len()).min(title.len()) cannot be shorter than the callers' slices by contract, but taking the min is right for zip equivalence, so leave it.

Not built or run here (no checkout and no AVX2 machine), so this is a reading of the patch, not a test run; the added merge_piece_matches_scalar_across_lengths sweep over 0..4096 is what would catch a disagreement anyway.


AI use: read the patch and the scalar functions on main through the GitHub API. No code was written by an agent here and no build was run.

<!-- greyfinch-sync:DexNom/VIctory:review:6060991590 --> Imported from [DexNom/VIctory](https://github.com/DexNom/VIctory/pull/1#pullrequestreview-6060991590). Originally posted by [itsonewi](https://github.com/itsonewi) on 2026-11-25T16:14:19Z. **Review:** COMMENTED --- Checked the SIMD paths against the scalar ones they replace in `crates/victory-gpu/src/shadow.rs` on `main`, and they are equivalent - including the part that is easiest to get wrong. - `_mm256_blendv_epi8(v_n, v_t, eq)` takes `v_t` where the bytes are equal and `v_n` where they differ, which is exactly the scalar `(*t & !wrote) | (*n & wrote)` for `wrote = 0xff` when `n != h`. The skipped all-equal chunk is a no-op for both slices: `title` would be stored its own value and `held` its own value. - `diff_acc |= xor(merged, v_t)` is the scalar's `differs |= merged ^ *t`, so the returned bool keeps meaning "`title` changed", not "the GPU wrote something". - `first_difference_avx2`: `movemask` bit k is byte k, so `(!mask).trailing_zeros()` gives the first differing byte, and the `i + 32 <= len` bound means no bit can come from beyond the slice - the classic false positive of a masked tail is not there. - `last_difference_avx2` is symmetric: highest differing byte is `31 - (!mask).leading_zeros()` on the reversed walk, the `rposition` tail runs first so ordering is kept, and `while i >= 32 { i -= 32 }` cannot underflow. - `is_x86_feature_detected!` plus `#[target_feature(enable = "avx2")]` on an `unsafe fn` is the right shape, and the loads are `loadu`, so no alignment requirement leaks into the callers. Nit, not a bug: `let len = now.len().min(held.len()).min(title.len())` cannot be shorter than the callers' slices by contract, but taking the min is right for `zip` equivalence, so leave it. Not built or run here (no checkout and no AVX2 machine), so this is a reading of the patch, not a test run; the added `merge_piece_matches_scalar_across_lengths` sweep over 0..4096 is what would catch a disagreement anyway. --- **AI use:** read the patch and the scalar functions on `main` through the GitHub API. No code was written by an agent here and no build was run.
molodayamama commented 2026-11-25 18:54:01 +00:00 (Migrated from github.com)

Imported from DexNom/VIctory. Originally posted by molodayamama on 2026-11-25T18:54:01Z.


Verified on AMD Ryzen 5 5600 (Zen 3, AVX2) + NVIDIA GeForce RTX 4060 8 GB / Windows 10 22H2 (19045.5794) / Rust 1.98.1 (x86_64-pc-windows-msvc):

  • Clean merge with current main (2e01ab4)
  • cargo test --locked -p xtask: 4 passed, 0 failed (191 files ok)
  • cargo clippy --workspace --all-targets --locked -- -D warnings (default & --all-features): 0 warnings
  • cargo test --locked -p victory-gpu --lib shadow::: 21 passed, 0 failed (including merge_piece_matches_scalar_across_lengths and differences_are_found_as_byte_by_byte on Zen 3 AVX2)
  • Full cargo test --locked -p victory-gpu --lib on RTX 4060 (merged onto main + Agility SDK 1.614.1 via #12): 189 passed, 0 failed
<!-- greyfinch-sync:DexNom/VIctory:comment:7171554745 --> Imported from [DexNom/VIctory](https://github.com/DexNom/VIctory/pull/1#issuecomment-7171554745). Originally posted by [molodayamama](https://github.com/molodayamama) on 2026-11-25T18:54:01Z. --- Verified on **AMD Ryzen 5 5600 (Zen 3, AVX2)** + **NVIDIA GeForce RTX 4060 8 GB** / Windows 10 22H2 (`19045.5794`) / Rust `1.98.1` (`x86_64-pc-windows-msvc`): - Clean merge with current `main` (`2e01ab4`) - `cargo test --locked -p xtask`: **4 passed, 0 failed** (`191 files ok`) - `cargo clippy --workspace --all-targets --locked -- -D warnings` (default & `--all-features`): **0 warnings** - `cargo test --locked -p victory-gpu --lib shadow::`: **21 passed, 0 failed** (including `merge_piece_matches_scalar_across_lengths` and `differences_are_found_as_byte_by_byte` on Zen 3 AVX2) - Full `cargo test --locked -p victory-gpu --lib` on RTX 4060 (merged onto `main` + Agility SDK `1.614.1` via #12): **189 passed, 0 failed**
andrewDoing commented 2026-11-26 23:40:19 +00:00 (Migrated from github.com)

Imported from DexNom/VIctory. Originally posted by andrewDoing on 2026-11-26T23:40:19Z.


Independent release verification at a902405 on Ryzen 7 5700X3D: 131,104 AVX2 length/alignment oracle trials passed for first_difference, last_difference, and merge_piece, covering lengths 0–4096 and offsets 0–31. This is synthetic CPU coverage; no gameplay was tested.

Verification was AI-assisted with GPT-6.2 Astra.

<!-- greyfinch-sync:DexNom/VIctory:comment:7205746958 --> Imported from [DexNom/VIctory](https://github.com/DexNom/VIctory/pull/1#issuecomment-7205746958). Originally posted by [andrewDoing](https://github.com/andrewDoing) on 2026-11-26T23:40:19Z. --- Independent release verification at `a902405` on Ryzen 7 5700X3D: 131,104 AVX2 length/alignment oracle trials passed for `first_difference`, `last_difference`, and `merge_piece`, covering lengths 0–4096 and offsets 0–31. This is synthetic CPU coverage; no gameplay was tested. Verification was AI-assisted with GPT-6.2 Astra.
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/1:upstream-pr/1'
git switch 'upstream-pr/1'

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