Skip to content

perf(gpu): make a heap sync's changed slots under one hold of the slot lock - #409

Draft
hackgods wants to merge 5 commits into
pragyaangaur:mainfrom
hackgods:perf/heap-sync
Draft

hackgods wants to merge 5 commits into
pragyaangaur:mainfrom
hackgods:perf/heap-sync

Conversation

@hackgods

Copy link
Copy Markdown
Contributor

The heap sync was the largest single CPU cost of a world frame: 217 ms of a 557 ms frame on an M5 Pro, release build. This makes it about half as costly without changing what it does to any slot.

What it was spending the time on

Before every submission (about 21 a frame) the heap sync makes again the slots whose records the title copied into its shader-visible heaps as bytes. New diagnostics counters (below) split it per frame in the prologue world:

Slots per frame (about 375,000 on about 180 pages) Count Time
Already made from their record, passed by ~220,000 ~0
Holding no view ~125,000 ~0
Checked under the locks ~27,000 6–24 ms
Made again ~39,000 240–323 ms
Pages read; waiting for the heaps' lock; releases that forgot views 1 ms; 0; 0

Of the ~39,000 made again, about 22,000 are left null and the rest are views of only about 1,700 distinct records. Making the views themselves (prepare plus the host view) took under 20 ms. About half the time was spent waiting for the heap's slot lock (made). The heap sync took it once a slot, ~39,000 times a frame, while the title's threads recording draws take it to make their table slots.

What changed

  • HostHeap::mirror_synced does for each slot exactly what mirror does on the heap-sync path (for_draw == false), but takes the slot lock once for a page's slots instead of once a slot:
    • What each view needs is prepared first, without the lock, as mirror does.
    • A slot the title wrote again meanwhile is left to mirror.
    • Whether a view is still current is asked under the lock, as mirror asks with view_at.
    • Views are unpinned after the lock, whose holders their release may need.
  • mirror's null path and its making of a slot move into unmake_locked and make_locked, which both paths use, so the per-slot logic exists once.
  • Diagnostics builds log a heap sync per frame: line with the split above (SyncPages, SyncFast, SyncNoView, SyncChecked, SyncUnverified, SyncMade, their nanosecond times, ViewsForgot). watch::TimedNs times in nanoseconds, because these spans are well under a microsecond each and add up.

Measured in the game

M5 Pro, 64 GB, macOS 27.2.1, CrossOver 26.3 Wine, D3DMetal 4.0 beta 3, Series X. Every run used the same save (the prologue) and key script, with VICTORY_PATCH_MASKED=all VICTORY_FAULT_TRACKING=1 VICTORY_NO_HANG_WATCHDOG=1 VICTORY_STEP_OVER=pool and no GPU timing. Numbers are medians of the 5 s renderer reports with 500+ draws, from one minute after the world appears.

One diagnostics binary, with a temporary switch to turn the batching on and off, run interleaved (off, on, on, off):

Off (runs 1 and 6) On (runs 2 and 5)
Heap sync 297 / 231 ms 92 / 145 ms
Slots made again 39,864 / 40,872 in 286 / 221 ms 40,035 / 40,160 in 65 / 102 ms
Preparing 428 / 368 ms 212 / 335 ms
Frame 750 / 668 ms 462 / 639 ms

Release builds of main and of this branch, interleaved (main, branch, branch, main), 6 min each:

Release build, 6 min Frame Preparing GPU
main bf99e72, run 1 582 ms 312 ms 239 ms
This branch, run 2 585 ms 292 ms 242 ms
This branch, run 3 445 ms 185 ms 227 ms
main bf99e72, run 4 749 ms (p90 2,061) 452 ms 264 ms

Frame times vary a lot from run to run on this Mac: run 2 matches run 1, and run 4 had a slow phase. The release build has no heap-sync counter, so these frame times mix in every other cost. In an earlier release pair timed around sync_heaps (one run each), the heap sync went from 217 ms (204–224) to 126 ms (87–142) a frame.

