[pr-perf] Eliminate per-submission allocation churn and O(N^2) grouping in card_before, card_record, and send::take #2587

Closed
steven-seagull27 wants to merge 1 commit from upstream-pr/2587 into main
steven-seagull27 commented 2026-11-29 14:41:07 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by steven-seagull27 on 2026-11-29T14:41:07Z.


Summary

Eliminates per-submission heap allocation churn and O(N²) compare-list grouping overhead on the GPU submission hot path (Host::card_before, Host::card_record, and host::send::{take, Own::record}) while preserving bit-identical command ordering, coalescing, batching, and barrier semantics.

What Changed

  1. Zero-copy CardDeclared / CardLooked borrowing in Host::card_before (crates/victory-gpu/src/host.rs)

    • Previously, card_take cloned every (Arc<Shadow>, Vec<(usize, usize)>) in declared just to filter .carded(), and cloned picked.looked into owned Vecs even on the synchronous card_before path where card_record consumes them immediately on the same thread.
    • Introduced CardDeclared<'a> and CardLooked<'a> (Borrowed / Owned) so card_before borrows directly from &[Declared] and &[picked::Range] whenever !picked::lands() || picked.written.is_empty(), while card_take (used by cross-thread Handoff) continues to produce an owned CardTake<'static>.
  2. Allocation-free range normalization & O(N) flat compare-list batching in Host::card_record (crates/victory-gpu/src/host.rs)

    • Added normalized_ranges which fast-paths 0-range, 1-range, and already-sorted strictly disjoint slices (w[0] <= w[1] && w[0].1 < w[1].0) by returning the input slice directly with zero heap allocations, and otherwise sorts and coalesces in place inside a reusable thread-local scratch Vec (eliminating both the ranges.clone() and separate spans Vec).
    • Replaced the O(N²) groups.iter_mut().find(...) + per-group vec![idx] compare-list batcher with CardBatcher: a flat intrusive singly-linked node array (groups + nodes) with a consecutive-key fast path, linear scan for ≤8 distinct keys, and automatic HashMap<CardBatchKey, usize, BuildHasherDefault<AddressHash>> indexing beyond 8 distinct keys. Preserves exact first-seen group order and insertion order within each group with zero per-group Vec allocations.
    • Reused prepared_ranges, range normalization scratch, and CardBatcher via RAII-guarded thread-local CardRecordScratch (draining/clearing all Arc<Shadow>s on exit and capping retained capacity at 4096 entries so outlier spikes are released). Also pre-reserves plan.ranges under CARD_WORK.
  3. Flattened runs and reusable scratch buffers in host::send (crates/victory-gpu/src/host/send.rs)

    • Flattened per-copy Copy.runs: Vec<(usize, u64, usize)> into a single contiguous PlanBuffers.runs buffer indexed by (runs_start, runs_len) per Copy, recycled via SPARE_PLANS on Drop (capped at MAX_SPARE_PLANS = 4, MAX_SPARE_COPIES = 4096, MAX_SPARE_RUNS = 16_384, and cleared in send::trim() under critical commit).
    • Eliminated the intermediate work: Vec<(usize, &[(usize, usize)], usize)> allocation in send::take by indexing chunk_plans directly inside run_scatter.
    • Reused chunk_plans, moves, copy_pieces, and copy_tasks via thread-local TakeScratchGuard (with pack_copy_tasks_into filling scratch directly, and std::mem::take when VICTORY_SEND_BESIDE=1 hands moves off to worker threads) and reused first/last D3D12_RESOURCE_BARRIER Vecs in Own::record via thread-local RecordScratchGuard (capacity-capped so spikes are not retained).

Synthetic Release Microbenchmarks

Measured with:

cargo test --release --locked -j 2 -p victory-gpu --lib -- before_vs_after --ignored --nocapture --test-threads=1

Each benchmark runs 3,000 synthetic submissions (30 submissions/frame × 100 frames) comparing the exact previous allocation/grouping logic against the optimized path and asserting identical checksums across 3 repeated runs:

Synthetic Benchmark (30 subs/frame) Before (median) After (median) Speedup
card_record bookkeeping (150 declared copies + 200 compare items across 64 keys) 12.66 µs/sub (379.7 µs/frame) 1.78 µs/sub (53.5 µs/frame) 7.1× (6.22×–7.15×)
send::take planning (150 dirty copies, mixed short/long runs + pack_copy_tasks) 5.27 µs/sub (158.0 µs/frame) 0.94 µs/sub (28.1 µs/frame) 5.6× (5.32×–5.67×)
Combined (bookkeeping + planning alone) 17.93 µs/sub (537.7 µs/frame) 2.72 µs/sub (81.6 µs/frame) 6.6× (-456 µs/frame)

