Skip to content

[integration] PageMirror, GPU detile, async queue & RDNA2->SPIR-V performance stack (INTEGRATION-PERF-CPU-GPU-R6) - #2566

Open
aslan2142 wants to merge 200 commits into
ProjectLeonida:mainfrom
aslan2142:integration/perf-cpu-gpu-r6
Open

aslan2142 wants to merge 200 commits into
ProjectLeonida:mainfrom
aslan2142:integration/perf-cpu-gpu-r6

Conversation

@aslan2142

@aslan2142 aslan2142 commented Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator

Claimed in the coordination issue as: INTEGRATION-PERF-CPU-GPU-R6

What and why

Integration PR (aslan2142:integration/perf-cpu-gpu-r6, merged cleanly with upstream main d48a957bb) combining the PageMirror / in-place console descriptor heap / GPU detile runtime stack with ten rounds of CPU submission, bindless GC, memory-tracking, async synchronization, and RDNA2 → SPIR-V translator performance & correctness work.

1. RDNA2 → SPIR-V Translator Correctness & GPU Codegen (tools/rdna2spirv.py, tools/shader_meta.py, tools/lane_masks.py, docs/design.md)

  • Absent-lane subgroup UB elimination: Guards wave-uniform v_readfirstlane_b32, v_readlane_b32, v_permlane16_b32/v_permlanex16_b32, DPP (fi:1 & out-of-row), ds_append/ds_consume/ds_permute/ds_lane_read, and non-fragment s_wqm against unlaunched/absent subgroup lanes; adds static SPIR-V invariant checker (tests/semantic/check_absent_lane_ub.py), partial-wave CPU regression suite (tests/semantic/test_absent_lane_ub.py), and live GPU test (tests/test_absent_lane_gpu.py).
  • FTZ32 & fmulz enablement: Checks exact HW_REG_MODE bit overlap with [4, 6) (FP_DENORM.fp32) in _disables_ftz32(), re-enabling FTZ32 and fmulz across the corpus while keeping explicit software denormal flushing (force=True) on v_exp_f32 (GLSL.std.450 Exp2).
  • Compact outlined sbuf_slow + NonWritable SMEM: Replaces expanded per-load slow paths with compact OpLoopMerge ... DontUnroll %sbuf_slow_{ro,rw}_xN helpers with overflow-safe 64-bit bounds, and adds CFG store-reachability (WAR-safe) + descriptor-provenance NonWritable SMEM tagging.
  • Image, sampler, coherent VMM & write-back metadata:
    • SPV_KHR_vulkan_memory_model (MakePointerVisible/MakePointerAvailable) for glc/dlc loads & stores + reads_glc_buffer metadata.
    • Compile-time literal S# sampler OpSpecConstant specialization (literal_samplers / literal_sampler_spec_base) bypassing FNV-1a bindless probes.
    • Float-only image_read_typed dead-branch elision (f32/f16 consumers + bilinear/linear-mip literal samplers) and table-driven buffer_store_format.
    • writes_buffer and buffer_write_slots metadata for gating passive write-back.
    • Wide s_buffer_load, SPV_KHR_integer_dot_product (v_dot4), heap T# bindless index word in dword 6, and pure scalar-spill VGPR parking.
  • All new translator rules are documented in the contract table of docs/design.md.

