Skip to content

perf(gpu): opt-in Wait-Before-Prep Flight-1 GPU overlap and async submit worker - #447

Open
gdemontalivet wants to merge 2 commits into
pragyaangaur:mainfrom
gdemontalivet:perf/macos-async-submit-flight1
Open

gdemontalivet wants to merge 2 commits into
pragyaangaur:mainfrom
gdemontalivet:perf/macos-async-submit-flight1

Conversation

@gdemontalivet

Copy link
Copy Markdown
Contributor

Summary

Adds opt-in Wait-Before-Prep single-flight GPU overlap (VICTORY_FLIGHT1=1) and a dedicated async queue submission worker (VICTORY_ASYNC_SUBMIT=1) so title command recording overlaps with host D3D12/D3DMetal GPU execution while preserving full shadow-buffer, descriptor-heap, staging-pool, and fence ordering invariants:

  • crates/victory-gpu/src/host/flight.rs & crates/victory-gpu/src/host.rs:
    • Splits submission preparation (prepare_submission) and post-GPU completion (finish_post_gpu) cleanly from synchronous execution.
    • Under VICTORY_FLIGHT1=1, drains Flight N-1 completely before Flight N touches shared Shadow, descriptor-heap, upload-staging, or Mark state (Wait-Before-Prep), then returns immediately after ExecuteCommandLists + Signal while a background victory-flight finisher lands GPU copy-backs, bottom-of-pipe writes, and attached fence signals.
    • Checks fence.GetCompletedValue() >= value before WaitForSingleObject in wait_for_on_event to avoid spurious poll delays, and records pure GPU execution time (gpu_done - launched) separately from lock wait and copy-back timing.
    • Exposes before_sync / drain_submit / Quiet barriers for synchronous host callers (present, readbacks, captures, page-mapping batches).
  • crates/victory-gpu/src/hold.rs & crates/victory-gpu/src/queue.rs:
    • Adds Held::take_ready_with supporting multi-queue coalesced segments, chained bottom-of-pipe waits, deferred mid-batch fence signals, and hazard-split restoration while HELD is unlocked around host GPU calls.
    • Under VICTORY_ASYNC_SUBMIT=1, title ExecuteCommandLists / Signal / Wait calls enqueue into HELD and wake victory-submit instead of blocking the title thread on host GPU execution.
    • Both flags default to off (0), keeping default synchronous behavior unchanged.

Verification

  • cargo xtask policy: passed (263 files ok)
  • cargo clippy --target x86_64-pc-windows-gnullvm --workspace --all-targets -- -D warnings (default and --features diagnostics): clean
  • Live Wine/D3DMetal unit tests (tools/macos/test-wine.sh -p victory-gpu):
    • host::flight::tests::: 4 passed; 0 failed (including 10-iteration back-to-back GPU write/refresh non-clobber and signal-ordering tests)
    • hold::tests::: 12 passed; 0 failed (including take_ready_coalesced_merges_cross_queue_bop_and_deferred_signals)
  • Matched quiet Apple Silicon M5 Max A/B benchmark (identical combined binary and frozen warm shader cache, VICTORY_COALESCE_PIECES=1):
    • Sync (VICTORY_FLIGHT1=0 VICTORY_ASYNC_SUBMIT=0): 75.85s (0.527 FPS) across +8..+48, 13–17 host submissions/frame
    • Async Flight-1 (VICTORY_FLIGHT1=1 VICTORY_ASYNC_SUBMIT=1): 28.13s (1.422 FPS, 2.70× faster) across +8..+48 and 60.29s (1.360 FPS) across +8..+90, 7–8 host submissions/frame, -26.5s faster to world entry, zero stalls or crashes.

…async submit worker (VICTORY_ASYNC_SUBMIT=1)

Implement Wait-Before-Prep Flight-1 overlap (Phase A, VICTORY_FLIGHT1=1)
and a dedicated victory-submit worker thread (Phase B, VICTORY_ASYNC_SUBMIT=1)
behind opt-in environment switches (default off):

- Move Flight-1 state, launch, background victory-flight finisher thread,
  signal attachment, and GPU regression tests into host/flight.rs.
- Enforce Wait-Before-Prep: finish_flight_locked always drains Flight N-1
  (GPU fence wait, Mark check, copy-back, defer_after, BoP writes, upload
  list return, HostList recycling, and atomic pending_signals delivery)
  before Flight N touches any shared Shadow, descriptor heap, texture
  staging pool, or Mark buffer.
- Keep Vec<Arc<HostList>> and owned bindless::Uploads inside InFlight so
  list::restart preserves strong_count > 1 on early title Reset and
  bindless::LIST / texture::recycle never reset in-flight resources.
- Drain any active flight inside Host::quiet() after locking submitted so
  the GPU is idle during shader-visible descriptor heap creation/null-fill.
- Add Held::take_ready / finish_running so victory-submit and Flight-1
  never hold HELD across GPU submission, strictly preserving the lock DAG
  (SUBMIT_DRAIN -> HELD -> Host::submitted -> Host::flight -> Fence::waiters)
  and draining cleanly at PresentX, CopyPageMappingsBatchX, and sync
  Host::execute calls.

@hackgods hackgods left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this. A single flight with wait-before-prep keeps shadow and snapshot state one submission at a time, which is the hard part. These notes come from reading c67735c and from a trial merge onto a branch that carries more of the open PRs:

  1. Test isolation. TEST_FLIGHT1 and TEST_ASYNC_SUBMIT are process-global (flight.rs:83–121), so other tests running in parallel see the modes flip mid-run. On a branch that also has the BVH/upload tests, list::tests::allocate_upload_survives_early_reset… fails because it expects pump_held to run synchronously. A test that pumps while holding HELD deadlocks through before_sync → drain_submit → held(). Thread-scoped overrides or a serial test binary would fix both.
  2. Bigger pieces under the worker. take_ready_with(..., false) (queue.rs:307) → take_ready_per_queue (hold.rs:421) joins every ready segment of a queue into one submission. Within one submission, every list's CPU-side steps (stand-in copies, moves, fills, refreshes) run before any of its GPU work. So a later list's CopyBufferRegion into a buffer that an earlier list reads on the GPU now lands before that read, where they used to be separate submissions. A gate like #419's can_join, or a cap, plus a test for that order, would settle it.
  3. A SetEventOnCompletion with a null event still returns E_NOTIMPL (fence.rs:104). With fences now lagging, it returns instead of blocking. None of our runs hit it, but it's now reachable.
  4. Preparing still never overlaps the GPU (flight.rs:187). The waits that remain (flight.rs:362 and the one in execute_sync) can be used to make the next submission's descriptor-heap sync. We have that as a small separate switch (VICTORY_SYNC_IN_WAIT). It is −19 to −21% in a synthetic test; our in-game numbers are still inside run-to-run noise. It merges with yours with one conflict in host.rs, so the two compose.
  5. Slot remakes on title threads while a flight is in the air (make_read, texture upgrades) caused device losses in a Windows fork (avatarmanz 3bab23c, held until earlier submissions finish). Exposure grows now that title threads no longer block.
  6. VICTORY_ASYNC_SUBMIT=1 also turns on Flight-1 (flight.rs:46). Worth a line in the docs.

Prepared with Claude Code; review of the code plus a local trial merge, no game data.

@mikebuckets171

Copy link
Copy Markdown
Contributor

Preparing an M5 Pro comparison: could you identify the exact combined commit used for the reported 2.70× run?

At c67735c, the production call in queue.rs:307 is held.take_ready_with(&read_value, &fence, &no_write, &no_join, false), and git grep VICTORY_COALESCE_PIECES finds no switch in this head. The coalescing implementation and test are present, but that runtime call selects the per-queue path. The benchmark section names VICTORY_COALESCE_PIECES=1, so I want to distinguish the standalone PR's behavior from the combined build's enabled features before attributing measurements.

I can test this head's actual async/Flight-1 path independently. A pinned combined revision, or a note that the coalescing flag was inert in the measured build, would make the published comparison reproducible.

Prepared by GPT-6 Astra from the pinned public source.

@mikebuckets171

Copy link
Copy Markdown
Contributor

M5 Pro (48 GB), macOS 27.2.1, Rosetta + Wine 11.0, mapped D3DMetal 4.0 beta 3: no frame-time improvement in this standalone async/Flight-1 toggle pair.

Tested c67735c on the #439 evaluation base at 2443b68, producing retained integration fb5087942796ea6ce903ede463d672c58d3ed7e2. Both runs used the same executable SHA-256 a41ef037139fcc1f0bb02c4425b228cb5a2fbf0bfd59495ec8ac7794d36e247a, retained profile, 720p output, diagnostics, fault tracking and fast heap synchronization. The complete launch records differ only in VICTORY_FLIGHT1 and VICTORY_ASYNC_SUBMIT, both 0 versus both 1. VICTORY_GPU_TIMING=0; both feature-activation log markers were present in the enabled run.

Each run used the same initial-room pose, 20 seconds settling followed by 120 seconds stationary with no manual input. Values below are medians of paired reporting-interval averages; frame time comes from presented-frame wall time, not a sum of the overlapping component counters.

Metric Both off Both on
Reports 21 19
Frame time 416.8 ms 421.3 ms
Preparation 178.3 ms 167.9 ms
Heap synchronization 69.8 ms 62.6 ms
GPU time 206.8 ms 209.6 ms
Copy-back 27.5 ms 20.9 ms
Guard wait 70.4 ms 66.4 ms
Draws/frame 4,912 4,911
Dropped without a pipeline 30 30

The 1.1% frame-time difference in one sequential pair is not evidence of a general regression or speedup. This does not reproduce the PR description's combined/coalesced workload: as noted above, the pinned standalone head's production call selects coalesce=false. I have not attributed the combined build's 2.70× figure to this standalone path.

Both reached the room with no logged unhandled title exception or Metal completion error. Camera/backward input response was observed after the enabled measurement, but this variant has no full control/stability/relaunch qualification. The control stopped intentionally. The enabled run ended at 601 seconds because I missed renewing the operator's visibility heartbeat during the post-measurement input checks, after the full measurement had completed; the watchdog recovered Wine, the lock and inference. That was an operator-supervision expiry, not a diagnosed title crash.

Integration gates: native 600 passed / 0 failed / 17 ignored; serial Wine 1,170 passed / 0 failed / 29 ignored, no SKIPPED lines, including all four host::flight::tests. Native and strict Windows default/all-features Clippy and policy passed. Formatting still fails on the base's 81 paths plus two wrapping differences in the new host/flight.rs.

Prepared and tested by GPT-6 Astra on Michael's Mac; game artifacts and raw logs stay local.

@4TheDoctor

Copy link
Copy Markdown

Tested c67735c on an M3 Max (40-core GPU, 48 GB), macOS 27.2.1, CrossOver 26.1, D3DMetal 4.0b3, Grand Theft Auto VI, Series X. Diagnostics build of this head as is (base bf99e72), one executable for both runs; only VICTORY_FLIGHT1 and VICTORY_ASYNC_SUBMIT differ (both 0 vs both 1, the enabled run logs both features). VICTORY_GPU_TIMING=0, fault tracking on, aliasing on (default), stock wineserver. 600 s each, medians from 430 s (world):

both off both on
frame 827 ms 791 ms
preparing 350 ms 346 ms
on the GPU 454 ms 401 ms
command buffers macOS ended (recovered) 0 5

One pair, -4%, close to my run-to-run noise, so I would not call it a gain yet; it agrees with the M5 Pro result above.

Two cautions from this machine (#442): without timing, 3 of my last 6 runs hung for good (Metal's submission thread stuck in IOGPU), including an earlier run of this same executable with both switches off (~420 s). With both on, the 5 ended command buffers are more than I have seen in any other run (0 to 3), but one run is not enough to blame the overlap.

AI-assisted testing.

@4TheDoctor

Copy link
Copy Markdown

Correction to my comment above: the old "ended a submission" warning is only logged at powers of two, so the counts were lower bounds. With both switches on it was 4 to 7 command buffers ended, and an earlier run on my lab build with timing on also had 4 to 7. So it is not more than in other runs, and nothing points at the overlap from that. The frame-time result (-4%, near noise) stands.

@pragyaangaur

Copy link
Copy Markdown
Owner

Thanks for this. Many pull requests landed today, and this one now conflicts with main. Could you merge or rebase main into it, rerun the checks and ping here? I will review and merge it as soon as CI is green.

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