(In addition to the measured bookkeeping and planning gains above, card_before eliminates per-submission Declared Arc<Shadow>/Vec clones and Own::record eliminates per-submission barrier Vec allocations.)

Verification

  • cargo test --locked -j 2 -p victory-gpu --lib -- send:: --test-threads=1: 4 passed, 0 failed (including new equivalence & capacity-cap tests plan_dirty_ranges_matches_reference_across_shapes and pack_copy_tasks_into_reuses_buffers_and_matches_reference).
  • cargo test --locked -j 2 -p victory-gpu --lib -- host:: --test-threads=1: 216 passed, 0 failed (including new equivalence, fuzz, and capacity-cap tests normalized_ranges_matches_reference_across_shapes and card_batcher_matches_reference_grouping_and_order).
  • cargo test --release --locked -j 2 -p victory-gpu --lib -- send:: --test-threads=1 and normalized_ranges card_batcher: all passed.
  • cargo clippy --locked -j 2 -p victory-gpu --lib --tests: 0 new warnings in host.rs or host/send.rs.
  • cargo check --locked -j 2 -p victory-gpu --lib --features diagnostics: 0 errors/warnings in touched code (note: pre-existing unrelated compile errors exist on main in copystat.rs:1349 and host.rs submit timing() shadowing under --features diagnostics).
  • git diff --check: clean.
<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:issue:5551779224 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/2587). Originally posted by [steven-seagull27](https://github.com/steven-seagull27) on 2026-11-29T14:41:07Z. --- ## Summary Eliminates per-submission heap allocation churn and O(N²) compare-list grouping overhead on the GPU submission hot path (`Host::card_before`, `Host::card_record`, and `host::send::{take, Own::record}`) while preserving bit-identical command ordering, coalescing, batching, and barrier semantics. ### What Changed 1. **Zero-copy `CardDeclared` / `CardLooked` borrowing in `Host::card_before` (`crates/victory-gpu/src/host.rs`)** - Previously, `card_take` cloned every `(Arc<Shadow>, Vec<(usize, usize)>)` in `declared` just to filter `.carded()`, and cloned `picked.looked` into owned `Vec`s even on the synchronous `card_before` path where `card_record` consumes them immediately on the same thread. - Introduced `CardDeclared<'a>` and `CardLooked<'a>` (`Borrowed` / `Owned`) so `card_before` borrows directly from `&[Declared]` and `&[picked::Range]` whenever `!picked::lands() || picked.written.is_empty()`, while `card_take` (used by cross-thread `Handoff`) continues to produce an owned `CardTake<'static>`. 2. **Allocation-free range normalization & O(N) flat compare-list batching in `Host::card_record` (`crates/victory-gpu/src/host.rs`)** - Added `normalized_ranges` which fast-paths 0-range, 1-range, and already-sorted strictly disjoint slices (`w[0] <= w[1] && w[0].1 < w[1].0`) by returning the input slice directly with zero heap allocations, and otherwise sorts and coalesces in place inside a reusable thread-local scratch `Vec` (eliminating both the `ranges.clone()` and separate `spans` `Vec`). - Replaced the O(N²) `groups.iter_mut().find(...)` + per-group `vec![idx]` compare-list batcher with `CardBatcher`: a flat intrusive singly-linked node array (`groups` + `nodes`) with a consecutive-key fast path, linear scan for ≤8 distinct keys, and automatic `HashMap<CardBatchKey, usize, BuildHasherDefault<AddressHash>>` indexing beyond 8 distinct keys. Preserves exact first-seen group order and insertion order within each group with zero per-group `Vec` allocations. - Reused `prepared_ranges`, range normalization scratch, and `CardBatcher` via RAII-guarded thread-local `CardRecordScratch` (draining/clearing all `Arc<Shadow>`s on exit and capping retained capacity at `4096` entries so outlier spikes are released). Also pre-reserves `plan.ranges` under `CARD_WORK`. 3. **Flattened `runs` and reusable scratch buffers in `host::send` (`crates/victory-gpu/src/host/send.rs`)** - Flattened per-copy `Copy.runs: Vec<(usize, u64, usize)>` into a single contiguous `PlanBuffers.runs` buffer indexed by `(runs_start, runs_len)` per `Copy`, recycled via `SPARE_PLANS` on `Drop` (capped at `MAX_SPARE_PLANS = 4`, `MAX_SPARE_COPIES = 4096`, `MAX_SPARE_RUNS = 16_384`, and cleared in `send::trim()` under critical commit). - Eliminated the intermediate `work: Vec<(usize, &[(usize, usize)], usize)>` allocation in `send::take` by indexing `chunk_plans` directly inside `run_scatter`. - Reused `chunk_plans`, `moves`, `copy_pieces`, and `copy_tasks` via thread-local `TakeScratchGuard` (with `pack_copy_tasks_into` filling scratch directly, and `std::mem::take` when `VICTORY_SEND_BESIDE=1` hands `moves` off to worker threads) and reused `first`/`last` `D3D12_RESOURCE_BARRIER` `Vec`s in `Own::record` via thread-local `RecordScratchGuard` (capacity-capped so spikes are not retained). ## Synthetic Release Microbenchmarks Measured with: ```powershell cargo test --release --locked -j 2 -p victory-gpu --lib -- before_vs_after --ignored --nocapture --test-threads=1 ``` Each benchmark runs 3,000 synthetic submissions (30 submissions/frame × 100 frames) comparing the exact previous allocation/grouping logic against the optimized path and asserting identical checksums across 3 repeated runs: | Synthetic Benchmark (30 subs/frame) | Before (median) | After (median) | Speedup | |---|---:|---:|---:| | `card_record` bookkeeping (150 declared copies + 200 compare items across 64 keys) | 12.66 µs/sub (379.7 µs/frame) | 1.78 µs/sub (53.5 µs/frame) | **7.1×** (6.22×–7.15×) | | `send::take` planning (150 dirty copies, mixed short/long runs + `pack_copy_tasks`) | 5.27 µs/sub (158.0 µs/frame) | 0.94 µs/sub (28.1 µs/frame) | **5.6×** (5.32×–5.67×) | | **Combined (bookkeeping + planning alone)** | **17.93 µs/sub (537.7 µs/frame)** | **2.72 µs/sub (81.6 µs/frame)** | **6.6× (-456 µs/frame)** | *(In addition to the measured bookkeeping and planning gains above, `card_before` eliminates per-submission `Declared` `Arc<Shadow>`/`Vec` clones and `Own::record` eliminates per-submission barrier `Vec` allocations.)* ## Verification - `cargo test --locked -j 2 -p victory-gpu --lib -- send:: --test-threads=1`: **4 passed, 0 failed** (including new equivalence & capacity-cap tests `plan_dirty_ranges_matches_reference_across_shapes` and `pack_copy_tasks_into_reuses_buffers_and_matches_reference`). - `cargo test --locked -j 2 -p victory-gpu --lib -- host:: --test-threads=1`: **216 passed, 0 failed** (including new equivalence, fuzz, and capacity-cap tests `normalized_ranges_matches_reference_across_shapes` and `card_batcher_matches_reference_grouping_and_order`). - `cargo test --release --locked -j 2 -p victory-gpu --lib -- send:: --test-threads=1` and `normalized_ranges card_batcher`: **all passed**. - `cargo clippy --locked -j 2 -p victory-gpu --lib --tests`: **0 new warnings** in `host.rs` or `host/send.rs`. - `cargo check --locked -j 2 -p victory-gpu --lib --features diagnostics`: **0 errors/warnings in touched code** (note: pre-existing unrelated compile errors exist on `main` in `copystat.rs:1349` and `host.rs` `submit` `timing()` shadowing under `--features diagnostics`). - `git diff --check`: clean.
erLCoder commented 2026-11-29 18:57:58 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by erLCoder on 2026-11-29T18:57:58Z.


<html>

Hardware testing — RTX 5060 Ti 16 GB / Ryzen 5 3600

Tested PR #2587 (90400203) on physical NVIDIA hardware.

System configuration:

  • GPU: NVIDIA RTX 5060 Ti 16 GB

  • CPU: AMD Ryzen 5 3600 (6C/12T)

  • RAM: 32 GB DDR4-3200

  • OS: Windows 10 Enterprise 22H2

  • NVIDIA driver: 621.40

  • Series S profile, DLSS Quality, Frame Generation disabled

  • Pipeline workers: 3

  • DirectStorage workers: 4

  • **Results during the boat sequence (last 60 seconds):**
    Metric PR #2504 PR #2587
    Median FPS 12.65 14.10
    Frame time 79.15 ms 71.10 ms
    CPU submission 71.50 ms 65.15 ms
    Resource refresh 23.10 ms 22.25 ms
    GPU idle 43.30 ms 37.60 ms
    GPU fetch 8.40 ms 7.40 ms
    Card copies 11.30 ms 9.60 ms
    Draw calls per frame 3878 3924
    Frames exceeding 100 ms 87 34
    PSO creation failures 0 0

    Both PRs were tested independently on the same base, which includes PR #2578 and a local fix preventing D3D12 initialization during pipeline failure reporting.

    Compared with the #2504 build, #2587 showed approximately 11.5% higher median FPS, lower CPU submission time, reduced GPU idle time, and noticeably fewer long frames despite a comparable draw-call count.

    The game successfully reached gameplay without crashing during this test.

    Limitations: This was a preliminary hardware comparison, not a controlled benchmark against unmodified upstream. The shader cache was warmer during the #2587 run, and the scenes were not frame-identical. Therefore, the measured difference cannot be attributed exclusively to this PR.

    Nevertheless, the results are promising, particularly on an older six-core CPU. This optimization deserves further hardware testing.

    Thanks for working on the CPU submission bottleneck!

    </html>
<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:comment:7260898851 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/2587#issuecomment-7260898851). Originally posted by [erLCoder](https://github.com/erLCoder) on 2026-11-29T18:57:58Z. --- <html> <body> <!--StartFragment--><h3><span>Hardware testing — RTX 5060 Ti 16 GB / Ryzen 5 3600</span></h3><p><span>Tested PR #2587 (</span><code><span>90400203</span></code><span>) on physical NVIDIA hardware.</span></p><p><strong><span>System configuration:</span></strong></p><ul><li><p><span>GPU: NVIDIA RTX 5060 Ti 16 GB</span></p></li><li><p><span>CPU: AMD Ryzen 5 3600 (6C/12T)</span></p></li><li><p><span>RAM: 32 GB DDR4-3200</span></p></li><li><p><span>OS: Windows 10 Enterprise 22H2</span></p></li><li><p><span>NVIDIA driver: 621.40</span></p></li><li><p><span>Series S profile, DLSS Quality, Frame Generation disabled</span></p></li><li><p><span>Pipeline workers: 3</span></p></li><li><p><span>DirectStorage workers: 4</span></p></li> **Results during the boat sequence (last 60 seconds):** | Metric | PR #2504 | PR #2587 | |---|---:|---:| | Median FPS | 12.65 | 14.10 | | Frame time | 79.15 ms | 71.10 ms | | CPU submission | 71.50 ms | 65.15 ms | | Resource refresh | 23.10 ms | 22.25 ms | | GPU idle | 43.30 ms | 37.60 ms | | GPU fetch | 8.40 ms | 7.40 ms | | Card copies | 11.30 ms | 9.60 ms | | Draw calls per frame | 3878 | 3924 | | Frames exceeding 100 ms | 87 | 34 | | PSO creation failures | 0 | 0 | <p><span>Both PRs were tested independently on the same base, which includes PR #2578 and a local fix preventing D3D12 initialization during pipeline failure reporting.</span></p><p><span>Compared with the #2504 build, #2587 showed approximately 11.5% higher median FPS, lower CPU submission time, reduced GPU idle time, and noticeably fewer long frames despite a comparable draw-call count.</span></p><p><span>The game successfully reached gameplay without crashing during this test.</span></p><p><strong><span>Limitations:</span></strong><span> This was a preliminary hardware comparison, not a controlled benchmark against unmodified upstream. The shader cache was warmer during the #2587 run, and the scenes were not frame-identical. Therefore, the measured difference cannot be attributed exclusively to this PR.</span></p><p><span>Nevertheless, the results are promising, particularly on an older six-core CPU. This optimization deserves further hardware testing.</span></p><p><span>Thanks for working on the CPU submission bottleneck!</span></p><!--EndFragment--> </body> </html>
steven-seagull27 commented 2026-11-29 20:35:20 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by steven-seagull27 on 2026-11-29T20:35:20Z.


Thanks @erLCoder for testing #2587 (90400203) on your Ryzen 5 3600 / RTX 5060 Ti setup and sharing the breakdown! Really glad to see lower CPU submission time, fewer >100 ms frames (87 -> 34), and 0 crashes / PSO failures on a 6-core CPU. Appreciate you noting the warm-cache / scene caveats too — additional controlled A/B runs on main are always welcome.

<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:comment:7262200349 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/2587#issuecomment-7262200349). Originally posted by [steven-seagull27](https://github.com/steven-seagull27) on 2026-11-29T20:35:20Z. --- Thanks @erLCoder for testing `#2587` (`90400203`) on your Ryzen 5 3600 / RTX 5060 Ti setup and sharing the breakdown! Really glad to see lower CPU submission time, fewer >100 ms frames (`87 -> 34`), and 0 crashes / PSO failures on a 6-core CPU. Appreciate you noting the warm-cache / scene caveats too — additional controlled A/B runs on `main` are always welcome.
steven-seagull27 commented 2026-11-30 00:18:45 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by steven-seagull27 on 2026-11-30T00:18:45Z.


Rebased cleanly onto origin/main (41adb551, v2026.11.29.05).

Conflict resolution

  • crates/victory-gpu/src/host/send.rs: preserved #2509's parallel_copy_work threshold in send::take (passing scratch.0.moves.len(), summary.total_run_bytes, and !chunk_plans.is_empty()), keeping both #2509's many-small-runs parallelization and #2587's recycled TakeScratch / PlanBuffers.
  • crates/victory-gpu/src/host.rs: auto-merged cleanly, preserving card_before borrowing, flat intrusive CardBatcher, and zero-alloc normalized_ranges.

Verification

  • cargo test --locked -j 3 -p victory-gpu --lib -- send:: --test-threads=1: 5 passed, 0 failed (including parallel_copy_threshold_requires_multiple_tasks, pack_copy_tasks_into_reuses_buffers_and_matches_reference, and plan_dirty_ranges_matches_reference_across_shapes).
  • cargo test --locked -j 3 -p victory-gpu --lib -- host:: --test-threads=1: 218 passed (host::batch:: / card_before tests all passed; the 1 unrelated host::card_steps::tests::places_written_after_sending_are_learned failure under single-thread heap address reuse passes 1/1 in isolation).
  • cargo check --locked -j 3 -p victory-gpu --lib --features diagnostics: passed.
  • cargo clippy --locked -j 3 -p victory-gpu --lib --tests: 0 new warnings in touched files.
  • git diff --check origin/main..HEAD: clean.
<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:comment:7265156253 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/2587#issuecomment-7265156253). Originally posted by [steven-seagull27](https://github.com/steven-seagull27) on 2026-11-30T00:18:45Z. --- Rebased cleanly onto `origin/main` (`41adb551`, `v2026.11.29.05`). ### Conflict resolution - `crates/victory-gpu/src/host/send.rs`: preserved `#2509`'s `parallel_copy_work` threshold in `send::take` (passing `scratch.0.moves.len()`, `summary.total_run_bytes`, and `!chunk_plans.is_empty()`), keeping both `#2509`'s many-small-runs parallelization and `#2587`'s recycled `TakeScratch` / `PlanBuffers`. - `crates/victory-gpu/src/host.rs`: auto-merged cleanly, preserving `card_before` borrowing, flat intrusive `CardBatcher`, and zero-alloc `normalized_ranges`. ### Verification - `cargo test --locked -j 3 -p victory-gpu --lib -- send:: --test-threads=1`: 5 passed, 0 failed (including `parallel_copy_threshold_requires_multiple_tasks`, `pack_copy_tasks_into_reuses_buffers_and_matches_reference`, and `plan_dirty_ranges_matches_reference_across_shapes`). - `cargo test --locked -j 3 -p victory-gpu --lib -- host:: --test-threads=1`: 218 passed (`host::batch::` / `card_before` tests all passed; the 1 unrelated `host::card_steps::tests::places_written_after_sending_are_learned` failure under single-thread heap address reuse passes 1/1 in isolation). - `cargo check --locked -j 3 -p victory-gpu --lib --features diagnostics`: passed. - `cargo clippy --locked -j 3 -p victory-gpu --lib --tests`: 0 new warnings in touched files. - `git diff --check origin/main..HEAD`: clean.
steven-seagull27 commented 2026-11-30 18:19:03 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by steven-seagull27 on 2026-11-30T18:19:03Z.


Closing as merged — commit 90400203 landed on main via 81611478 (Merge PR #2587). Thanks again to @erLCoder for the hardware testing and @trustno1-coder for merging!

<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:comment:7287668167 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/2587#issuecomment-7287668167). Originally posted by [steven-seagull27](https://github.com/steven-seagull27) on 2026-11-30T18:19:03Z. --- Closing as merged — commit `90400203` landed on `main` via `81611478` (`Merge PR #2587`). Thanks again to @erLCoder for the hardware testing and @trustno1-coder for merging!

Pull request closed

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
trustno1-coder/VIctory-NVIDIA!2587
No description provided.