2. Runtime PageMirror, Console Heaps in Place & GPU Detiling (runtime/src/title_mirror.h, title_mirror_hot_cold.h, shadow_keep.h, vulkan_title_detile.h, runtime/shims/d3d12_*, xmem.cpp)

  • PageMirror & in-place console descriptor heaps: Mirrors title memory pages into sparse device-local chunks (Chunk::pages[32768] direct table) with 256-byte piece-level CPU/GPU merge, hot/cold submission write tracking (kPromote = 6/8), 64 MiB copy-queue readback with sub-page 256 B copies, page_mirror_buffer resolve_cache, and hoisted FilterCacheScope + parallel Phase-A/disjoint-WC-flush console heap filtering (local_mirror chunk cache, AVX2 32-byte slots_equal_32, 8 KiB L1d seen_keys, per-batch T# dedup, lock-free in_place_work_pending fast-skip).
  • AVX2 / x86-64-v3 SIMD & 8-worker mirror pool: Enables /arch:AVX2 (x64 MSVC/clang-cl) and -march=x86-64-v3 (x86-64 GCC/Clang) for C/C++ targets; adds 4×256-bit AVX2 + 4×128-bit SSE2 shadow_keep::sum_of(), sum_of_batch_256(), and fused SEH-safe guarded::copy_and_sum_256(), plus an 8-worker TitleMirror::WorkerPool with 50 µs spin and WC streaming copies.
  • Low-syscall VM guard tracking & shared Cell::known_*: Unlocked parallel Phase-1 readback pre-hashing, shared Cell::known_* across CellGuard & TitleTextureCells (excluding PAGE_READONLY from VQ caches), TitleHeap::hooks.commit/decommit map-change scoping, batched copy_page_mappings(), safe per-tile bridged VirtualProtect rollback (preserving already-armed gap tiles), zero-syscall all_armed fast paths, and range-scoped reopen() / changes_since().
  • GPU detiling & batched texture refresh (title_texture_watch.h, title_texture_refresh.h, d3d12_title_image_upload.h):
    • GPU compute detiling directly from TitleMirror chunks + TitleMirror::range_sum() skip + 512-job / 128 MiB GPU-mirror upload batching (TitleImagePool 8 MiB/16 MiB cap, kMaxScratchSlots=64).
    • Deferred slot-70 uploads to GPU detile + publish_streamed_texture() fix, separated title_texel_writes, Stage-2 TextureVqCache + Stage-2b Cell::restore[] readability bypass, single-lock page_mirror_check_batch(), and TitleTextureWatch::examine_batch() + TitleTextureCells::arm_batch().
  • Bindless view sharing & two-phase dead-sweep GC (vulkan_bindless.h, d3d12_vulkan_device.cpp):
    • Refcounted ViewKey sharing, O(1) BindlessSet free-lists, single-lock bind_title_image(), ConsoleHeapSlotRecords kTexture/kSettled live tracking, and explicit evictable classification.
    • Two-phase GC (Phase 1 dead-key sweep with 0 texture notifications + 8,192-slot hysteresis, Phase 2 emergency live-LRU only on hard_full, multi-key sv.keys liveness, dim_2d mirror-slot room notifications) eliminating 65,536-slot saturation and GC thrash in long gameplay sessions.

3. Runtime Async Queue, Replay Cache, List-Value Sync & Single-Flight Coalescing (runtime/src/vulkan_backend.h, queue_holds.h, vulkan_replay.h, vulkan_presenter.h, runtime/shims/d3d12_com.cpp, d3d12_xs_list_values.h)

  • Dynamic rendering scope batching & ReplayStateCache: Batches compatible consecutive draws into single dynamic rendering scopes, elides redundant Vulkan pipeline/descriptor/push/viewport/scissor binds in emit_commands(), caches CommandList summaries, and fans out synchronous unbuilt PSOs concurrently via PipelineCompiler.
  • Zero-unmet list-value sync & GPU-to-GPU relays: Fixed Pump::choose_release() TOCTOU + quiet window (0 released unmet), dedicated QueueHolds barrier-drain thread, non-blocking release_ready(), SEH aligned volatile read_value(), 1000 ms slot-12 timeout, VulkanFence::signal_gpu_relay() (vis_seq=0) + retroactive QueueHolds::relay_wait() / VulkanQueue::apply_wait_relay() with WriteGroup::bare visibility safety, exact landed-value console_value_met() verification, wait_met re-check, relay_wait() gate preservation, and signal-only consumed_wait_vis transitivity.
  • Single-flight BeforeExecuteCoalescer + feed-only mirror drain: Reordered global refresh (wb -> mirror -> flush -> tex -> shadows -> 2nd flush) with decoupled lazy gpu_profile_.resolve() and 4-deep VulkanPresenter::frames_; coalesced submissions run a lock-free O(1) check / drain_page_mirror_feed_only() (0.11–0.29 ms when CopyPageMappingsBatchX remaps are queued) achieving 96–97% coalescing with 0 single-flight waits (opt-out LEONIDA_BEFORE_EXECUTE_COALESCE=0).

Measured Impact (RX 7900 XTX, RADV, Wine)

  • Stability: Continuous multi-minute cutscene + in-game runs (run107, post-merge run108: 370–400+ s) with 0 GPUVM faults, 0 VK_ERROR_DEVICE_LOST, 0 unmet list-value gates (across 28,372–42,047 held gates), and 0 bindless GC thrash (3 clean dead-sweeps of 8,192 dead keys each, 0 textures notified).
  • Opening cutscene FPS: Rose from ~0.6–0.8 fps baseline (3.6–5.9 fps at Round 6) to 7.4–13.9 fps (96–97% before-execute coalesced, 0 single-flight waits, own threads 50.8–88.3 ms/f, title threads 8.6–11.3 ms/f).
  • In-game gameplay FPS: Stable 6.0–7.4 fps (79–84 ms/f own threads, 7.0–15.1 ms/f title threads, Direct GPU now 66–75% utilized / 101–121 ms/f busy — shifting the bottleneck from CPU to GPU).

Tested

  • Shader translator & semantic suites (post-merge 232b4a1ee):
    • python3 -m compileall -q make_game.py tools tests: 0 errors.
    • python3 -m unittest tests/semantic/test_alu_exp_f32.py tests/semantic/test_ftz32_fmulz.py tests/semantic/test_buffer_format_d16_hi.py -v: 14/14 PASS.
    • All 17 merged-feature semantic suites (test_absent_lane_ub, test_ds_permute_eager, test_cvt_f16_denorm_mods, test_f16_denorm_preserve, test_buffer_format_d16_hi, test_gather4_c_lz, test_sample_g16, test_high_half_shared_readers, test_ftz32_fmulz, test_wave64_emulate_opt, test_wave64_halves, test_fma_denorm_product, test_alu_sat_pk_u8_i16, test_lds_bound_access, test_lds_write2_equal_offsets, test_active_runs, test_fp_edge_conformance): 278/278 PASS.
    • Full-corpus retranslation (32 shards): 29,267 / 29,267 shaders translated & spirv-val-valid; full-corpus check_absent_lane_ub.py sweep: 0 flagged / 0 UB sites.
  • Linux portable build & Vulkan tests (-march=x86-64-v3, MESA_VK_DEVICE_SELECT='1002:164e!'):
    • cmake --build runtime/build + ctest --test-dir runtime/build --output-on-failure -j8: 136/136 PASS (2 skipped: shader_library_corpus, vk_sync_validation).
    • LEONIDA_VK_VALIDATION=1 on list_value_progress, submit_frame, vk_title_mirror, vk_title_detile, vk_bindless_grow, vk_bindless_dimensions, title_mirror_hooks, r3b_runtime_hooks, replay_state_cache: 9/9 PASS, 0 validation errors.
  • Windows cross-build (clang-cl /arch:AVX2) & targeted Wine iGPU suite (r10-main-merge-igpu):
    • gta6rt.exe + gta6rt_tls_host.dll: clean build, 0 errors.
    • Targeted 41-test Wine iGPU suite (d3d12_existing_heap, d3d12_heap_in_place, d3d12_queue_wait, xbox_list_value_fallback, list_value_progress, submit_frame, console_heap_slot_records, title_mirror, shadow_keep, xmem, vk_bindless, vk_title_detile, d3d12_pipeline_checkpoint, xs_proxy_mock, acphal, d3d12_fence_timing): 40/41 PASS (xmem_write_watch passed on re-run; only upstream d3d12_fence_timing's EnumAdapterByLuid failed under headless Wine Xvfb without DRI3 — its GPU/CPU clock calibration checks passed).
  • Hygiene:
    • python3 -I scripts/check_no_game_data.py: PASS.

GPUs tested:

  • AMD Radeon RX 7900 XTX (RADV NAVI31), Mesa 26.3.1-arch1.3, Linux 7.3.6-zen1-1-zen (Wine)
  • AMD Ryzen 9 7950X3D iGPU (RADV RAPHAEL_MENDOCINO), Mesa 26.3.1-arch1.3, Linux 7.3.6-zen1-1-zen (native Linux + Wine)

AI-assisted: yes — Antigravity (Gemini 4 Neon & Claude Opus 5.5).

Checklist

  • Based on current main and merges cleanly (merged d48a957bb, reviewed by two independent reviewers).
  • One topic; follow-up work goes in a new pull request (integration PR of the PageMirror + CPU/GPU performance stack).
  • 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.

aslan2142 and others added 30 commits November 26, 2026 16:39
…cations need it (RT-MEMORY-BREAKDOWN-AND-SPARSE-ARENA)

The arena was one allocation of its whole size, made at start: with LEONIDA_ARENA_MB=4095 a world run used about
0.8 GB of it (peak end about 1 GB) and held 4 GiB of Resizable BAR memory. Where the device can, the arena is now a
sparse buffer: LEONIDA_ARENA_MB bounds the address range, and memory is bound as it is used.

- src/arena_backing.h (new): the backing units. A unit is one VkDeviceMemory, mapped once, bound over whole 2 MiB
  blocks. An allocation no larger than a block stays inside one block; a larger one takes whole blocks of its own
  (the free-block map's keep-out, footprint and alignment). A unit is bound before the first allocation in it is
  handed out, and when its last allocation is released it is pending with the release's retire ticket; it is unbound
  and freed only once completed_retire_ticket() has reached that ticket. An allocation in a pending block revives it.
- The CPU reaches the arena through one accessor, DeviceState::arena_host(offset, bytes): one table read, null with a
  rate-limited line for a range without memory. Callers that name an offset they do not hold (write_arena_value,
  read_arena, the fsdraw probe) use ArenaBacking::with_host under its shared lock; copy_destination and
  known_view_heap use offset_of. arena.mapped is gone, so every former `arena.mapped + offset` was converted.
- Binds go to a queue nothing else uses (pick_arena_bind_queue: RADV's sparse-only family, or a sparse family with
  a queue to spare) and are waited for there, so a bind never sits behind a submission that waits for a fence the
  CPU signals later. The device asks for that queue at creation.
- Unbinding is safe because: arena_release records submitted_retire_ticket() + 1 (as defer_destroy), so the
  submission being recorded is covered too; reclaim_arena() runs at the start of ExecuteCommandLists, reads
  completed_retire_ticket() before taking the arena lock, and unbinds only units whose ticket has completed; the
  table entries are cleared under the exclusive lock before the memory is freed. An unbound range reads as zero
  (residencyNonResidentStrict is required), never a fault.
- A D3D12 heap in the arena lends its unit's memory (at the heap's place in the unit) to reserved resources' tiles;
  Heap::offset() keeps the arena VA.
- Without sparse buffers, strict residency, a sparse address space as large as the arena, or a queue to spare
  (llvmpipe), one allocation backs the whole arena as before, through the same accessors. No new setting.
- The arena line at release gains `GPU address arena: bound N MiB now (peak P, U units of 2 MiB blocks, sparse)`;
  the mem-probe breakdown's arena `bound` is the bound bytes.

Tests: arena_backing_test (CPU, fake driver): placement never crosses a unit, binds shared per block, unbinding
waits for the ticket, revival, a random workload whose bound bytes equal the blocks live allocations touch, bind
failure, the one-allocation arena, the bind queue choice. arena_sparse_gpu_test (a real device, 77 without sparse
binding): a 256 MiB arena with 40 MiB allocated has 44 MiB bound; CPU writes are what the GPU reads; released blocks
stay bound while a submission that reads them is in flight and are unbound (reading zero) once it completes; a bind
made while the work queue is blocked completes. Both are new (fail to build on main).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…; a sparse arena only then (RT-MEMORY-MODEL)

RADV puts sparse buffers 64 TiB above ordinary ones, so with the sparse arena of the previous commit every geometry
copy and title-window block lay below heap_base and TitleBufferWindows::allocate refused it (it accepted only a
positive offset below 2^47). Shaders translated since 2026-11-24 sign-extend a V#'s 48-bit base and say so in their
index entry (vsharp_base_sign_extended), and RADV hands out every address from one 2^47 half of the 48-bit space, so
any block is within reach of heap_base as a signed offset.

- shader_library.h: VsharpBaseCensus counts the marker over every loaded module; signed only when all have it.
- The device reads V# bases signed when the census says so (or with LEONIDA_IMPORT_BELOW_ARENA=1, as before). The
  import refusal still follows that setting alone. One line logs the census.
- create_arena: the arena is sparse only with signed offsets; otherwise one allocation, and one line says why.
- TitleBufferWindows::shader_reachable replaces the positive-only check. The first failure of each Vulkan call while
  making a block, and the first block refused for its address, are logged.
- rebase_title_vsharp sign-extends a base it already rewrote below heap_base.
- device_arena_memory (for tests); cs_user_data.comp reads V# bases sign-extended, as translated shaders do.

Tests: d3d12_title_va_game_device and d3d12_geometry_views_game_device (d3d12_title_va_test --game-device: the
device the game makes, with the arena's bind queue); geometry_views_test (shader_reachable at the measured RADV
addresses and the range edges); shader_library_test (the census). Wine suite on the iGPU: 429 pass / 23 fail against
425 / 23 on main 8bc59a7, nothing pass to fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…on the CPU, and are never skipped (RT-TITLE-UPLOAD-GPU-ORDER)

A title texture upload waited on the CPU, with the submit lock held, for all work submitted on every queue, at
most 250 ms, and skipped the write when that work was not done. World frames take longer, so changed textures
(the planes of a video frame among them) arrived late or out of step, and the submitting thread stalled up to
250 ms per upload (the 200-277 ms maxima of the textures phase in world runs).

The staged transfer now waits for that work on the GPU: write_staged_title_image hands it every queue timeline
value submitted so far. Every such value is already submitted, and console waits whose signal is not submitted
live in QueueHolds, so the GPU wait cannot deadlock. The upload slots are reused once their transfer is done
(looked up, not waited for), and new ones are made while all are in flight. Every title fill goes through this
upload, so the host-copy path for title textures (write_host_texture, its bounded wait and
LEONIDA_ORDER_TEXTURE_UPLOADS) goes. As before, the transfer is submitted on the primary queue before the
submission whose before_execute runs the refresh, and the other queues wait for it on the GPU, so that
submission's draws sample the new texels.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ere written, not at every texture's bytes (RT-TITLE-TEXTURE-WRITE-TRACKED)

Before every submission (at most every 16 ms, and not at all when a view held the registry), the refresh hashed
every mapped or stale texture and a round robin of the rest (sampled, a full hash every sixth pass), within
byte and time budgets that could split the planes of one video frame over passes.

Now each title texture filled from memory is watched through the geometry watch's cells: its 64 KiB tiles, at
its CPU view and every other address xmem maps them at, are armed read-only; a write faults once per tile, and
the fault, a mapping change or a kernel write's opening queues the tile (geometry_writes::WriteQueue, new). The
refresh, at every submission and with the registry waited for, takes that queue and reads only the textures over
the written tiles (TitleTextureWatch, src/title_texture_watch.h), arming them again before the read; a texture
nobody wrote costs nothing. A tile that cannot be armed (not committed, pinned, no fault handler) names its
textures at every pass: the one fallback. A fill whose full hash equals the last one uploads nothing. A slot-70
view no longer hashes its texture: it fills only one never filled or known changed.

Removed with the hash pass: LEONIDA_TITLE_TEXTURE_PERIOD_MS, _CHECK_KB, _FILL_MB, _FILL_MS,
LEONIDA_TEXTURE_HASH_BUDGET_US, LEONIDA_TEXTURE_SWEEP_BUDGET_US, LEONIDA_TITLE_EVERY_BUDGET_US,
LEONIDA_TITLE_VIEW_REFRESH_MS and the async mode LEONIDA_TEXTURE_REFRESH_ASYNC (its worker pass, first-use
fills, mapped list and range index). A line every 10 s counts passes, textures looked at, uploaded, unchanged,
written tiles and arms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nly at the slots it overlaps (RT-SLOT-RECORDS-EXACT-INDEX)

The records' two indexes kept each V# half in a bucket per power-of-two span class and 64 KiB-or-larger block,
and a change visited every entry of every bucket it reached, plus resolved halves for an addition that only
re-fixes waiting ones: 82,000-472,000 slots looked at per submission for 2-15 changes and 1,450-3,150 slots
fixed in the busiest world windows of one run, 4.4-13.4 ms a submission.

Now each index holds the halves by their exact range: halves naming the same range share a group with a resolved
and a waiting list, each half keeping its place in its list (a move or a removal is O(1), no stale entries, an
empty group goes). Groups are ordered by start per power-of-two class of their length; a query searches each
class in use once and walks the groups starting less than one class length before the change. A change looks at
exactly the halves whose range overlaps it (an addition: the waiting ones only); the groups compared besides are
those that start within one class length before it and end before it, one comparison each and no slot. 20 bytes
a half (was 24), plus a group per distinct range. Interface and device code unchanged.

Test: 300,000 slots of 16 bytes packed into 74 blocks of 64 KiB; a 40-byte release looks at the 3 it overlaps
(the bucketed index looked at the whole block and fails), by source it also finds a 1 MiB range starting two
blocks earlier, a moved slot leaves nothing behind, and an addition over all of them looks at the 1,000 waiting.
The 400 random rounds against a full re-resolution still pass (entries looked at 792,825 -> 133,506 for the same
81,005 slots fixed); copies that skip large ranges or the waiting lists on a removal fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tes, not host remaps (RT-MEMORY-MODEL)

The console queue's CopyPageMappingsBatchX goes through xmem's range callback in a retail run. It host-mapped every
destination page of a paired GPU-only range twice: the GPU-only page and its CPU twin. Each map is a VirtualQuery, a
placeholder split and a MapViewOfFile3/UnmapViewOfFile2, which are wineserver round trips under Wine. All of it ran on
the render thread under g_phys_mutex, which DirectStorage's page transfers take too. A local world run spent 3.9-6.0 s
mapping per 10-12 s.

Nothing on the host reads a GPU-only address of a paired range:
- the D3D12 layer, DirectStorage and the texture refresh read the CPU twin (title_gpu_views::to_cpu);
- the runtime reads a page by number through its section's scratch view (host_page);
- the title's CPU never touches the range (PAGE_NOACCESS on the console).

So such a page now gets its physical page in g_mapped and g_table_pages alone, with no host view, as the console edits
GPU page tables only. The twin is mapped as before, and so is a destination with no CPU pair: an independent-pages
range (LEONIDA_SLOT31_RUNS), whose pages are read where they are.
- A view the title mapped there itself is unmapped once when a copy lands on it.
- unmap_range_locked drops table pages in its range, so the title's own unmap or release clears them.
- A table page is not one of its physical page's host addresses (no note_mapping, no alias peer). It can be neither
  written nor guarded on the host, so a twin plus a GPU-only page is no longer "aliased" for the slot-133 shadows and
  the geometry watch.
- A table update raises title_memory_map::changed and geometry_writes::notify(replaced) for the GPU-only address, as
  a host remap did. A remap changes bytes, not what a V# resolves to, so the slot-record change list is not involved.
- The periodic slot-31 line gains "pages N by table, M by host remap" (slot31_mapping_counts).

Tests (Wine):
- xmem_test, test_copy_page_mappings_cpu_view: no host view on the GPU-only range; one host remap per page, not two;
  a copy from a GPU-only page finds what its table entry holds; a page the title mapped there is replaced by a table
  entry; the title's unmap clears the table.
- d3d12_xmem_placed, queue_remap_default_route: it read the GPU-only pages directly (the old behaviour). It now reads
  them through a slot-31 copy and checks that they have no host view.

Wine suite on the iGPU: 425 pass / 23 fail, the same as main e5a7c89, nothing changed. Linux ctest on llvmpipe:
115/115.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…guarded (4f364c8)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
… when it appears; no T# retries

A title-written T# that found no texture went on a retry list that every submission tried again, round robin, for
500 us (LEONIDA_CONSOLE_RETRY_US). World runs had up to ~35,000 waiting, 200-550 retried per submission, and every
retry counted again as a T# "naming no texture" (1.56 million in 27 log windows of one run). A bound T# whose texture
went never came back unless the title rewrote its slot.

The per-slot records of RT-VSHARP-SLOT-RECORDS now hold T#s too (src/console_heap_slot_records.h): the exact base
address and bound / waiting / waiting for room, with an index by that address. Texture changes go on the same change
list: note_image_address, a GPU placement added and a streamed texture published (texture_added), forget_image and a
placement removed (texture_gone), freed bindless entries (texture_room), each also at the other view of pool memory.
The next submission fixes exactly the T#s naming the address. A V# refused a geometry copy for lack of room is fixed
again when geometry copies are freed (geometry_room, GeometryViews::free_generation), closing the gap A1 left.

"No texture at the T# address" is counted in "unbound T#s by reason" by what the address is: title memory, a texture
of ours that is gone, low 32 bits naming one of ours (same shape / other shape / gone), or none. The slot records
line gives T#s recorded, waiting, fixes left waiting and refills.

Removed: retry_console_slots. LEONIDA_CONSOLE_RETRY_US applies only to the opt-in GPU heap pass now; slots deferred
by LEONIDA_CONSOLE_FIX_US are fixed first at the next submission (fix_deferred_slots).

Tests: console_heap_slot_records_test (T# and room cases), new d3d12_tsharp_refill_test (the last of 60,001 waiting
T#s samples its texture at the first submission after it appears; its T# leaves the hash table when it goes),
d3d12_unbound_tsharp_rules_test (address classes). Linux ctest 115/115 (llvmpipe); Wine suite (clang-cl, iGPU RADV)
425 pass / 24 fail, against test/three-fixes 425/23: d3d12_tsharp_refill new and passing, xmem (known flake) the
only pass->fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ng else can make progress

A list value wait (wait32/wait64) that is not met at submission holds its queue until memory meets it. The fixed
200 ms timeout, LEONIDA_VALUE_WAIT_TIMEOUT_MS and the 4 ms demotions are removed (in Linux world runs 14-63 gates a
run timed out with the writer's value not there yet).

A held gate goes without its value only when nothing else can make progress (releaser idle, no title
ExecuteCommandLists in progress, nothing of the pump's running on the GPU; work the layer holds behind a wait is not
running, asked through the new rt::d3d12::fence_signal_submitted), and then only: in a cycle (at once), at a present
queued behind it (VIctory-Belobug-AMD's rule, queue/behind.rs step, queue.rs release_held), or when the title has made
no queue call for 2 s; every gate goes at device loss. src/list_value_progress.h (portable) replaces
list_value_wait_budget.h. Each release is logged with gate, queue, wait and reason; released waits met later are
counted. stop() drops gates it leaves shut so they no longer hold their queues.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t probe their memory again (RT-TITLE-TEXTURE-WRITE-TRACKED)

A pending stream texture whose first bytes arrive through a noted write (the pending slot-70 views case of
d3d12_existing_heap) kept its cached unreadable answer and was never filled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…the GPU (8c579b7)

runtime/README.md: the sparse arena changed the LEONIDA_IMPORT_BELOW_ARENA row and the texture work removed the LEONIDA_ORDER_TEXTURE_UPLOADS row next to it; the arena's row is kept and the removed row stays removed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The T# records, the room lists and the texture and room changes of descriptor-refill now live in the exact-range
index of slot-records-index. src/console_heap_slot_records.h: a third index, by T# address (the exact range
[address, address + 1)), of the same groups with a settled and a waiting list; a texture gone visits exactly the
T#s recorded for its address, a texture added the waiting ones. The records waiting for room (V# halves refused a
geometry copy, T#s refused for a full bindless array) are kept in a list per kind with each record's place, so a
record leaves it in O(1) and room made visits only the records waiting for it. Interface as descriptor-refill
has it (states, set_texture, base, textures, textures_waiting); device code, README rows and both sides' docs kept.
32 bytes a half.

Tests: console_heap_slot_records_test, both sides' cases (60,010-slot release; 300,000 slots in 74 blocks, a
40-byte release looks at 3; 400 random rounds against a full re-resolution; a texture registered looks at the 10 of
60,015 waiting on its address; room changes touch only the records waiting for room); a copy that skips settled
lists on a removal fails. Linux ctest 115/115.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
runtime/README.md: the console-heap rows come from the refill branch, the shadow rows from ProjectLeonida#1867.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…nd a kernel write in progress is waited out, not read (RT-TITLE-TEXTURE-WRITE-TRACKED)

Run 57 showed 99.9 % of the arms refused, 60,637 tiles not armed and about 8,700 textures looked at per pass
(60-68 ms a pass). The refusals were this watch's own: a tile with any page not committed was refused, so
every streamed texture registered before its memory arrived was named and its arming retried at every pass,
and a texture never filled because its memory was not readable was named again at every pass too.

Now pages not committed are left as they are: xmem's commit or mapping bumps the tile's cell, and the mapping
change makes the textures over it probe their memory again. A texture whose memory is not readable is not
named again until then, except one the title mapped (its pages may be committed under the Map pointer). A tile
pinned for a kernel write is busy: the texture is not read (which uploaded half-written textures at every pass
until the write ended) and is read once the pin is gone. Only a tile whose guard cannot be set is read at every
pass. The log line counts busy looks and arms apart from refusals.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…wait for the write (9aed60a)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…holds; a record is looked at once an index a submission

One world run with the merged index showed 60,000-135,000 records looked at per submission for 1,300-2,600 slots
fixed again and 130-210 changes. Two causes in ConsoleHeapSlotRecords::touched:

- An addition (an alias range, title memory, a backing) visited every waiting record whose range overlapped it.
  Waiting V#s with large spans (data words that read as V#s of up to 4 GiB into title memory) were visited by every
  addition anywhere inside their span, at nearly every submission, and fixed again to no effect. A V# resolves only
  through an alias range, backing, copy or title memory that holds its base (or a backing that holds its refused
  target), so an addition now visits the waiting records whose range starts inside it; the groups with waiting
  records are kept by start a second time for this, so only those are walked. TitleVaAliases tells title memory as
  the merged range it is now part of (a V# whose base lies in the older part may fit only now), and nothing for a
  commit inside a range it already has.
- A record named by several changes of one submission was looked at once per change. Each group's two lists now
  carry the touched() call that last visited them, so a record is looked at once an index a call at most.

Test: 5,000 waiting halves of 4 GiB; 200 additions inside their spans that hold no base look at none (the previous
index looked at all of them 200 times and fails), one that holds 10 bases looks at those 10; 200 removals over the
same 5,000 resolved halves look at each once. The 400 random rounds against a full re-resolution still pass (slots
fixed again there 81,005 -> 75,919, looked at 133,506 -> 97,952); a copy whose removals skip waiting records fails.
Linux ctest 115/115.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…mission (67863b3)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
… on several threads, and submits their uploads in order (RT-TITLE-TEXTURE-WRITE-TRACKED)

Run 58: with the watch in effect a pass still read, hashed and detiled every named texture on the title's
submitting thread, one after another: about 1,250 textures and 95 MiB a pass in the world load, 198 ms a pass,
up to 795 ms (read from write-combined title memory, a full hash, the detile into the upload slot).

The upload is split into three steps (TitleImageUpload::reserve, fill, commit). The pass reserves a slot for
each named texture on its own thread, a small pool of threads of ours (TitleReadPool, a quarter of the cores,
at most seven, plus the submitting thread) copies, hashes and detiles them in batches of 16 or 64 MiB, and the
submitting thread then records and submits the transfers one by one in key order, still before the submission
whose draws sample them. The reads of different textures are independent; only the submissions carry the
ordering, and they stay where they were.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…transfers committed in order (d170028)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…d to it; a rewritten V# whose range waits takes that answer

Two findings from one world run (every slot records line: 0 refills; fixing slots 18.2 ms a submission).

T#s: the title rebuilds T#s of the layer's textures from 32 bits. The run's unbound T#s name 0x7f0000021400 for the
layer's 0x100021400 and 0x2ef600 for 0x1002ef600 (bits 32-39 clear, 0x7f or 0 in bits 40-47): "its low 32 bits name
a texture of ours that is gone" (291-3,794 a window) and "no title memory and no texture of ours" (270-4,585, low bits
past the last address handed out: textures still to come). They were recorded under that address, while a texture's
arrival is announced at the layer's address, so no arrival ever reached them, and bind_title_image looked them up by
the exact address only. tsharp_texture_key maps such an address outside the title's memory to the layer's texture
address with the same low 32 bits (while fewer than 2^24 were handed out); the T# waits under it, and
bind_title_image takes the texture there when its shape fits (another shape stays unbound, as before).

V#s: about 2,100 rewritten V# halves a submission, 70% resolving to nothing at about 9 us each (the alias table,
the backings, the geometry copies and the title memory walked again, VirtualQuery included), 63% with words seen
before. A waiting record is fixed again by every change that could let it resolve, so while one waits its answer
stands: a rewritten half whose exact range another half of the heap waits for takes that answer
(ConsoleHeapSlotRecords::waiting_answer, one hash lookup; a half that asks for a geometry copy only from one that did,
and not after geometry room was freed since the refresh). To keep answers current, the submission's changes are
applied before the rewritten slots, and the changes noted during the pass (a window a fix made, a buffer another
thread released) are applied to the heap before an answer is taken (sync_slot_changes). The records keep a third
list per range for waiting halves that asked for a geometry copy. The slot records line counts the answered halves.

Tests: d3d12_tsharp_refill_test also writes the texture's T# in the title's two 32-bit forms before the texture exists
and expects both bound at the first submission after it appears, and gone with it. d3d12_unbound_tsharp_rules_test:
the 0x7f form with the texture's shape binds (it expected "no texture"). console_heap_slot_records_test: in the 400
random rounds half the writes take a waiting answer after applying the changes noted so far, and each answer must be
what resolving at that moment gives (a copy that skips applying them fails); the rounds still equal a full
re-resolution. Linux ctest 115/115.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…om it; textures are read at first use and by their written tiles (RT-TITLE-TEXTURE-WRITE-TRACKED)

Blocks of older frames in run 58: a texture without GPU-write flags placed over the memory of a GPU-written
one (a render target, depth or UAV texture) was filled from the title's pages there. Those pages never hold
what our GPU renders into the target's image, only what the CPU last put there, and every write mark over
them (a write-back of a GPU copy, a neighbour's write in the same tile) re-uploaded those old bytes. The
registry now keeps the CPU-view range of every GPU-written texture (DeviceState::gpu_owned), and a texture
over such a range is not watched or filled by the refresh (index_texture); one already watched stops when the
target is registered. Test: d3d12_existing_heap's "texture over a render target's memory" (fails without
this: the written 64 KiB piece shows in the texture).

Upload at first use: a title texture no descriptor names is not read, uploaded or watched. Its first
descriptor of any kind (a D3D12 view, a slot-70 view, a T# the title wrote into a console heap: all reach
Resource::note_shader_view) queues it, and the refresh before that submission reads it whole and uploads it.
A texture whose descriptors are all gone later stays on the write-driven path (nothing counts them down).

Reads by written tiles: each texture keeps a hash of its part in every 64 KiB tile (TilePieces). When some
of its tiles were written, those parts are hashed in place first; equal, and the texture is unchanged
without a whole read. The watch reports writes per 64 KiB tile (the geometry cells' fault reopens a whole
tile), so a neighbour in a written tile costs its share of that tile, not a read of all of it.

The 10 s line: textures written or new, read whole, found unchanged by their parts, uploaded, named for the
first time, not named by any descriptor (not read), ms a pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…#s in the title's 32-bit form wait under our address (d94b6c3)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…re's first descriptor, written parts hashed (f7c3df1)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…y resolve to the render target's image (RT-TITLE-TEXTURE-WRITE-TRACKED)

f7c3df1 stopped filling such a texture from the title's pages; its own image then held nothing the GPU
drew. A GPU-written texture placed at the address (render target, depth or UAV) now answers first, for
console T#s (bind_title_image) and slot-70 views (place_title_view), when the description fits: the T#'s
extent and samples, and mips and layers within the target's (TitleGpuPlacements::matches), in any format the
target's image takes a view in (its own, a castable one, or one its view list allows). Otherwise the other
texture answers as before, and the reason is counted (format; extent or samples; mips or layers) in a line
next to the refresh's.

Either order at one address: a render target placed over a texture placed first leaves that texture's
registry entry in place and drops its T# bindings, so they bind again, to the target. The ranges GPU-written
textures cover are kept by the resource (DeviceState::gpu_owned), so a texture placed later at the same
address does not take the target's range away; when the target goes, the texture at its address is filled
from memory again and its T#s find it. D3D12 views the title made of the plain resource itself still name
its own image.

Test: d3d12_existing_heap's "view over a render target" (both orders, and the target's release).

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

Copy link
Copy Markdown

I retested the queue and presenter changes on a desktop RTX 4090, driver 616.64, in response to the NVIDIA retest request. The asynchronous compute wait now completes. The stock M4 shader fixtures still fail Vulkan validation on this card.

Native Windows, MSVC Release, Khronos validation 1.4.369, synthetic tests. I compared eccc71b324 directly with its parent 660872215a.

CTest Parent PR head
vk_presenter_sync Failed presenter.presented() == shown + 1 after destroying the queue Passed 3/3, including the queued present
vk_presenter_sparse_capture Passed Passed 3/3
d3d12_m4_compute, stock shaders Four validation errors Same four errors
d3d12_m4_compute_async_small_waits, stock shaders Timed out at 30 s Finished in 0.29 s with the four validation errors

Remaining fixture issue. The head's device probe reports denorm_flush_to_zero_f32=false. The CMake fixture builder still emits DenormFlushToZero 32 for both cs_m4_fill and cs_m4_indirect, triggering VUID-VkShaderModuleCreateInfo-pCode-08740 and VUID-RuntimeSpirv-shaderDenormFlushToZeroFloat32-06300.

I rebuilt only those two synthetic shader modules with --no-ftz32 and reran the same test binaries with validation enabled. On the parent, ordinary M4 passed and the asynchronous case still timed out at 30 s. On the head, both passed 3/3. Each of the six runs read back all 1,924 expected words with zero validation errors. The synthetic FSSM inputs were byte-identical. Having runtime/test/shaders/build.py use the FTZ32 capability decision already used by make_game.py would let the stock fixture exercise the fixed wait on this driver.

Coordination claim. AI-assisted verification with OpenAI Codex (GPT-6).

@ecox982745

Copy link
Copy Markdown

The attached patch fixes the stock M4 shader fixtures on the RTX 4090. It applies directly to eccc71b324 with git am. The fixture builder now passes --no-ftz32 when the selected GPU explicitly reports that it lacks float32 flush-to-zero. A supported or unknown capability keeps the translator default. The builder reuses one probe for this choice and the existing barycentric fallback.

I rebuilt d3d12_m4_compute_test from scratch on native Windows with MSVC Release, NVIDIA driver 616.64 and Khronos validation 1.4.369. Both stock CTests used the shaders generated by CMake.

Test RTX 4090 result
d3d12_m4_compute 3/3 passed
d3d12_m4_compute_async_small_waits 3/3 passed

Every run matched all 1,924 GPU output words against the CPU reference, with zero Vulkan validation errors. Both generated shaders passed spirv-val --target-env vulkan1.2. Before the patch, each stock test produced four validation errors on this same PR head. Earlier controlled comparison

The shader-builder and translator-flag suites passed 7/7 and 42/42, respectively. The patch also isolates the translator tests from the host GPU and checks that an unavailable capability probe preserves the recorded FTZ choice. AI-assisted with OpenAI Codex (GPT-6).

Apply the three-file patch to the PR branch

Copy the following block to a file and run git am shader-fixtures.patch.

From 0d505491c77801297c526fd5333d7e60f9a6f070 Mon Sep 17 00:00:00 2001
From: OpenAI Codex <codex@localhost.invalid>
Date: Sun, 29 Nov 2026 10:05:52 +1000
Subject: [PATCH] tests: honor GPU float32 flush-to-zero support in shader
 fixtures

Pass --no-ftz32 when the selected device reports no float32 flush-to-zero support. Probe once for both fixture fallbacks and keep the existing default for an unknown capability. Isolate the translator flag tests from the host GPU and cover reuse of a recorded FTZ choice.

AI-assisted with OpenAI Codex (GPT-6).
---
 runtime/test/shaders/build.py            | 33 ++++++++++++++----------
 tests/test_make_game_translator_flags.py | 10 ++++++-
 tests/test_shader_build_fallbacks.py     | 27 ++++++++++++++++---
 3 files changed, 52 insertions(+), 18 deletions(-)

diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py
index 377f7025e..9513cac7c 100644
--- a/runtime/test/shaders/build.py
+++ b/runtime/test/shaders/build.py
@@ -60,17 +60,25 @@ def barycentric_fallback_override():
     return None
 
 
-def barycentric_fallback():
-    override = barycentric_fallback_override()
-    if override is not None:
-        return override
+def gpu_fallback_flags():
+    """Match the selected device's barycentric and float32 flush-to-zero capabilities."""
     try:
         r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "vk_subgroup_info.py")],
                            capture_output=True, text=True, timeout=60)
         answer = json.loads(r.stdout.strip().splitlines()[-1])