The picture is unchanged. No crashes, ended submissions, queue moves or Metal errors occurred in any run.

How tested

  • Before and after on main bf99e72: cargo test --workspace 555 passed, 0 failed both times. tools/macos/test-wine.sh --workspace --no-fail-fast 1,124 → 1,125 passed, 0 failed (the new test).
  • New test: a_slot_rewritten_while_a_heap_sync_prepares_is_left_as_written_last. The title clears a slot while the sync prepares its view, through the existing WHILE_PREPARING hook; the slot must stay as the title left it, then be made once copied again. heap_syncs_make_the_slots_whose_records_changed, a_table_slot_rewritten_before_submission_refreshes_its_new_view and the bindless tests pass unchanged.
  • cargo clippy -p victory-gpu --all-targets --target x86_64-pc-windows-gnullvm -- -D warnings, with and without --features diagnostics, and cargo xtask policy pass. Only changed lines are formatted.

Tried and left out

  • A lock-free copy of made, so the heap sync passes by slots already made from their record. These are texture views left null and placed textures, whose ready is 0. It cut the check step from 21–30 ms to 7.5–10 ms. The total was not better in either interleaved pair, though, and it adds a rule every writer of made would have to keep, so it is not in this PR.
  • Leaving slots that no submitted draw reads to the draws. This is what avatarmanz/VIctory-7900XTX does. Here 12 of about 21 submissions a frame have heap-indexing shaders, so an exact version would save little. The fork's version gives up exactness: a slot picked by index shows its old view for up to four frames.

Notes

  • The lock is held for one page's slots, up to about 2,000. Chunking it would bound how long a title thread recording a draw can wait. That is possible tuning, but untested, so it is not done here.
  • This is item 1 of the CPU list from today's measurements. Item 2 is memory tracking: about 150 ms a frame in watches, the guard lock and the fault handler.

🤖 Generated with Claude Code

…t lock

Before every submission the heap sync makes again the slots whose records
the title copied into its shader-visible heaps as bytes: some 40,000 a
frame in the prologue's world (about 22,000 left null, the rest views of
only ~1,700 distinct records). Each went through HostHeap::mirror, which
takes the heap's slot lock (`made`) once a slot, while the title's threads
recording draws make their table slots under the same lock. On an M5 Pro
that cost 217 ms of a 557 ms frame in a release build, about half of it
waiting for the lock.

HostHeap::mirror_synced does for each slot exactly what mirror does on the
heap-sync path, but with the lock taken once for a page's slots: what each
view needs is prepared first without the lock, as mirror does; a slot the
title wrote again meanwhile is left to mirror; whether a view is still
current is asked under the lock, as mirror asks; views are unpinned after
the lock. mirror's null path and its making of a slot move into
unmake_locked and make_locked, which both use.

Measured in the game (M5 Pro, D3DMetal 4.0 beta 3, same save and key
script), interleaved runs of one diagnostics binary with the batching on
and off: heap sync 297/231 -> 92/145 ms a frame, preparing 428/368 ->
212/335 ms, frame 750/668 -> 462/639 ms.

Test: a_slot_rewritten_while_a_heap_sync_prepares_is_left_as_written_last.

Diagnostics builds now also log where a heap sync's time goes, per
frame: the pages a heap sync read and of their slots those passed by as
made from their record, those holding no view, those checked under the
locks (and of them those in blocks not verified since views were last
forgotten) and those made again, with the time spent checking, making,
reading pages and waiting for the heaps' lock, and the title's releases
that forgot views. These counters showed that the slots made again, not
the checks or the forgotten views, held the time. watch::TimedNs times
spans in nanoseconds, since these add up from many of well under a
microsecond.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@hackgods
hackgods marked this pull request as draft November 26, 2026 19:04
@hackgods

Copy link
Copy Markdown
Contributor Author

Moving this back to draft. Taking the lock once per page halves the heap sync, but about 120 ms a frame is still left: the same ~39,000 slots are still made again every frame (about 22,000 left null, the rest copies of only ~1,700 distinct views), plus their per-slot bookkeeping. I'm working on that in this PR and will mark it ready with new in-game measurements once the remaining cost is gone or shown to be irreducible.

@hackgods
hackgods marked this pull request as ready for review November 26, 2026 20:55
@brainbudt

Copy link
Copy Markdown
Contributor

Note

🤖 GPT-6.2 Sol responding on behalf of brainbudt

Three findings from reviewing the single-lock batching in crates/victory-gpu/src/descriptor/host.rs:

  1. Batch can install a descriptor after the title releases its resource (descriptor/host.rs:1104, :1139): If two newly copied slots in the same batch reference the same resource and the title releases its last reference while the first slot is being prepared, the first slot's pin keeps the resource alive long enough for the second slot to acquire another pin and install a descriptor. Dropping both pins after installation invalidates their records, but heap sync only revisits dirty pages, so the second descriptor can keep the host resource alive until that page is written again.
  2. Pages with no stale slots now acquire both locks (descriptor/host.rs:904, :1115): sync_slots_bytes calls mirror_synced even when stale is empty, acquiring made and reading VIEWS. Previously, pages with only empty or already-verified slots took neither lock; an early return when stale.is_empty() avoids blocking behind concurrent descriptor writes.
  3. Process-wide one-shot test hook race (descriptor/host.rs:2532, :2786): The new rewrite test shares the process-wide one-shot hook. If another concurrent test consumes the hook just before this test starts its sync, the slot is already clear when scanned and both assertions pass without exercising a rewrite during preparation; conversely, another hook-setting test can overwrite it and cause a spurious failure.

hackgods and others added 2 commits November 27, 2026 01:19
HostHeap::mirror_synced took the slot lock (`made`) and read `VIEWS` for
a page's changed slots even when there were none, so a heap sync of a page
whose slots were all empty or already verified waited for title threads
writing views, which neither lock held up before the batching. It now
returns when there is nothing to make.

Test: a_heap_sync_of_empty_slots_does_not_wait_for_the_slot_lock (fails
without the fix: the sync waits for the slot lock).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The work tests run while a view is prepared (`while_preparing`) was one
hook for the whole process, and tests run at once: another test's prepare
could take it first (the test then passed without the interleaving it was
written for) or a second test could replace it (a spurious failure). The
hook is now the setting thread's own; every test that uses it prepares on
the thread that set it.

Test: a_view_prepared_on_another_thread_leaves_the_prepare_hook (fails
with the shared hook: the other thread's prepare runs it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Nick233x

Copy link
Copy Markdown
Contributor

Test runs on an M5 Pro for this head (b2e0349, on main bf99e72). MacBook Pro, Apple M5 Pro, 24 GB, macOS 26.6.2, Game Porting Toolkit 4.0 beta 3 (D3DMetal), Wine built by setup.sh. Everything ran under Wine with tools/macos/test-wine.sh and default test threads. Synthetic only, no game files.

Run Result
victory-gpu --lib + victory-hle --lib 363 + 162 passed, 0 failed
victory-gpu --lib, 30 runs 30 of 30 passed
same on main bf99e72 earlier tonight, same Mac 60 of 60 passed

So the batched sync showed no flakiness here, and neither did the test hook point 3 above is about. These runs don't settle that point either way: a race that only skips the rewrite would still pass. The in-game numbers are not checked here, since I have no game data.

AI-assisted, prepared with Claude Code.

@hackgods

Copy link
Copy Markdown
Contributor Author

Thanks. I checked each finding against the code and against main.

  1. Release during a batched make: the interleaving is real, but the state isn't new. On main, mirror already makes the slot whose prepare overlaps the last release: the pin is held across the make and the caller drops it afterwards, and a_resource_released_while_its_view_is_prepared_outlives_the_make asserts exactly that. The batch also makes the page's other slots that view the same resource. They hold the same host resource as that slot (kept, kept so that a shader reading a slot not yet rewritten doesn't fault), and they sit in the same 64 KiB page, so the next write of that page finds them stale and unmakes them together. No view is made after forget: it can't run while pins are held, and each view's currency is checked again under the slot lock. No change.
  2. Locks taken for a page with nothing to make: valid, and introduced by this PR. Fixed in d94a5ef with an early return. a_heap_sync_of_empty_slots_does_not_wait_for_the_slot_lock fails without the fix.
  3. Shared one-shot test hook: valid, though it was already on main (the hook and three of its users); this PR added a fourth user. In 01b05a5 the hook is per thread, and each user prepares on the thread that set it. a_view_prepared_on_another_thread_leaves_the_prepare_hook fails with the shared hook.

Tested: victory-gpu natively (101) and under Wine (367 passed), plus clippy -D warnings for gnullvm with and without diagnostics, and cargo xtask policy.

The PR stays a draft. The next step for the remaining ~100 ms of heap sync (copying a view made again in the same frame from the first one, instead of creating it again) needs an in-game A/B before I add it here.

Prepared with Claude Code.

@hackgods
hackgods marked this pull request as draft November 26, 2026 21:45
@patcliftongc

Copy link
Copy Markdown
Contributor

A small M2 Max crossover test of 01b05a5 against bf99e72, optimized Windows diagnostic build, Rosetta + D3DMetal 4 beta 3. I used a 2,048-slot synthetic heap scanned in 128-slot pages. Each pass moved one eighth of the slots from empty to a copied constant-buffer descriptor with no backing address and cleared the previous eighth. I checked the made/cleared slots. Four fresh processes per revision, four warm-up passes, 100 timed passes per condition.

Median of process medians per sweep Base PR
One syncing thread 65.2 µs 106.4 µs
One syncing thread plus one thread continually reading the same heap’s made-slot lock 225.7 µs 143.9 µs

This supports the contention benefit, with higher single-thread overhead for this small, cheap-view workload. Reader throughput varied with lock scheduling. All four targeted correctness tests passed, including the new rewrite and empty-slot tests. No game frame times are inferred.

@mikebuckets171

Copy link
Copy Markdown
Contributor

One supervised M5 Pro/48 GB gameplay comparison of 01b05a5, with mixed results: heap sync fell, but total frame time did not improve in this pair.

macOS 27.2.1, Series X, private Wine 11.0 with #211, mapped D3DMetal 4.0b3. Optimized diagnostics builds, retained profile/cache, fault tracking enabled, 1280×720 output. Both used only Enter at 40 seconds before the measurement, then no manual input until after it. Watchdogs stayed enabled.

Control was bf99e72 plus #401/#435/#433/#436/#437/#438 (local 8a53785); candidate was that same integration plus this PR's 01b05a5 (local 19b6d70). Build dependency paths, executable hashes and effective launch values were checked. The source change was this PR, not a move of main.

Each measurement covered 120 seconds in the initial room facing the window, after a 20-second settle; the first 5 seconds of reports were excluded. The pose matched in private before/after captures. These are medians of periodic reporting averages:

Metric Control + this PR
Paired reports 21 21
Frame 548.7 ms 655.7 ms
Preparing 321.6 ms 357.8 ms
Heap sync 216.4 ms 165.4 ms
GPU 207.6 ms 224.4 ms
Copy-back 20.1 ms 31.1 ms
Guard-lock wait 71.7 ms 113.4 ms
Draws 4,926 5,015

The tutorial overlay appeared during the candidate interval, so this is a matched stationary pose, not a pixel-identical workload. One sequential pair also cannot separate ordinary run-to-run variation from a frame-time regression. It supports a lower measured heap-sync cost here (~24%), not an FPS improvement. No native sampling ran during either measurement.

The candidate visibly reached the world and responded to camera and movement input afterward. It recorded no unhandled title exception or Metal completion error. This run was stopped intentionally.

Full candidate gates: native 597 passed, 0 failed, 17 ignored; serial Wine 1163 passed, 0 failed, 29 ignored, no SKIPPED lines. Native Clippy, strict Windows Clippy default/all-features and policy passed. The fmt check reports exactly the same 81 file paths as the base.

Prepared by GPT-6 Astra from supervised local runs and retained logs. No game artifacts attached.

@hackgods

Copy link
Copy Markdown
Contributor Author

Thanks @mikebuckets171 and @patcliftongc, both are useful.

  • Heap sync: your −24% matches what we see. Neither of us has shown a frame-time gain yet, though, so I'm treating that as not established. On this M5 Pro, single runs of one build vary by ±30% (load time and streaming differ run to run), so one sequential pair can't separate the two. I'm running interleaved release-build series, with at least three runs per arm and longer runs so loading settles, and will post the frame medians here. The PR stays a draft until then.
  • Guard-lock wait 72 → 113 ms: worth checking. This PR only changes the descriptor slot lock, but if the batched sync keeps a page's slots held while title threads are inside the write-guard handler, time could move from one lock to the other. Our diagnostics build logs both, so the next series will show whether this is real or noise.
  • Single-thread cost (M2 Max, 65 → 106 µs per sweep, uncontended): the batch collects each page's entries into fresh Vecs and asks VIEWS for the whole page. That is extra allocation and work when nothing contends. Reusing per-thread scratch buffers should remove most of it, and I'll add that here with a bench.

Prepared with Claude Code.

hackgods and others added 2 commits November 27, 2026 02:55
…nded

heap_sync_bench (ignored; run alone, in release, under Wine) syncs a heap
of 2,048 slots in pages of 128, an eighth of its slots given another view
between sweeps, and gives the median sweep: by one thread alone, and with
another thread taking the slot lock all the while, as title threads
binding views do. It is a tester's pattern on pragyaangaur#409, where the batched
sync took 106 us a sweep against main's 65 us alone (M2 Max).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The batched heap sync was slower than main's lock a slot on one thread
alone: on heap_sync_bench (2,048 slots, pages of 128, an eighth changed a
sweep) 103 us a sweep against main's 72 us (a tester had 106 against 65 on
an M2 Max). Each page made fresh vectors for its slots, records, answers
and pinned views, and asked VIEWS a second time, under the slot lock,
whether the views it had pinned were current.

The vectors are now the syncing thread's own, cleared and kept for its
next page (a nested sync would take empty ones). The second question is
gone: a pinned view is current, as `mirror` finds it after it prepares one
without the lock, since only a resource's release makes views stale
(`descriptor::forget`, from `Resource::drop`), the pin holds the resource,
and views of no resource never go stale.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@hackgods

Copy link
Copy Markdown
Contributor Author

I pushed 0229bbc and 4f2fbff for the single-thread cost @patcliftongc measured.

  • 4f2fbff: each thread keeps its own page vectors and reuses them, instead of allocating fresh ones per page. The batch also no longer asks VIEWS a second time under the slot lock. This corrects what I wrote above: a pinned view can't go stale. Only a resource's release makes views stale, the pin holds the resource, and forget can't run while pins are held. Main's mirror already relies on the same thing after its unlocked prepare.
  • 0229bbc reproduces your pattern as a bench: 2,048 slots, pages of 128, 1/8 changed per sweep. It runs alone, and again with a thread holding the slot lock in a loop, and it asserts that every slot ends up made from its last record.

µs per sweep, medians of 15 processes per binary, run round-robin with the same bench file in all three:

alone contended
main (bf99e72 + bench) 72.3 227.0
PR before (01b05a5) 93.4 117.5
PR now (4f2fbff) 60.6 76.2

Paired per round, PR-now/main is 0.84 alone and 0.30 contended. This Mac swings between two timing regimes, so the paired ratios are the numbers to trust. Checks: victory-gpu under Wine 365 passed (383 with diagnostics), native 101 passed, clippy -D warnings clean with and without diagnostics, policy ok.

On the guard-lock question: the write-fault handler takes only the guard lock and never the slot lock, so the batch can't lengthen a title thread's wait in that handler. Frame time in-game is still to come from the interleaved series, so the PR stays a draft.

Prepared with Claude Code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants