metal, gpu: scope per-encoder heap residency and batch useResources (#382) #405

Merged
Sheffy007 merged 1 commit from upstream-pr/405 into main 2026-11-28 00:38:42 +00:00
Sheffy007 commented 2026-11-27 16:58:23 +00:00 (Migrated from github.com)

Imported from LakshanSivakumar/Native-Victory-macOS. Originally posted by Sheffy007 on 2026-11-27T16:58:23Z.


Summary

When residency sets are disabled (VICTORY_METAL_RESIDENCY_SETS=0, and by default on Macs with less than 32 GiB RAM), every render and compute pass named all ~37,000 resource-heap allocations one-by-one with MTLResourceUsage::Read | Write via useResource, costing ~155 ms per render pass in the kernel even when a pass's shaders never touched ResourceDescriptorHeap or only indexed bounded descriptor-table entries (docs/metal-backend.md).

This PR scopes per-encoder heap residency to the pass's proven heap accesses and batches useResources:

  1. Zero-invalidation DXIL heap-access analysis (Binding::of, analyze_dxil):
    • Inspects victory-shader's emitted DXIL bitcode alongside HostShader::user_data (without modifying victory-shader or invalidating testers' warm shader disk caches) to classify every resource dx.op.createHandleFromHeap / dx.op.annotateHandle call per stage (VS/MS, PS, CS):
      • Bounded Table { slot, offset, writes }, Pairs { writes } (memory_handle / ROOT_SRV_VIEW / ROOT_UAV_VIEW), and Fixed { index, writes } (including Select and cycle-checked Phis).
      • unbounded / unbounded_writes fallback whenever any resource heap index is dynamic or unrecognized, tracking UAV write flags (ResourceProperties bit 0x1000).
      • Preserves ps_heap_access on the pipeline's graphics Binding even when ps_binding is filtered to None because the pixel stage has no user-data/views of its own.
  2. Zero-allocation per-pass range resolution (NativeHost::execute, HeapAccess):
    • Resolves StageHeapAccess against bound Root::Table slots and [bh.count .. bh.count + 2 * pairs) into a shared Vec<HeapRange> buffer per execute call, attaching HeapAccess<'a> slices to Dispatch and Draw.
  3. Scoped & batched encoder residency (victory-metal::gfx):
    • Tracks can_write (true for buffers and ShaderWrite textures, false for read-only SRV textures) and caches lazy contiguous (read_only, writable) resource pointer slices on Heap.
    • Replaces per-draw/per-dispatch use_heap_encoder loops with encoder-level use_heaps_encoder using Metal's batch useResources:count:usage: / useResources:count:usage:stages::
      • 0 heap resources named when no active draw/dispatch in the encoder accesses heaps.resource;
      • Merged, deduplicated Read and Read | Write batches over only the named entries for bounded passes (preserving Metal's automatic UAV Write -> SRV Read hazard ordering when !set_on_queue);
      • Cached contiguous Read + Read | Write batch slices for unbounded bindless passes, keeping non-ShaderWrite textures Read instead of Read | Write.
    • MTLResidencySet mode (residency_sets == true) is unchanged.

Measurements & Verification

  • Added end-to-end Metal GPU test encoder_residency_scopes_bounded_passes_and_batches_bindless_passes covering:
    1. Render pass with set_heaps bound whose VS/PS do not read the heap (0 heap resources named vs 259);
    2. Bounded compute UAV-texture copy followed by bounded PS SRV sample in one submission (3 + 2 = 5 heap resources named vs 518, verifying UAV Write -> SRV Read hazard ordering without residency sets);
    3. Bounded Lower::memory + view_addresses compute pass (3 heap resources named, 0 of 256 unrelated textures);
    4. Dynamic waterfall SRV read + bounded UAV store (unbounded && !unbounded_writes, batched useResources over 260 resources).
  • Added ignored release benchmark per_encoder_residency_10k_textures_benchmark:
    • 200 alternating passes (190 bounded compute/render passes + 10 bindless render passes) over a 10,000-texture heap (with_residency_sets(false)): 148.38 ms total (0.742 ms/pass), naming 100,320 heap resources vs 2,000,400 unscoped (20x reduction; 0–3 resources per bounded pass).
  • Verified:
    • cargo test -p victory-hle -p victory -p victory-gpu -p victory-metal -p victory-shader -p xtask
    • cargo clippy --workspace --all-targets --target x86_64-pc-windows-gnullvm -- -D warnings
    • cargo clippy --workspace --all-targets --all-features --target x86_64-pc-windows-gnullvm -- -D warnings
    • cargo xtask policy

cc @Olima34

Closes #382
Refs #8, #79, #258, #392

<!-- greyfinch-sync:LakshanSivakumar/Native-Victory-macOS:issue:5530295393 --> Imported from [LakshanSivakumar/Native-Victory-macOS](https://github.com/LakshanSivakumar/Native-Victory-macOS/pull/405). Originally posted by [Sheffy007](https://github.com/Sheffy007) on 2026-11-27T16:58:23Z. --- ## Summary When residency sets are disabled (`VICTORY_METAL_RESIDENCY_SETS=0`, and by default on Macs with less than 32 GiB RAM), every render and compute pass named all ~37,000 resource-heap allocations one-by-one with `MTLResourceUsage::Read | Write` via `useResource`, costing ~155 ms per render pass in the kernel even when a pass's shaders never touched `ResourceDescriptorHeap` or only indexed bounded descriptor-table entries (`docs/metal-backend.md`). This PR scopes per-encoder heap residency to the pass's proven heap accesses and batches `useResources`: 1. **Zero-invalidation DXIL heap-access analysis (`Binding::of`, `analyze_dxil`):** - Inspects `victory-shader`'s emitted DXIL bitcode alongside `HostShader::user_data` (without modifying `victory-shader` or invalidating testers' warm shader disk caches) to classify every resource `dx.op.createHandleFromHeap` / `dx.op.annotateHandle` call per stage (`VS`/`MS`, `PS`, `CS`): - Bounded `Table { slot, offset, writes }`, `Pairs { writes }` (`memory_handle` / `ROOT_SRV_VIEW` / `ROOT_UAV_VIEW`), and `Fixed { index, writes }` (including `Select` and cycle-checked `Phi`s). - `unbounded` / `unbounded_writes` fallback whenever any resource heap index is dynamic or unrecognized, tracking UAV write flags (`ResourceProperties` bit `0x1000`). - Preserves `ps_heap_access` on the pipeline's graphics `Binding` even when `ps_binding` is filtered to `None` because the pixel stage has no user-data/views of its own. 2. **Zero-allocation per-pass range resolution (`NativeHost::execute`, `HeapAccess`):** - Resolves `StageHeapAccess` against bound `Root::Table` slots and `[bh.count .. bh.count + 2 * pairs)` into a shared `Vec<HeapRange>` buffer per `execute` call, attaching `HeapAccess<'a>` slices to `Dispatch` and `Draw`. 3. **Scoped & batched encoder residency (`victory-metal::gfx`):** - Tracks `can_write` (`true` for buffers and `ShaderWrite` textures, `false` for read-only SRV textures) and caches lazy contiguous `(read_only, writable)` resource pointer slices on `Heap`. - Replaces per-draw/per-dispatch `use_heap_encoder` loops with encoder-level `use_heaps_encoder` using Metal's batch `useResources:count:usage:` / `useResources:count:usage:stages:`: - **0 heap resources named** when no active draw/dispatch in the encoder accesses `heaps.resource`; - **Merged, deduplicated `Read` and `Read | Write` batches** over only the named entries for bounded passes (preserving Metal's automatic UAV Write -> SRV Read hazard ordering when `!set_on_queue`); - **Cached contiguous `Read` + `Read | Write` batch slices** for unbounded bindless passes, keeping non-`ShaderWrite` textures `Read` instead of `Read | Write`. - `MTLResidencySet` mode (`residency_sets == true`) is unchanged. ## Measurements & Verification - Added end-to-end Metal GPU test `encoder_residency_scopes_bounded_passes_and_batches_bindless_passes` covering: 1. Render pass with `set_heaps` bound whose VS/PS do not read the heap (`0` heap resources named vs `259`); 2. Bounded compute UAV-texture copy followed by bounded PS SRV sample in one submission (`3 + 2 = 5` heap resources named vs `518`, verifying UAV Write -> SRV Read hazard ordering without residency sets); 3. Bounded `Lower::memory` + `view_addresses` compute pass (`3` heap resources named, `0` of `256` unrelated textures); 4. Dynamic waterfall SRV read + bounded UAV store (`unbounded && !unbounded_writes`, batched `useResources` over `260` resources). - Added ignored release benchmark `per_encoder_residency_10k_textures_benchmark`: - 200 alternating passes (190 bounded compute/render passes + 10 bindless render passes) over a 10,000-texture heap (`with_residency_sets(false)`): **148.38 ms total (0.742 ms/pass)**, naming **100,320** heap resources vs **2,000,400** unscoped (20x reduction; 0–3 resources per bounded pass). - Verified: - `cargo test -p victory-hle -p victory -p victory-gpu -p victory-metal -p victory-shader -p xtask` - `cargo clippy --workspace --all-targets --target x86_64-pc-windows-gnullvm -- -D warnings` - `cargo clippy --workspace --all-targets --all-features --target x86_64-pc-windows-gnullvm -- -D warnings` - `cargo xtask policy` cc @Olima34 Closes #382 Refs #8, #79, #258, #392
Olima34 commented 2026-11-28 00:37:09 +00:00 (Migrated from github.com)

Imported from LakshanSivakumar/Native-Victory-macOS. Originally posted by Olima34 on 2026-11-28T00:37:09Z.

Review: CHANGES_REQUESTED


Thanks for this PR! We're helping the maintainer clear the queue tonight, and main has moved a lot (the preview branch landed as 86cefd22, then a batch of PRs; main is now a6a58361). This branch now conflicts with main in crates/victory-gpu/src/native/heap_tests.rs.

Could you merge current main into the branch (a merge commit is fine, no need to rebase) and resolve the conflict? It looks like tests appended at the same spot as tests that landed on main; keep both sides. Once GitHub shows it as mergeable and CI is green on the new head, we'll read it through and merge it if it holds up.

<!-- greyfinch-sync:LakshanSivakumar/Native-Victory-macOS:review:6094669035 --> Imported from [LakshanSivakumar/Native-Victory-macOS](https://github.com/LakshanSivakumar/Native-Victory-macOS/pull/405#pullrequestreview-6094669035). Originally posted by [Olima34](https://github.com/Olima34) on 2026-11-28T00:37:09Z. **Review:** CHANGES_REQUESTED --- Thanks for this PR! We're helping the maintainer clear the queue tonight, and main has moved a lot (the preview branch landed as 86cefd22, then a batch of PRs; main is now a6a58361). This branch now conflicts with main in `crates/victory-gpu/src/native/heap_tests.rs`. Could you merge current `main` into the branch (a merge commit is fine, no need to rebase) and resolve the conflict? It looks like tests appended at the same spot as tests that landed on main; keep both sides. Once GitHub shows it as mergeable and CI is green on the new head, we'll read it through and merge it if it holds up.
Olima34 commented 2026-11-28 00:40:37 +00:00 (Migrated from github.com)

Imported from LakshanSivakumar/Native-Victory-macOS. Originally posted by Olima34 on 2026-11-28T00:40:37Z.


Please disregard my change request above: it crossed with the maintainer merging this PR (land/prs-2), so the conflict is resolved on main. Thanks!

<!-- greyfinch-sync:LakshanSivakumar/Native-Victory-macOS:comment:7231105209 --> Imported from [LakshanSivakumar/Native-Victory-macOS](https://github.com/LakshanSivakumar/Native-Victory-macOS/pull/405#issuecomment-7231105209). Originally posted by [Olima34](https://github.com/Olima34) on 2026-11-28T00:40:37Z. --- Please disregard my change request above: it crossed with the maintainer merging this PR (land/prs-2), so the conflict is resolved on main. Thanks!
ItsMariusBC commented 2026-11-28 00:45:46 +00:00 (Migrated from github.com)

Imported from LakshanSivakumar/Native-Victory-macOS. Originally posted by ItsMariusBC on 2026-11-28T00:45:46Z.


A game data point for this from a 24 GB Mac, where the default is useResource per encoder. It was taken before the merge, on the PR head as it was then.

Apple M5 Pro, 24 GB, macOS 27.2.1, main b998bb65 + this PR at 9706344f, Series S, windowed, warm shader cache (no translation in the runs), VICTORY_HOLD_BYTE=1471b6330:1 VICTORY_TEXTURE_DROP_TOP_MIP=1, --seconds 480. The build also carried a local change that is off unless a switch is set.

Per command buffer, in the world (VICTORY_TRACE_COMMITS=1 VICTORY_PASSES_PER_BUFFER=1, the 370 s from the first indirect rectangle-list draw to the end):

main, the same measurement earlier (posted on #8) this PR
Command buffers 10,964 13,729
Sum of gpu_ms 179 s 118 s
Over 100 ms the longest all sat between 145 and 163 ms 891, 109 s in all; 808 of them between 100 and 140 ms
Median, p90, p99 not kept 0.0, 0.7, 129.7 ms
Failed 0 0

So nine buffers in ten are now near free, and what is left of the cost is in 891 of them at 100 to 140 ms each. I take those to be the unbounded passes, but the trace does not say which pass a buffer holds, so that is a guess.

The frame rate did not follow. World frames in 480 s runs without the trace: 32 and 47 with this PR, 11 on main b998bb65 earlier the same evening, about 30 on main in the morning. That spread is too wide to show a gain.

What the trace says about why: the GPU is busy 118 s of the 370, and a buffer takes 263 ms from commit to done at the median (p90 1,018 ms) while its gpu_ms is near zero. During the run the free memory level (kern.memorystatus_level) was 2 to 3 % and 6.4 GB of swap was in use. So on 24 GB the time is no longer in the passes. I did not measure where it goes instead.

Before the world: 19,498 buffers, 2.4 s of gpu_ms in all, the longest 30 ms. No GPU error in any of these runs, and the load reaches frame 1984 at about +83 s against +112 s on main.

I can attach the logs.

<!-- greyfinch-sync:LakshanSivakumar/Native-Victory-macOS:comment:7231172822 --> Imported from [LakshanSivakumar/Native-Victory-macOS](https://github.com/LakshanSivakumar/Native-Victory-macOS/pull/405#issuecomment-7231172822). Originally posted by [ItsMariusBC](https://github.com/ItsMariusBC) on 2026-11-28T00:45:46Z. --- A game data point for this from a 24 GB Mac, where the default is `useResource per encoder`. It was taken before the merge, on the PR head as it was then. Apple M5 Pro, 24 GB, macOS 27.2.1, main `b998bb65` + this PR at `9706344f`, Series S, windowed, warm shader cache (no translation in the runs), `VICTORY_HOLD_BYTE=1471b6330:1 VICTORY_TEXTURE_DROP_TOP_MIP=1`, `--seconds 480`. The build also carried a local change that is off unless a switch is set. **Per command buffer, in the world** (`VICTORY_TRACE_COMMITS=1 VICTORY_PASSES_PER_BUFFER=1`, the 370 s from the first indirect rectangle-list draw to the end): | | main, the same measurement earlier (posted on #8) | this PR | | --- | --- | --- | | Command buffers | 10,964 | 13,729 | | Sum of `gpu_ms` | 179 s | 118 s | | Over 100 ms | the longest all sat between 145 and 163 ms | 891, 109 s in all; 808 of them between 100 and 140 ms | | Median, p90, p99 | not kept | 0.0, 0.7, 129.7 ms | | Failed | 0 | 0 | So nine buffers in ten are now near free, and what is left of the cost is in 891 of them at 100 to 140 ms each. I take those to be the unbounded passes, but the trace does not say which pass a buffer holds, so that is a guess. **The frame rate did not follow.** World frames in 480 s runs without the trace: 32 and 47 with this PR, 11 on main `b998bb65` earlier the same evening, about 30 on main in the morning. That spread is too wide to show a gain. What the trace says about why: the GPU is busy 118 s of the 370, and a buffer takes 263 ms from commit to done at the median (p90 1,018 ms) while its `gpu_ms` is near zero. During the run the free memory level (`kern.memorystatus_level`) was 2 to 3 % and 6.4 GB of swap was in use. So on 24 GB the time is no longer in the passes. I did not measure where it goes instead. Before the world: 19,498 buffers, 2.4 s of `gpu_ms` in all, the longest 30 ms. No GPU error in any of these runs, and the load reaches frame 1984 at about +83 s against +112 s on main. I can attach the logs.
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
LakshanSivakumar/Native-Victory-macOS!405
No description provided.