Skip to content

GPU: run submissions asynchronously on a host fence timeline (rebase of #595) - #1923

Open
slatefield wants to merge 1 commit into
Marvisak:mainfrom
slatefield:up-595-rebase
Open

slatefield wants to merge 1 commit into
Marvisak:mainfrom
slatefield:up-595-rebase

Conversation

@slatefield

Copy link
Copy Markdown

Rebase of #595 onto current main (4118f33). The original work is wbkepler's; the commit is kept with its author and message, only conflict resolution sits inside it. If #595 is updated first, take that one.

Why it is the biggest frame-time change available: Host::execute waits for every submission before copying back, so a world frame's ~150 submissions are fully serialized and the CPU and GPU never overlap. The author measured, on an RTX 5090 in the world: median 283 -> 267 ms/frame, mean 319 -> 286, GPU wait per frame 79 -> 1 ms, with no device removal over 7-minute runs; a 5070 tester saw 1.8-2.0 -> 2.0-2.5 fps. It also makes a list reset while it runs safe, which is what the title does every frame.

The rebase, 5 conflict regions over 3 files:

  • descriptor.rs: main inlined shader_slot() away; the PR's heap-id scheme (NEXT_HEAP_ID, id-based release_dynamic) is applied to main's inlined code.
  • host.rs x3: main's id/ScratchChunk growth kept, the PR's budget/last/fresh_after fields and spare-chunk pool added. One design choice: scratch allocation uses the PR's list_buffer (L0 custom heap) rather than main's upload_buffer, because repeated-list preludes CopyBufferRegion into scratch and a D3D12 upload-heap resource cannot be a copy destination.
  • shadow.rs: main's newer update_busy and the PR's stale/submission_done kept side by side.
  • Outside textual conflicts: main-added tests that read GPU output straight after execute now call host.drain(), as tester notes on the PR said.

Checked here: Windows-target clippy for victory-gpu and victory (and whole workspace) with and without --all-features, clean; native tests green for the crates that build on Linux (shader 144, formats 38, game 15, core 13, pipeline 7); timeline.rs is pure std, compiled and its tests run natively (ordering, signals, conflicts) and pass; cargo xtask policy 183 files ok.

Not checked, needs a Windows GPU: the 9 new tests and the live numbers. Also worth knowing before merging, from the PR's own review thread: refresh_conflict ignores in-flight GPU reads (a reviewer reproduced it; the author deferred it), the AMD inbox repeated-recording test fails there while WARP passes, and present still drains the frame. ID3D12CommandQueue::Wait is a no-op on main (queue.rs:167) and the synchronous wait is what hides it today; #32 is the PR that fixes Wait, and it is worth landing near this one.

If merged as-is, the next bottleneck is CPU preparation (the author measured 148 -> 241 ms, title-memory copies); their note is that shadow buffers in VRAM with GPU dirty tracking is the next target.

Submissions are no longer waited for: each signals the next host fence
value and joins a timeline of up to 16 in flight, finished in order (copy
back, then bottom-of-pipe writes, then title fence signals) by a finisher
thread or whichever thread first needs one. Allocators, preludes, scratch,
kept objects, twins, dynamic descriptor leases and retired heap resources
are released behind their submission's fence. A step touching title memory,
host copies or texture staging waits only for in-flight submissions that
write (or read) it.

Rebased onto the page table, bindless heap views, twins and change journal:
a list's after-run work and missed-memory checks move into the pending
submission; bindless texture uploads, view heap refreshes and page table
refreshes wait for in-flight writers like other steps, a page table is
rewritten only with no reader in flight, and a page table user counts as
writing every copy it names.

A list named again in one submission gets its own prelude, and what its
steps write into the list's own memory (upload memory, scratch, budget
word) goes into an upload buffer of the submission that the repeat's
prelude copies in on the GPU, so each run reads its own data with no CPU
wait. List memory is a CPU-visible custom heap the GPU can copy into.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

@catminou4 catminou4 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.

Static review only: victory-gpu is Windows-only (D3D12/windows_sys) — nothing compiles or runs on macOS; source review of the diff.

Submissions run asynchronously on a…: async submission path — big behavioral change; needs Windows stress testing.

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

This pull request does not merge cleanly into main. Conflicting files: crates/victory-gpu/src/host.rs, crates/victory-gpu/src/shadow.rs.

It will be reviewed once it is rebased onto the current main.


Generated by Claude Code

@nathanbzrr

Copy link
Copy Markdown
Contributor

I put together a tested rebase of #1923 (4f1228c1) onto main (940d32f) with the async soundness fixes needed for marked-page copy-backs and an AMD RDNA3 repeat-submission fix:

Conflicts resolved

  • Resolved 4 conflict hunks across crates/victory-gpu/src/host.rs and crates/victory-gpu/src/shadow.rs (the other 14 files from 4f1228c1 merged cleanly, plus crates/victory-gpu/src/descriptor/host.rs for the set_mark / retire_shadow fixes below).
  • No victory-shader changes were needed: VIEW_WRITES (u1, space2) is already bound per command list via root UAV in draw.rs.

