Skip to content

d3d12/vulkan + rdna2spirv: staged VRAM arena, DMA readback batching, parallel shadows, stream-pool fix & wave64 perf (RT-ARENA-DEVICE-LOCAL-STAGED) - #2865

Merged
aslan2142 merged 5 commits into
ProjectLeonida:mainfrom
azsekazvamdimitar:feat/rtx3090-vram-perf-and-translator
Dec 1, 2026

Conversation

@azsekazvamdimitar

@azsekazvamdimitar azsekazvamdimitar commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Claimed in the coordination issue as: RT-ARENA-DEVICE-LOCAL-STAGED (#2570)

Depends on: #2501 (included in this branch — see note below)

What and why

Brings RTX 3090 retail performance from 0.40 fps → 4.80–5.00 fps (non-ReBAR BAR1 = 256 MiB, ~12.5× composite speedup) and from 3.78 fps → 4.60 fps (+22% on 32 GiB ReBAR with LEONIDA_DEVICE_LOCAL_ARENA=1), fixes intermittently missing world/character meshes caused by unbacked stream-pool root views, and adds a HOST_CACHED DMA readback path for uncached ReBAR BAR1 memory.

Note on #2501 (SHADER-WAVE-LOOP-EXEC-VOTE): This branch includes the changes from PR #2501 (lane_masks.insert_data_merges / s_mask_to_data_b32 (TO_DATA) + tests/semantic/test_ballot_bit_loop.py, originally authored by @Tyrannys), since #2501 is currently stale/conflicting against main and is required to prevent lib_cs_03010 from regressing from < 2.5 ms/frame to 91–370 ms/call under wave64 emulation.

Runtime (d3d12_vulkan, vulkan_backend, arena_staging, d3d12_title_buffer_windows)

  1. Staged DEVICE_LOCAL VRAM arena & budgeted overflow slabs (runtime/src/arena_staging.h, runtime/shims/d3d12_title_buffer_windows.h, runtime/test/arena_staging_test.cpp): Keeps the 4 GiB GPU address arena and overflow TitleBufferWindows slabs in DEVICE_LOCAL VRAM paired with a HOST_CACHED staging mirror (LEONIDA_DEVICE_LOCAL_ARENA=auto|1|0), avoiding host-visible sysmem fallback on non-ReBAR GPUs and also beating direct WC BAR1 on 32 GiB ReBAR (+22% FPS). Both VRAM (Consumer::windows) and host staging (Consumer::staging) bytes are tracked in memory_breakdown::Owner and counted against reserved_ and a bounded cap (LEONIDA_EXTERNAL_WINDOWS_MB, default 4 GiB total staged / 2 GiB unstaged); empty staged slabs beyond 1 spare are reclaimed.
  2. ReBAR uncached BAR1 DMA readback (RebarReadbackScratch + ShadowPages::ReadbackLookup): When running unstaged on ReBAR (DEVICE_LOCAL | HOST_VISIBLE without HOST_CACHED), ShadowPages::write_back previously read directly from WC BAR1 via std::memcmp/memcpy (wb = 62.9–165.0 ms). Now batches retired ranges via copy_buffers_sync into a HOST_VISIBLE | HOST_COHERENT | HOST_CACHED scratch buffer (Consumer::staging), dropping ReBAR menu/load wb from 62.9–165.0 ms → 0.01–1.17 ms (loading FPS 6.04 → 18.3–29.3 fps).
  3. Batched DMA readback queue (VulkanContext::copy_buffers_sync, TitleBufferWindows::collect_host_readbacks): Batches retired host readbacks into one command buffer submission per family via readback_channels_, cutting staged wb from 27.62 ms → 1.56–2.35 ms/frame (-91.5%). (Lock order: callers hold shadow_mutex, copy_buffers_sync acquires submit_mutex_; no path acquires shadow_mutex under submit_mutex_.)
  4. Parallel ShadowRefreshPool (d3d12_vulkan_device.cpp): Persistent 3-helper + caller-thread pool parallelizing ShadowPages::refresh across independent trackers, cutting shadows from 26.91 ms → 10.2–11.1 ms/frame (-62%) and total before-execute from 70–75 ms → 21.8–22.9 ms/frame (-68%).
  5. Startup allocator race fix (d3d12_vulkan_device.cpp): Caches max_compute_shared_memory_size, mutex-guards the shared VkPipelineLayout, and loads pipeline_cache() eagerly (0 startup crashes across 25+ boots).
  6. Stream-pool root-view unbacked fix (resolve_pool_memory, d3d12_vulkan_device.cpp): Clamps kRootViewBytes = 65536 root-view probes to the committed stream-pool block while preserving vsharp_address room < bytes checks, dropping stream pool: ... got no GPU copy from 131,072 → 16–33 (root view unbacked = 0) and restoring missing world/character meshes.
  7. Console-heap GPU pass without geometry.cap() (d3d12_vulkan_device.cpp): Drops the geometry.cap() gate on LEONIDA_CONSOLE_HEAP_GPU=1 / LEONIDA_CONSOLE_HEAP_ARENA=1 so the GPU console-heap pass and T# index word updates can run with LEONIDA_GEOMETRY_MB=0, and flips vsharp_address's fourth argument to !geometry.cap().

Shader translator & build wiring (tools/lane_masks.py, tools/rdna2spirv.py, make_game.py, docs/design.md)

  1. PR Translator: gather a lane mask's bits where a merge takes it as data (SHADER-WAVE-LOOP-EXEC-VOTE) #2501 TO_DATA merges (tools/lane_masks.py, tests/semantic/test_ballot_bit_loop.py): Inserts s_mask_to_data_b32 at CFG merges where a lane mask meets scalar data; documented in docs/design.md. Fixes lib_cs_03010 (91–370 ms/call → < 2.5 ms/frame).
  2. --compute-serial-waves (opt-in, default off): Serializes wave64-emulated compute loops while preserving VulkanMemoryModel coherency; fixes lib_cs_00977 + lib_cs_00986 (160 ms/frame → < 2.4 ms/frame).
  3. --spirv-opt (opt-in, default off): Runs spirv-opt -O below 512 KiB and safe SSA passes at >= 512 KiB, with automatic fallback and spirv-val verification.
  4. --mesh-native-wave32 (opt-in, default off) + v_readfirstlane guard (tests/semantic/ms_native_readfirstlane.asm, tests/semantic/test_mesh_native_wave32.py).
  5. make_game.py wiring: Added --compute-serial-waves, --mesh-native-wave32, and --spirv-opt to FALLBACK_FLAGS and CLI so make_game.py shaders forwards and records them in translator_flags.txt.

Tested

  • Translator semantic test suite (python3 -I scripts/run_semantic_tests.py tests/semantic on rebased main 4009a3426): 555 files, 6,727 tests, 0 failures
  • Standalone Python & hygiene checks: check_no_game_data.py (all 15 touched files clean), compileall, make_game.py --help, tests/test_text_write_line_endings.py (3/3), tests/test_lane_masks.py (ok), test_ballot_bit_loop.py (2/2), test_mesh_native_wave32.py (4/4)
  • Linux portable CTest (Clang 21 + Ninja inside leonida-dev): 160 / 160 passed, 0 failures (including arena_staging with test_staged_slab_budget_and_reclamation)
  • Windows cross-build & live GPU test run under Proton on RTX 3090 (clang-cl + xwin SDK):
    • gta6rt.exe, arena_staging_test.exe, and d3d12_existing_heap_test.exe built and linked with exit 0
    • arena_staging_test.exe: PASS
    • d3d12_existing_heap_test.exe: PASS (vulkan slot-133 shadow adopts geometry_writes read-only guard: ok, vulkan slot-133 heap-lock faults: 20272 submissions ... no deadlock)
  • Shader corpus translation: 47,840 / 47,840 translated and spirv-val-valid (0 regressions)
  • Per-component retail measurements (RTX 3090 24 GB, Linux + GE-Proton, driver 590.48.01, 1080p PROFILE=0):
    • Composite non-ReBAR (BAR1 = 256 MiB, staged arena + DMA readback + parallel shadows + --compute-serial-waves + --spirv-opt on 4,131 active shaders): 0.40 fps → 4.80–5.00 fps (50 frames / 10.1 s)
    • 32 GiB ReBAR comparison on the same RTX 3090 (after VBIOS ReBAR update, rebased main 4009a3426):
      • ReBAR direct without DMA readback: wb 62.91–165.04 ms, 6.04 fps loading
      • ReBAR direct with RebarReadbackScratch: wb 0.01–1.17 ms loading (18.3–29.3 fps), 3.75–3.80 fps steady-state world (before-execute 49.1–50.8 ms, wb 21.45–22.60 ms, lists 24.2–26.3 ms)
      • ReBAR + LEONIDA_DEVICE_LOCAL_ARENA=1: 4.54–4.60 fps steady-state world (+22% over ReBAR direct; before-execute 25.15–27.27 ms, wb 1.56–2.02 ms, lists 3.55–4.49 ms, 0 crashes / 0 DEVICE_LOST)

GPUs tested: NVIDIA GeForce RTX 3090 24 GB (both non-ReBAR BAR1 = 256 MiB and 32 GiB ReBAR), driver 590.48.01, Linux (GE-Proton)

AI-assisted: yes

Checklist

  • Based on current main and merges cleanly (a conflicting pull request is labeled needs rebase).
  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed.

@github-actions github-actions Bot added the needs rebase Conflicts with the base branch: rebase it on main label Dec 1, 2026

@KelboLive KelboLive left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The arena/readback/shadow work looks directionally sound, and the translator side reproduces exactly here: scripts/run_semantic_tests.py tests/semantic = 555 files, 6,727 tests, 0 failed; test_lane_masks, semantic/test_ballot_bit_loop, semantic/test_mesh_native_wave32, test_text_write_line_endings pass; arena_staging_test.cpp compiles and runs (MSVC 14.44, /std:c++20 /W4 /permissive-, Vulkan SDK 1.4.363); check_no_game_data clean on all 14 changed files.

Two blockers.

  1. The staged slabs are not a budgeted pool. TitleBufferWindows allocates a full 64 MiB slab for every staged allocation (d3d12_title_buffer_windows.h:27, :258), never destroys one when it goes empty (:449), counts only the VRAM half in reserved_ (:390), and its host mirror is allocated with no memory_breakdown::Owner (:298-305) — outside both the budget and the memory report. d3d12_vulkan_device.cpp:4567 passes cap = UINT64_MAX. A title that churns large windows can accumulate 64 MiB VRAM + 64 MiB sysmem per slab without a cap, and the main arena's staging mirror is a second full-size allocation that is not part of its budget either.
  2. The Windows test expectations were not updated. d3d12_existing_heap_test.cpp:3699, :3707 and :3722 still assert title_shadow_refresh_queries(...) == 1 for the reserved (uncommitted) tail. With unchanged() now skipping kZero pages (d3d12_vulkan_device.cpp:1161-1163), that tail is skipped and the count is 0. Only the other test's expectation (:839) was changed — so the Windows GPU test was built, not run.

Unmentioned semantic reversal. This diff also drops the geometry.cap() gate on the GPU console-heap pass (:10890), rewrites T# index words on the GPU (:11586, :11635-11637), and flips vsharp_address's fourth argument to !geometry.cap() (:11794). That reverses the documented invariant "the pass does not write the T# index word the shaders read; heaps are fixed on the CPU" and has no dedicated test. It belongs in the description at minimum.

Claims. wb 27.62 → 1.75-2.35 ms, shadows 26.91 → 10.2-11.1, before-execute 70-75 → 21.8-22.9 are credible and name a machine (RTX 3090, non-ReBAR, GE-Proton, 590.48.01). The 0.40 → 4.80-5.00 fps (~12.5x) is a composite of arena + readback batching + parallel shadows + --compute-serial-waves + --spirv-opt, with no per-change attribution. And those flags cannot be requested through make_game.py: FALLBACK_FLAGS (make_game.py:2016-2021) is a closed allowlist with no argparse options for --compute-serial-waves, --spirv-opt or --mesh-native-wave32, and they are not recorded in translator_flags.txt, so a make_game.py shaders re-run would silently drop them. --spirv-opt's help still says 750 KiB while SPIRV_OPT_LARGE_BYTES = 512 * 1024 (tools/rdna2spirv.py:23960 vs :23726), and the new docs/design.md row says 551 files / 6,680 tests (stale).

Readback ordering is sound (sorted/coalesced, only retired tickets), but two things to note: the DMA copy is ordered against the producer only by the host-side completion check, not a semaphore (:5217, :6460-6470), and Map() can block the graphics queue up to 5 s (vulkan_backend.h:38) while sync_retired_readbacks_to_host runs under shadow_mutex (:5250-5268) — a shadow_mutex -> submit_mutex_ order not in the documented hierarchy.

Please split it. Land the console-heap T#/geometry.cap() rework as its own PR first — it reverses a documented invariant, has no test, and is unmentioned. Keep arena staging + readback batching + shadow parallelism as a second PR, with arena_staging_test (it passes here) plus a unit test for the slab accounting and the corrected Windows expectations.

@azsekazvamdimitar

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review @KelboLive! Addressed all the technical points in 57579a34d and updated the PR description (keeping this as one PR for now):

  1. Staged slab budgeting & accounting (Blocker 1): TitleBufferWindows now tags VRAM allocations with memory_breakdown::Consumer::windows and host staging mirrors with Consumer::staging, counts both VRAM + host staging bytes in reserved_ against a bounded cap (LEONIDA_EXTERNAL_WINDOWS_MB, default 4 GiB total staged / 2 GiB unstaged instead of UINT64_MAX), and reclaims empty staged slabs beyond 1 spare. Added test_staged_slab_budget_and_reclamation in arena_staging_test.cpp.
  2. Windows test expectations (Blocker 2): Updated d3d12_existing_heap_test.cpp:3699, 3707, 3722 to == 0 for the skipped kZero reserved tail, and ran both arena_staging_test.exe and d3d12_existing_heap_test.exe live under Proton on RTX 3090 — both pass (vulkan slot-133 shadow adopts geometry_writes read-only guard: ok, vulkan slot-133 heap-lock faults: 20272 submissions ... no deadlock).
  3. Console-heap GPU pass / geometry.cap(): Documented explicitly in the PR description (enables LEONIDA_CONSOLE_HEAP_GPU=1 / LEONIDA_CONSOLE_HEAP_ARENA=1 with LEONIDA_GEOMETRY_MB=0).
  4. Translator CLI & docs: Wired --compute-serial-waves, --mesh-native-wave32, and --spirv-opt into make_game.py's FALLBACK_FLAGS and CLI (recorded in translator_flags.txt), fixed --spirv-opt help text (512 KiB), updated docs/design.md test counts (555 files, 6,727 tests), and broke out per-component timing attribution in the PR description.
  5. Bonus (ReBAR DMA readback): After flashing ReBAR (32 GiB BAR1) on the same RTX 3090, we caught a 63–165 ms WC BAR1 readback stall in unstaged ShadowPages::write_back and added RebarReadbackScratch (Consumer::staging) + ShadowPages::ReadbackLookup so unstaged ReBAR readbacks use copy_buffers_sync too (and verified LEONIDA_DEVICE_LOCAL_ARENA=1 still beats ReBAR direct by +22% FPS in world: 3.78 -> 4.60 fps).

…ows, stream-pool fix

On top of PR ProjectLeonida#2566 (8db8335), combines verified runtime performance and
correctness improvements for non-ReBAR Vulkan GPUs (tested on Linux / Wine /
RTX 3090 24 GB, BAR1 = 246 MiB, driver 590.48.01):

- Stage 4 GiB GPU address arena + overflow TitleBufferWindows slabs in
  DEVICE_LOCAL VRAM with HOST_VISIBLE staging mirrors (arena_staging.h,
  arena_staging_test.cpp).
- Fix startup glibc realloc() race by caching max_compute_shared_memory_size,
  sharing mutex-guarded VkPipelineLayouts, and eagerly loading pipeline_cache()
  during single-threaded Device construction.
- Stage 9a-1: batch retired arena + external window host readbacks into a
  single copy_buffers_sync() submission on the dedicated DMA copy queue
  (wb: 27.6 ms -> 2.35 ms/frame).
- Stage 9a-2: parallelize ShadowPages::refresh across 4 persistent threads
  via ShadowRefreshPool (shadows: 26.9 ms -> 10.2 ms/frame).
- Fix resolve_pool_memory() zeroing out root descriptors probed with
  kRootViewBytes (64 KiB) near the end of committed stream-pool blocks
  (stream pool unbacked: 131,072 -> 16-33, root view unbacked: 0).

AI-assisted. Verified with 151/151 portable Linux CTest passing and Windows
MSVC build + retail boots on RTX 3090 (590.48.01).
…e32, --spirv-opt

On top of PR ProjectLeonida#2566 (8db8335), combines verified translator performance and
correctness improvements for NVIDIA Wave32 GPUs (tested on RTX 3090 24 GB,
driver 590.48.01):

- Cherry-pick PR ProjectLeonida#2501 lane_masks.insert_data_merges (TO_DATA) fixing
  lib_cs_03010 bit-scanning loops (91-370 ms/call -> < 2.5 ms/frame).
- Add --compute-serial-waves for >64-thread barrier/LDS/atomic-free compute
  shaders (lib_cs_00977 + lib_cs_00986: 160 ms/frame -> < 2.4 ms/frame) while
  preserving unmodified PR ProjectLeonida#2566 d88b2de VulkanMemoryModel coherency.
- Add --mesh-native-wave32 for strictly partition-invariant mesh shaders
  (9,116 / 9,282 dxbc MS shaders), running all threads natively in 1 Wave32
  pass with zero %x_buf LDS/barriers (-13% to -35% on hot mesh shaders).
- Add --spirv-opt (-O below 750 KiB, safe SSA pass set at >= 750 KiB to avoid
  NVIDIA 590.48.01 --scalar-replacement=0 compiler segfaults, with automatic
  fallback + spirv-val check).

AI-assisted. Verified with semantic tests and retail boots on RTX 3090 (590.48.01).
…-spirv-opt SSA threshold to 512 KiB

- Exclude v_readfirstlane from --mesh-native-wave32 until per-use uniformity
  analysis proves the source wave-uniform (with ms_native_readfirstlane.asm
  and test_mesh_native_wave32.py regression test + docs/design.md update).
- Lower SPIRV_OPT_LARGE_BYTES from 750 KiB to 512 KiB so library/lib_cs_03245
  and siblings use the safe SSA pass set instead of --scalar-replacement=0
  (avoiding NVIDIA 590.48.01 compiler SIGSEGV during warmup).

AI-assisted.
@azsekazvamdimitar
azsekazvamdimitar force-pushed the feat/rtx3090-vram-perf-and-translator branch from 57579a3 to 8ebe7cc Compare December 1, 2026 14:40
@github-actions github-actions Bot removed the needs rebase Conflicts with the base branch: rebase it on main label Dec 1, 2026
@merzleckeier

Copy link
Copy Markdown
Contributor

I rebuilt Win64 Release from the current head 8ebe7cc. With staging enabled, the unmodified arena_staging_test and d3d12_existing_heap_test passed under Wine 11.22 on Radeon Raphael (RADV 26.3.1) and RTX 4070 SUPER (620.73.04). The heap suite reached the Vulkan shadow and guarded-page stress cases. Its Microsoft host-D3D12 comparisons were skipped under Wine. The runtime subtree is identical after a clean merge onto 43c7b34.

A separate staging-map failure injection exposed a remaining fallback issue on both devices. I wrapped the Vulkan calls for a 64 MiB staged arena, forced only the first vkMapMemory of the staging mirror to return VK_ERROR_MEMORY_MAP_FAILED, and intercepted a second bind of the same arena buffer before forwarding to the driver. On stock 8ebe7cc the counters were 1 staging refusal, 1 successful arena bind, 1 duplicate bind attempt and no mapped host fallback. The successful permanent arena bind precedes the failed staging map.

In a local test patch, I completed staging setup before binding the arena buffer. Both devices then reported 1 refusal, 1 successful bind, zero duplicate attempts and a mapped host fallback. The same setup ordering can be used for external staged windows. My injected device-creation case covers the main arena. MEASURED with a synthetic frame-free device. AI-assisted (Codex).

@azsekazvamdimitar

Copy link
Copy Markdown
Contributor Author

Great catch @merzleckeier — thank you for testing on both RADV (Radeon Raphael) and RTX 4070 SUPER and catching that bind-order fallback bug!

Fixed in 4a305d066:

  1. Staging bind/map before VRAM bind: Both the main arena (d3d12_vulkan_device.cpp) and external staged slabs (d3d12_title_buffer_windows.h) now bind and map the staging buffer first and only call vkBindBufferMemory on the VRAM buffer after vkMapMemory succeeds (unmapping staging cleanly if the VRAM bind itself fails). Added a vkMapMemory failure-injection check to test_staged_slab_budget_and_reclamation in arena_staging_test.cpp asserting every buffer is bound at most once on host fallback.
  2. CI fix (test_docs_env_vars.py): Documented LEONIDA_EXTERNAL_WINDOWS_MB in docs/d3d12_vulkan.md (test_docs_env_vars.py 5/5 OK).

@merzleckeier

Copy link
Copy Markdown
Contributor

Retested the fix at 4a305d0 merged into 88a9f13 on Radeon Raphael (RADV 26.3.1) and RTX 4070 SUPER (620.73.04), Win64 Release under Wine 11.22. The stock arena_staging_test, including the new external-slab failure case, and d3d12_existing_heap_test passed on both GPUs. Under Wine the latter skips Microsoft host-D3D12 comparisons.

I also checked both main-arena fault paths on both GPUs. Repeating the original forced staging map refusal gave zero duplicate binds and a mapped host fallback. In a separate injection I let the staging mirror map successfully, then failed the first VRAM bind of the arena before forwarding it. The PR unmapped staging exactly once before mapping the host fallback, with one successful arena bind and zero duplicate attempts. The original symptom is fixed in this repro. MEASURED with synthetic fault injection on physical GPUs. AI-assisted (Codex).

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.

4 participants