-        return answer.get("barycentric_fallback") is True
     except (OSError, ValueError, IndexError, subprocess.SubprocessError):
-        return False
+        answer = {}
+    if not isinstance(answer, dict) or "error" in answer:
+        answer = {}
+    flags = []
+    bary = barycentric_fallback_override()
+    if bary is None:
+        bary = answer.get("barycentric_fallback") is True
+    if bary:
+        flags.append("--bary-fallback")
+    if answer.get("denorm_flush_to_zero_f32") is False:
+        flags.append("--no-ftz32")
+    return flags
 
 
 def asm_mattr(path):
@@ -145,7 +153,7 @@ def gs_container():
             + b"ISG1" + chunk + b"OSG1" + chunk)
 
 
-def translate_tests(work, names):
+def translate_tests(work, names, gpu_flags):
     disasm, fssm, spirv = (work / d for d in ("disasm", "fssm", "spirv"))
     disasm.mkdir()
     fssm.mkdir()
@@ -184,11 +192,9 @@ def translate_tests(work, names):
             (work / (n + ".dxbc")).write_bytes(gs_container())
         else:
             (work / (n + ".dxbc")).write_bytes(bytes(32))  # chunk count 0
-    cmd = [sys.executable, "-I", TRANSLATOR, disasm, "--out", spirv]
+    cmd = [sys.executable, "-I", TRANSLATOR, disasm, "--out", spirv, *gpu_flags]
     if os.environ.get("LEONIDA_W64_EMULATE") == "1":   # wave64 on 32-wide subgroups (compute shaders only)
         cmd.append("--wave64-emulate")
-    if barycentric_fallback():   # raw barycentrics without VK_KHR_fragment_shader_barycentric
-        cmd.append("--bary-fallback")
     if os.environ.get("LEONIDA_FMA") in ("glsl", "khr", "exact"):   # GLSL Fma (default), OpFmaKHR, or emulated
         cmd += ["--fma", os.environ["LEONIDA_FMA"]]
     if os.environ.get("LEONIDA_F16_INTERP_FALLBACK") == "1":   # f16 interpolation without PerVertexKHR (MoltenVK)
@@ -227,7 +233,8 @@ def main():
     names = [n for n in names if n not in skipped]
     # A computed I/J pair needs PerVertexKHR inputs, which both fallbacks take away: the translator refuses it there,
     # and check.py and run_gpu_tests.py report it as SKIP. Leave it out instead of losing the whole batch.
-    if barycentric_fallback() or os.environ.get("LEONIDA_F16_INTERP_FALLBACK") == "1":
+    gpu_flags = gpu_fallback_flags()
+    if "--bary-fallback" in gpu_flags or os.environ.get("LEONIDA_F16_INTERP_FALLBACK") == "1":
         per_vertex = [n for n in names if n in NEEDS_PER_VERTEX_INPUTS]
         if per_vertex:
             print("not built (computed I/J pairs need PerVertexKHR inputs, off under the fallback):",
@@ -238,7 +245,7 @@ def main():
     out.mkdir(parents=True, exist_ok=True)
     with tempfile.TemporaryDirectory(prefix="test-shaders-", dir=out) as tmp:
         work = Path(tmp)
-        status = translate_tests(work, names)
+        status = translate_tests(work, names, gpu_flags)
         if status:
             return status
         built = work / "spirv"
@@ -266,7 +273,7 @@ def main():
         sys.path.insert(0, os.path.join(HERE, "..", "..", "..", "tools"))
         import spirv_stubs
         spirv_stubs.generate_for_index(str(spirv), combined)
-        if barycentric_fallback():
+        if "--bary-fallback" in gpu_flags:
             # The pass-through geometry shader each --bary-fallback PS is drawn with (<name>.bary_gs.spv).
             import bary_fallback_gs
             bary_fallback_gs.build_for_index(str(spirv))
diff --git a/tests/test_make_game_translator_flags.py b/tests/test_make_game_translator_flags.py
index 50336e4fe..76b6a6884 100644
--- a/tests/test_make_game_translator_flags.py
+++ b/tests/test_make_game_translator_flags.py
@@ -369,7 +369,7 @@ class ProbeFailureKeepsAutomaticFlagsTest(RecordedFlagsTest):
 
     AUTOMATIC = ("--f16-interp-fallback", "--pc-tail-ubo")
 
-    def build(self, *extra_argv, per_vertex, max_push_constants, mesh_crash=False):
+    def build(self, *extra_argv, per_vertex, max_push_constants, mesh_crash=False, denorm_ftz_f32=True):
         """One `make_game.py --stages shaders` run: (the fallbacks of each translation it started, its log)."""
         translations, lines = [], []
 
@@ -394,6 +394,8 @@ class ProbeFailureKeepsAutomaticFlagsTest(RecordedFlagsTest):
                 mock.patch("make_game.wave64_settings", return_value=(False, True)), \
                 mock.patch("make_game.runtime_gpu_per_vertex", return_value=per_vertex), \
                 mock.patch("make_game.runtime_gpu_barycentric_fallback", return_value=None), \
+                mock.patch("make_game.runtime_gpu_integer_dot_product", return_value=True), \
+                mock.patch("make_game.runtime_gpu_denorm_ftz_f32", return_value=denorm_ftz_f32), \
                 mock.patch("make_game.runtime_gpu_max_push_constants", return_value=max_push_constants), \
                 mock.patch("make_game.runtime_gpu_mesh_draws_crash", return_value=mesh_crash), \
                 mock.patch("make_game.preflight"), \
@@ -426,6 +428,12 @@ class ProbeFailureKeepsAutomaticFlagsTest(RecordedFlagsTest):
         self.assertEqual(self.build(per_vertex=False, max_push_constants=None)[0], [])
         self.assertEqual(self.recorded(), " ".join(self.AUTOMATIC))
 
+    def test_failed_ftz32_probe_keeps_the_recorded_choice(self):
+        self.assertEqual(self.build(per_vertex=True, max_push_constants=256, denorm_ftz_f32=False)[0],
+                         [("--no-ftz32",)])
+        self.assertEqual(self.build(per_vertex=True, max_push_constants=256, denorm_ftz_f32=None)[0], [])
+        self.assertEqual(self.recorded(), "--no-ftz32")
+
     def test_a_probe_that_answers_still_decides(self):
         # Another GPU, or a driver that now takes PerVertexKHR inputs and 144 bytes: translating again is right.
         self.build(per_vertex=False, max_push_constants=128)
diff --git a/tests/test_shader_build_fallbacks.py b/tests/test_shader_build_fallbacks.py
index e205bfe95..d2267f5bb 100644
--- a/tests/test_shader_build_fallbacks.py
+++ b/tests/test_shader_build_fallbacks.py
@@ -47,7 +47,7 @@ class BuildUnderFallbackTest(unittest.TestCase):
         self.out = Path(tmp.name) / "out"
         self.asked = []
 
-    def fake_translate(self, work, names):
+    def fake_translate(self, work, names, gpu_flags):
         """What rdna2spirv.py leaves in <work>/spirv: a module and an index entry per shader it validated."""
         self.asked.append(list(names))
         fallback = any(os.environ.get(v) == "1" for v in FALLBACKS)
@@ -118,13 +118,32 @@ class BuildUnderFallbackTest(unittest.TestCase):
                     mock.patch.dict(os.environ, {"LEONIDA_BARY_FALLBACK": value}, clear=False):
                 proc = SimpleNamespace(stdout=json.dumps({"barycentric_fallback": probe}) + "\n")
                 with mock.patch.object(self.build.subprocess, "run", return_value=proc):
-                    self.assertIs(self.build.barycentric_fallback(), want)
+                    self.assertEqual("--bary-fallback" in self.build.gpu_fallback_flags(), want)
+
+    def test_ftz32_flag_follows_the_probed_device_even_with_a_barycentric_override(self):
+        for report, disable in (({"denorm_flush_to_zero_f32": False}, True),
+                                ({"denorm_flush_to_zero_f32": True}, False),
+                                ({"denorm_flush_to_zero_f32": None}, False), ({}, False)):
+            with self.subTest(report=report), tempfile.TemporaryDirectory() as tmp:
+                assembled = SimpleNamespace(stdout="\ts_endpgm\n", stderr="", returncode=0)
+                probe = SimpleNamespace(stdout=json.dumps(report), returncode=0)
+                translator = SimpleNamespace(returncode=23)  # stop after recording the translator command
+                with mock.patch.dict(os.environ, {"LEONIDA_BARY_FALLBACK": "0"}), \
+                        mock.patch.object(sys, "argv", ["build.py", tmp, "cs_store"]), \
+                        mock.patch.object(self.build.mc_command, "run", return_value=assembled), \
+                        mock.patch.object(self.build.subprocess, "run", side_effect=[probe, translator]) as calls:
+                    self.assertEqual(self.build.main(), 23)
+                self.assertEqual(calls.call_count, 2)
+                command = calls.call_args.args[0]
+                self.assertIn(self.build.TRANSLATOR, command)
+                self.assertEqual("--no-ftz32" in command, disable)
+                self.assertNotIn("--bary-fallback", command)
 
     def test_a_missing_module_without_a_fallback_still_fails_the_batch(self):
         keep = self.fake_translate
 
-        def refuse(work, names):
-            keep(work, names)
+        def refuse(work, names, gpu_flags):
+            keep(work, names, gpu_flags)
             os.remove(os.path.join(work, "spirv", "cs_store.spv"))
             return 0
         self.fake_translate = refuse

@github-actions github-actions Bot added the needs rebase Conflicts with the base branch: rebase it on main label Nov 29, 2026
This was referenced Nov 29, 2026
@Tauwni

Tauwni commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

AMD RDNA4 complement: vk_heap_alias (new in this PR) fails on a discrete AMD card, and an A/B narrows it to the queue the unbind runs on.

Radeon RX 9060 XT (RDNA4, 16 GB, desktop), driver 32.0.23033.1002 (Vulkan driverInfo 26.3.1, API 1.4.344), Windows 10 Pro 22H2 19045.7846, MSVC 14.44 RelWithDebInfo. PR head eccc71b32 tested as is: it does not merge into main b6bf3aa0b (conflicts in tools/rdna2spirv.py, tools/lane_masks.py, runtime/shims/d3d12_vulkan_device.cpp, runtime/test/vk_harness.cpp, docs/design.md, tests/semantic/test_wave32_lane_select.py).

ctest at the head vs main. MEASURED, full run, then failures rerun alone 3 times. Head: 12 failures out of 505; main: 11 out of 497. Only one is new and reproducible: vk_heap_alias, 3/3, line 311: got[per_page + i] == 0. The other 8 reproducible ones fail identically on main here (Windows 10's in-box D3D12/WARP and known AMD driver cases). dxgi_waitable_latency, d3d12_compile_teardown_one_worker and title_texture_watch failed only under -j 6 and passed 3/3 alone.

What the failing check reads. MEASURED, 3 runs, with a temporary print, not pushed. After bind(mirror, kTitle, VK_NULL_HANDLE), all 16384 words of the "unbound" mirror page still hold the home's words, not zero. The arena view of the same page is correct, and the earlier never-bound guard page does read zero. The device reports residencyNonResidentStrict = true, so the test does not skip.

One variable: the queue the sparse binds run on. Same binary, toggled by environment variables in a local debug build. MEASURED, 3 runs each:

  • Binds on a second queue of the work family (the test's choice: work 0/0, binds 0/1): fails 3/3.
  • Binds on a queue of another family (1/0, compute+transfer+sparse): fails 3/3.
  • Binds on the work queue itself (0/0): passes 3/3.
  • Second queue plus an empty vkQueueSubmit + vkQueueWaitIdle on the bind queue after the unbind: still fails 3/3.

So on this driver, an unbind (memory = VK_NULL_HANDLE) done on one queue is not seen by copies on another queue, even after vkQueueWaitIdle on the bind queue. Binding real memory on the other queue is seen; the first half of the test passes. As far as I read the spec, a host wait should be enough, so this looks like an AMD Windows driver issue. ASSUMED: no RADV or second AMD card here to confirm.

Why it may matter beyond the test. READ IN CODE, not measured: ArenaBacking::reclaim (runtime/src/arena_backing.h around 243-260) unbinds released units on the dedicated bind queue that pick_arena_bind_queue picks, then frees their memory. If the driver keeps the old mapping visible to the work queues, a reclaimed range may keep reading the freed allocation instead of zero. ASSUMED.

Possible ways out. Not tried in the runtime:

  • (a) Issue the unbinds on the queue that reads the range.
  • (b) Rebind released ranges to one shared zero-filled page instead of VK_NULL_HANDLE.
  • (c) At least, have vk_heap_alias skip or downgrade the mirror-unbind check on AMD Windows until a driver fix.

Happy to run any variant on this card.

Not checked by a second agent or human yet. AI-assisted: yes (Claude Code).

@bobcatchris

Copy link
Copy Markdown
Contributor

Native Windows 11 + AMD Radeon RX 7900 XTX 24 GB A/B comparison (main 791899f65 vs PR #2566 eccc71b32), using the identical native wave64 shader pack, copied precompiled <2 MiB compute journal, and recipe (first-run UI / menu, unattended 90 s steady-state runs).

Summary (warm-to-warm, t >= 30 s)

  • Stability: 0 faults, 0 VK_ERROR_DEVICE_LOST, 0 unmet held operations on both A and B.
  • Submissions/s: 60.09 /s (main) → 30.07 /s (#2566) (−50%; direct queue 1,504 → 606 submissions per 10 s).
  • CPU heaps cost: 4.65 ms/sub (~9.30 ms/frame) → 3.79 ms/sub (~3.79 ms/frame) (>2.4× reduction per frame).
  • GPU direct queue: busy 6.5% → 5.5%, max submit-to-done latency 5.8 ms → 2.1 ms (1.8 ms cold).
  • VRAM allocated: 4,982 MiB (main) → 5,157 MiB (#2566, +175 MiB).
RUN WIN-AMD-7900XTX-2566-A | 2026-11-29 05:51 UTC | bobcatchris | AI-assisted: Antigravity (Gemini 4 Neon)
BASE:        791899f65 + 1-line local MSVC 14.39 fix in runtime/src/crt_timed_wait.cpp:26 (_CRTIMP2_PURE _Thrd_result) | shaders: make_game.py --stages shaders --wave64-emulate off (29,280 translated, all spirv-val valid)
MACHINE:     AMD Radeon RX 7900 XTX, 24 GB, desktop | AMD Windows driver 32.0.32029.2010 | Windows 11 Pro 10.0.26200 | 63.7 GB RAM (Ryzen 7 7800X3D)
RECIPE:      documented ("Linux, Wine, AMD RX 7900 XTX (RADV)" adapted to native Windows) + DEVIATIONS: no LEONIDA_TITLE_WATCHDOG_KICK, no LEONIDA_SKIP_COMPUTE, LEONIDA_ASYNC_MIN_BYTES=2097152, LEONIDA_ASYNC_MIN_BYTES_GRAPHICS=0, LEONIDA_COMPILE_THREADS=12, LEONIDA_COMPILE_HEAVY_MAX=10 | precompile: yes, 3,757 compute pipelines (<2 MiB, --max-bytes 2097151, 0 failed)
OS/DRIVER:   Windows default TdrDelay (2 s), Resizable BAR off
TARGET:      A/B control (main) | PREDICTED (written before the run): 30.0 fps, ~60 subs/s, ~4.5 ms/sub heaps, 0 faults
MEASURED:    first-run UI / menu (unattended) | 30.05 fps mean (29.90-30.55) | 60.09 subs/s (1,504 direct/10s) | heaps 4.65 ms/sub, shadows 0.69 ms/sub, geometry 0.14 ms/sub | GPU direct latency 0.74 ms avg (5.8 ms max), 6.5% busy | 4 gfx / 800 compute pipelines live (0.1 s / 0.2 s) | 4,982 MiB VRAM | 0 faults | duration 90 s
END:         time limit (90 s)
CACHES:      warm (session + precompiled compute journal) | RUN 2 of 2 (control A)
INSTRUMENTS: LEONIDA_DEVICE_FAULT=1, LEONIDA_DEVICE_MARKERS=1, LEONIDA_GPU_LATENCY=1, LEONIDA_MEM_PROBE=30, LEONIDA_TITLE_HUD=1
VERDICT:     prediction held (MEASURED, n=2)
RUN WIN-AMD-7900XTX-2566-B1 | 2026-11-29 05:53 UTC | bobcatchris | AI-assisted: Antigravity (Gemini 4 Neon)
BASE:        eccc71b32 (PR #2566) + 1-line local MSVC 14.39 fix in runtime/src/crt_timed_wait.cpp:26 (_CRTIMP2_PURE _Thrd_result) | shaders: same main pack (29,280 translated, all spirv-val valid)
MACHINE:     AMD Radeon RX 7900 XTX, 24 GB, desktop | AMD Windows driver 32.0.32029.2010 | Windows 11 Pro 10.0.26200 | 63.7 GB RAM (Ryzen 7 7800X3D)
RECIPE:      same as A | precompile: copied journal from A (3,757 compute pipelines <2 MiB)
OS/DRIVER:   Windows default TdrDelay (2 s), Resizable BAR off
TARGET:      A/B treatment (PR #2566, cold session) | PREDICTED (written before the run): 30.0 fps, 0 faults, lower CPU heap/submission overhead than A
MEASURED:    first-run UI / menu (unattended) | 30.00 fps mean (29.94-30.06) | 30.03 subs/s (610 direct/10s) | heaps 3.84 ms/sub, shadows 0.71 ms/sub, geometry 0.22 ms/sub | GPU direct latency 0.93 ms avg (1.8 ms max), 5.5% busy | 4 gfx / 800 compute pipelines live (0.1 s / 0.2 s) | 5,161 MiB VRAM | 0 faults | duration 90 s
END:         time limit (90 s)
CACHES:      cold session / copied precompiled compute journal | RUN 1 of 2 (treatment B)
INSTRUMENTS: LEONIDA_DEVICE_FAULT=1, LEONIDA_DEVICE_MARKERS=1, LEONIDA_GPU_LATENCY=1, LEONIDA_MEM_PROBE=30, LEONIDA_TITLE_HUD=1
VERDICT:     prediction held (MEASURED, n=1)
RUN WIN-AMD-7900XTX-2566-B2 | 2026-11-29 05:55 UTC | bobcatchris | AI-assisted: Antigravity (Gemini 4 Neon)
BASE:        eccc71b32 (PR #2566) + 1-line local MSVC 14.39 fix in runtime/src/crt_timed_wait.cpp:26 (_CRTIMP2_PURE _Thrd_result) | shaders: same main pack (29,280 translated, all spirv-val valid)
MACHINE:     AMD Radeon RX 7900 XTX, 24 GB, desktop | AMD Windows driver 32.0.32029.2010 | Windows 11 Pro 10.0.26200 | 63.7 GB RAM (Ryzen 7 7800X3D)
RECIPE:      same as A | precompile: copied journal from A (3,757 compute pipelines <2 MiB)
OS/DRIVER:   Windows default TdrDelay (2 s), Resizable BAR off
TARGET:      A/B treatment (PR #2566, warm session) | PREDICTED (written before the run): matches B1 at 30.0 fps, ~30 subs/s, ~3.8 ms/sub heaps, 0 faults
MEASURED:    first-run UI / menu (unattended) | 30.00 fps mean (29.94-30.07) | 30.07 subs/s (606 direct/10s) | heaps 3.79 ms/sub, shadows 0.69 ms/sub, geometry 0.22 ms/sub | GPU direct latency 0.92 ms avg (2.1 ms max), 5.5% busy | 4 gfx / 800 compute pipelines live (0.0 s / 0.1 s) | 5,157 MiB VRAM | 0 faults | duration 90 s
END:         time limit (90 s)
CACHES:      warm (session + precompiled compute journal) | RUN 2 of 2 (treatment B)
INSTRUMENTS: LEONIDA_DEVICE_FAULT=1, LEONIDA_DEVICE_MARKERS=1, LEONIDA_GPU_LATENCY=1, LEONIDA_MEM_PROBE=30, LEONIDA_TITLE_HUD=1
VERDICT:     prediction held (MEASURED, n=2)

@qhukz13

qhukz13 commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

NVIDIA: why the stack likely does not engage

READ IN CODE at the PR head, nothing run yet. GTX 1050 Ti numbers will follow.

  • Most of the gains sit on the page mirror. create_page_mirror (runtime/shims/d3d12_vulkan_device.cpp:6169-6181) turns it off when no host-visible memory type can back a sparse buffer, or when the arena is one allocation. The arena code in this PR (around d3d12_vulkan_device.cpp:22049) notes that NVIDIA Vulkan restricts sparse buffers to DEVICE_LOCAL-only types, and then falls back to "one allocation, not sparse". INFERENCE: on NVIDIA the mirror is off with "the arena is one allocation".
  • GPU detile reads from the mirror's chunk buffer (vulkan_title_detile.h:4-10, d3d12_title_image_upload.h:116-131), so it goes off with it. So does the in-place heap filtering.
  • Gated by capability as intended, but absent on these cards:
    • FTZ32/fmulz: NVIDIA reports shaderDenormFlushToZeroFloat32 = false, so the pack is built with --no-ftz32;
    • ReBAR (vulkan_memory.h:25): not on Pascal;
    • NonWritable SMEM: a RADV/ACO path.
  • The arena's bind queue is fine on NVIDIA: pick_arena_bind_queue takes a spare queue of a family with sparse binding.

To confirm on any NVIDIA card: the [rt] d3d12: page mirror off: ... line in stderr.

A capability-gated adaptation, nothing keyed on vendor: when no host-visible type can back a sparse buffer, mirror homes go to DEVICE_LOCAL units and dirty pages are copied in from a staging ring before each submission. The existing write-back copy covers the other direction. AMD keeps host-visible homes, so its path and shader pack are unchanged.

AI-assisted (Claude Code).

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

Labels

needs rebase Conflicts with the base branch: rebase it on main

Projects

None yet

Development

Successfully merging this pull request may close these issues.