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

Manually merged
github merged 1 commit from github-bot/gh-405 into main 2026-11-28 00:42:30 +00:00 AGit
Owner

@⁠Sheffy007 on GitHub · 2026-11-27 16:58 UTC · original
Sheffy007:perf/metal-encoder-residency-scoping → main · +1601 −126 · 11 files · 1 commits · merged 2026-11-28 00:38 UTC

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 #385
Refs #8, #79, #258, #395

**@⁠Sheffy007** on GitHub · 2026-11-27 16:58 UTC · [original](https://github.com/LakshanSivakumar/Native-Victory-macOS/pull/405) `Sheffy007:perf/metal-encoder-residency-scoping` → `main` · +1601 −126 · 11 files · 1 commits · merged 2026-11-28 00:38 UTC ## 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 #385 Refs #8, #79, #258, #395
When residency sets are off (VICTORY_METAL_RESIDENCY_SETS=0, and by default
on Macs with less than 32 GiB), every render and compute pass named all
~37,000 resource-heap allocations one-by-one with 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.

- Inspect emitted DXIL bitcode in Binding::of (analyze_dxil, without
  changing victory-shader or invalidating the shader disk cache) to classify
  every resource createHandleFromHeap / annotateHandle call into bounded
  Table, Pairs, or Fixed entries vs unbounded bindless access, tracking UAV
  write properties per stage (including PS-only constant-offset heap reads).
- Resolve bounded stage accesses against bound Root::Table slots and pool
  pair ranges into a shared HeapAccess slice on Dispatch and Draw.
- Replace per-command, per-resource useResource loops in victory-metal with
  encoder-level use_heaps_encoder using batch useResources:count:usage:
  - 0 heap resources named when no command in the encoder reads the heap;
  - merged, deduplicated Read and Read | Write batches over only the named
    entries for bounded passes;
  - cached contiguous Read and writable slices for unbounded bindless passes,
    keeping non-ShaderWrite textures Read.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-27 17:05:42 +00:00
github-bot force-pushed github-bot/gh-405 from 9706344f99 to 7b7cca05f7 2026-11-28 00:01:26 +00:00 Compare
github-bot referenced this pull request from a commit 2026-11-28 00:29:35 +00:00
github manually merged commit b097d35152 into main 2026-11-28 00:42:30 +00:00
Author
Owner

@⁠Olima34 on GitHub · 2026-11-28 00:37 UTC · original · requested changes

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** on GitHub · 2026-11-28 00:37 UTC · [original](https://github.com/LakshanSivakumar/Native-Victory-macOS/pull/405#pullrequestreview-6094669035) · **requested changes** 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.
Author
Owner

@⁠Olima34 on GitHub · 2026-11-28 00:40 UTC · original

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!

**@⁠Olima34** on GitHub · 2026-11-28 00:40 UTC · [original](https://github.com/LakshanSivakumar/Native-Victory-macOS/pull/405#issuecomment-7231105209) 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!
Author
Owner

@⁠ItsMariusBC on GitHub · 2026-11-28 00:45 UTC · original

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.

**@⁠ItsMariusBC** on GitHub · 2026-11-28 00:45 UTC · [original](https://github.com/LakshanSivakumar/Native-Victory-macOS/pull/405#issuecomment-7231172822) 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.
This discussion has been locked. Commenting is limited to contributors.
No description provided.