Soundness fixes for async submissions + marked-page copy-backs

  1. Per-HostList pooled MarkBitmap (SPARE_MARK_BITMAPS, cap 64): replaces the single global shadow::BITMAP (HostList::view_writes, Pending::marks, copy_back_marks), preventing CPU/GPU clearing races, lost marks from shader read-before-InterlockedOr, premature copy-backs, and &mut [u32] aliasing.
  2. Fence-deferred Marks bit recycling: Shadow::drop queues freed (base, count) runs into RETIRED_MARKS instead of calling host.after (avoiding Timeline::entries self-deadlock), and HostHeap::keep retires replaced shadows via retire_shadow; Host::complete releases them after the fence passes.
  3. 64 KiB page-rounded marked writes & refcounted Shadow::pending: Pending::of and run_deferred round marked Step::GpuWrite ranges to 64 KiB pages, Batch::armed defers shadow.writing(..., true) until pending refreshes flush, Shadow::pending is refcounted (HashMap<(usize, usize), u32>), Tracked::disarm_page clears pages no longer covered by any remaining pending range, and Shadow::update runs update_busy across the whole tracked range rather than splitting pages.
  4. In-flight writer/reader guards: Batch::flush queries Timeline::in_flight_writers so clean in-flight writer subranges are skipped (and stale ones settled) instead of racing Shadow::update_busy; Timeline::has_subsequent_reader guards host-copy updates (*h = *t) in Shadow::copy_back_or_not and Shadow::copy_back_marked.
  5. Missing Timeline hazard tracking: Step::Heap(viewed, writes) threads UAV write ranges via bindless::refresh_kinds, Step::Memory(heap, writes) tracks stage.memory_dirty writes, and Step::Indirect(address, len) adds touches.labels before indirect::bound.
  6. Heap drop, set_mark, and queue guards: descriptor::Heap::drop calls host.drain() before removing from SHADER_HEAPS; HostHeap::set_mark uses a single aligned 64-bit AtomicU64::store(..., Release); added guards around ExecuteCommandLists (!group.is_empty()), wait_gpu (!e.0.is_invalid()), and Host::drain (release_retired()).
  7. AMD RDNA3 repeat-list ExecuteCommandLists cut (Host::execute_inner): in a_repeated_list_reads_its_own_upload_memory, submitting groups[1] = [prelude, list] immediately behind groups[0] = [list, between] on RX 7600 caused between to be skipped (out2[0] = 0, D3D12 Debug Layer clean, WARP unaffected) because resubmitting an in-flight command list that is not at the tail of its ExecuteCommandLists group disturbs the driver's IB2 chaining tail. Cutting the group immediately after any list that repeats later in runs (and before any repeated list) fixes it with zero CPU waits and keeps D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE on Host::list_buffer.

New synthetic concurrent marked-page tests (host::submissions)

  • overlapping_marked_submissions_on_disjoint_pages_preserve_marks_and_title_writes
  • same_page_marked_submissions_serialize_and_preserve_all_writers
  • list_reset_while_running_isolates_mark_bitmaps
  • overlapping_reader_and_title_write_preserve_marked_gpu_and_cpu_bytes
  • dropped_shadow_mark_bits_wait_for_in_flight_submission

Verification (Windows 11 x64, AMD Radeon RX 7600, dxil.dll 10.0.26100.0)

  • cargo xtask policy: asset policy: 182 files ok
  • cargo clippy --workspace --all-targets -- -D warnings: passed
  • cargo clippy -p victory-gpu --all-targets --features diagnostics -- -D warnings: passed
  • cargo test -p victory-gpu --lib -- --test-threads=1 (RX 7600): 157 passed; 0 failed; 2 ignored
  • cargo test -p victory-gpu --all-features --lib -- --test-threads=1 (RX 7600): 160 passed; 0 failed; 2 ignored
  • VICTORY_D3D12_DEBUG=1 cargo test -p victory-gpu --features diagnostics --lib -- --test-threads=1 (RX 7600 + Debug Layer): 160 passed; 0 failed; 2 ignored
  • VICTORY_D3D12_WARP=1 VICTORY_D3D12_DEBUG=1 cargo test -p victory-gpu --features diagnostics --lib -- --test-threads=1 (WARP + Debug Layer): 160 passed; 0 failed; 2 ignored

AI-assisted; synthetic tests only, no game files, dumps, or captures used.

clquwu added a commit to clquwu/leonida-ultimate that referenced this pull request Nov 25, 2026
… overlap

- runtime/src/xs_memory_waits.h:
  * Resolve paired 24 GiB GPU-only <-> CPU-view aliases via rt::xmem::alias_address_fn
    (or optional MemoryWaitAlias) in MemoryWaitLog::record_slot, probe_memory_wait,
    MemoryWaitHolds::unmet, MemoryWaitHolds::poll, and MemoryWaitHolds::given_up so
    waits whose primary VA reads 0x0 or faults immediately observe values written to the
    paired alias instead of stalling for the 500 ms deadline.
  * Mask 32-bit waits to 32 bits in MemoryWait::holds(), add mid-list work rejection
    (MemoryWaitLog::note_work / MemoryWaitRecord::mid_list, adapted from
    ThatRecompDev/five-star-recomp@efcc782, GPL-3.0), probe memory outside mutex_,
    cascade newly given-up primary+alias addresses across all waiting queues in a single
    poll(), add LEONIDA_MEMORY_WAIT_TIMEOUT_MS optional bound, and add lock-free-fast-path
    notify_write() / set_wake_callback() / wait_for_change() for sub-ms write wakeups.
- runtime/src/vulkan_present.h:
  * Implement clean N-1 frame overlap (concept adapted from Marvisak/VIctory#1923,
    GPL-3.0): submit frame N immediately and wait on frame N-1's fence afterward so the
    GPU stays fed with 1 frame in flight ahead of the CPU.
  * Add LEONIDA_PRESENT_SYNC=1 opt-out (and set_sync_present/sync_present accessors) to
    wait on frame N when needed for debugging or captures.
  * Make LEONIDA_CAPTURE race-free and low-overhead under N-1 overlap: record exact
    pending_capture_{number,extent,format}, copy to the staging buffer only on selected
    disk-capture frames (unless enable_capture() readback is active), and harvest
    completed captures non-blockingly via vkGetFenceStatus when the next frame does not
    overwrite the staging buffer.
  * Release stale plane VkImageViews right after each frame slot's fence completes.
- runtime/test/xs_memory_waits_test.cpp & runtime/test/xbox_present_test.cpp:
  * Add 20 CPU checks for alias wakeup, faulting-VA fallback, mid-list rejection,
    32-bit masking, cross-queue timeout cascade, and immediate notify_write wakeups.
  * Add GPU/Vulkan validation tests for N-1 overlap bursts, LEONIDA_PRESENT_SYNC=1,
    and race-free LEONIDA_CAPTURE disk output without enable_capture().
@r4tedx

r4tedx commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

I built on @nathanbzrr's rebase of this PR (261d75a5, on main 940d32f), which carries @slatefield's rebase of @wbkepler's #595, and reviewed it for ordering: copy-back has to come before the title can see GPU writes. Branch: r4tedx/VIctory@async/1923-on-main (974639af). nathanbzrr's commit is kept unchanged as its own commit; two commits sit on top.

What holds.

  • Completion order is right: copy-back, then bottom-of-pipe writes, then fence signals.
  • Queue Signal/Signal2X and null-event fence waits are ordered behind in-flight work. Labels and query results come after copy-back.
  • Submission-time copies and refreshes wait for conflicting in-flight work, and two writers of the same range are never in flight together.
  • Retirement on reset or drop happens behind the fence, wait_gpu handles WAIT_FAILED, and present, resize and page mappings drain.

What I fixed (974639af). With completion on its own thread, copy-back races the title's submitting thread, which on main is blocked in ExecuteX during copy-back. There were two windows:

  1. Each 64 KiB piece was written back whole (shadow.rs copy_back, copy_back_marked, copy_back_page). A title write to a byte the GPU didn't touch, made after the copy-back read the piece, was overwritten. Now only the byte runs the GPU changed are written.
  2. The page was then marked clean (taken) with the copy holding title memory as read. A title write in between never reached the copy, so later GPU reads saw old bytes. Now the page is compared again after taken, and a page that differs counts as changed.

Two synthetic tests (declared ranges and marked pages) place a title write between the read and the write-back. Both fail with the whole-piece write put back, and both fail with the recheck removed.

Opt-in. 8df20658 makes async opt-in, VICTORY_ASYNC_SUBMIT=1. By default each submission is finished on the submitting thread before execute returns, as on main, and no completion thread starts. Both fixes above apply only in async mode. Happy to drop the switch if you'd rather this be always on.

Overlaps.

Still open.

  • refresh_conflict still ignores in-flight GPU reads. As far as I can trace, it changes bytes only when the title writes data an in-flight submission reads (a race on the console too), or in pages whose writes were withheld after a missed read. Async widens that window a lot. Narrowing it by waiting for overlapping readers would serialize most world submissions.
  • Present still drains every frame.

Checks. cargo clippy -p victory-gpu --all-targets -- -D warnings, with and without --features diagnostics, is clean. VICTORY_D3D12_WARP=1 cargo test -p victory-gpu --features diagnostics --lib -- --test-threads=1 gives 163 passed, 0 failed, 2 ignored (main: 146 / 0 / 2). Not checked: hardware adapters, the debug layer and frame times. An in-game run with the switch on and off is planned and will follow here.

The title was not used in these tests.

AI-assisted

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants