Skip to content

vulkan_backend: hash the attachment-view cache and index it by image (PERF-VIEW-CACHE) - #8042

Open
TG0000 wants to merge 1 commit into
ItsNotRexed:mainfrom
TG0000:perf/native-core-fast
Open

TG0000 wants to merge 1 commit into
ItsNotRexed:mainfrom
TG0000:perf/native-core-fast

Conversation

@TG0000

@TG0000 TG0000 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Item: PERF-VIEW-CACHE (claimed in #7913)

VulkanContext::view hands the replay a VkImageView for every colour and depth attachment of every draw and clear (vulkan_replay.h calls it through ReplayFunctions::image_view). Two costs, both under views_mutex_:

  • Lookup. The cache was a std::map keyed by a 6-tuple (image, aspect, mip, layer, layer count, format), so each lookup walked a tree of tuple comparisons.
  • Destroy. Removing an image visited every cached view of every image to find its own.

ImageViewCache (runtime/src/image_view_cache.h, standard library only) replaces it:

  • one unordered_map lookup per call;
  • a per-image list of its keys, so erase_image visits only that image's views.

Behaviour does not change: the key fields are the same, the first view made for a key is kept, and destroy releases the same views through defer_destroy. resolve_framebuffers_ and resolve_passes_ are left as they were (rare, small).

Measurements

runtime/test/image_view_cache_test.exe --bench, built with clang 21 (llvm-mingw) at RelWithDebInfo on Windows 11. The numbers are the median of 3 runs, old std::map → new cache:

cached views lookup (random hits) destroy one image allocations in lookup / destroy heap per view
256 images × 2 41.8 → 21.4 ns (2.0x) 2,177 → 320 ns (7x) 0 / 0 both 72 → 165 B
1024 × 4 75.8 → 30.0 ns (2.5x) 26,377 → 699 ns (38x) 0 / 0 both 72 → 155 B
4096 × 4 109.7 → 67.2 ns (1.6x) 162,942 → 564 ns (289x) 0 / 0 both 72 → 155 B
16384 × 2 136.0 → 51.1 ns (2.7x) 283,412 → 615 ns (460x) 0 / 0 both 72 → 166 B
2048 × 32 210.1 → 47.2 ns (4.5x) 674,657 → 3,390 ns (199x) 0 / 0 both 72 → 146 B

The trade-off is memory: about 2.1x the heap per cached view, which is roughly 330 KB more at 4,000 views. These are CPU microbenchmarks of the cache alone. I have no in-game frame-time figure.

Tests

  • New image_view_cache_test (registered in CTest):
    • fixed cases: each key field is significant, the first view wins, destroying an image twice or one with no views, a reused handle, for_each, clear;
    • 200 random sequences of 400 insert/find/destroy operations checked against the old std::map with its linear destroy scan.
  • ctest --test-dir runtime/build -j8 with -DLEONIDA_BUILD_WINDOWS_RUNTIME=OFF: 64 of 65 pass, 2 skipped as usual (shader_library_corpus, vk_sync_validation).
    • The one failure, vk_queue_query_sync, is flaky and not from this change: built from unmodified origin/main it fails 4 of 6 runs; on this branch, 5 of 6.
  • vk_command_replay, vk_queue and replay_cpu_bench_selftest pass.
  • scripts/check_no_game_data.py on the new files and git diff --check: clean.

GPU: NVIDIA (the local Windows 11 machine's driver) for the Vulkan tests in CTest. The change itself is CPU-only.

AI-assisted (Claude Opus 5.5): written and tested by the agent.

🤖 Generated with Claude Code

VulkanContext::view runs for every colour and depth attachment of every
draw and clear the replay records. Its cache was a std::map keyed by a
6-tuple, and destroying an image walked every cached view of every image.
ImageViewCache (runtime/src/image_view_cache.h) makes the lookup one hash
probe and keeps each image's keys, so a destroy visits only its own views.
Same keys, same first-view-wins rule, same views released.

image_view_cache_test checks it against the old std::map on fixed and
random sequences and benchmarks both (1.7-3.6x faster lookups, 8-500x
faster destroys, no allocations on either path, ~155 vs 72 heap bytes per
cached view).

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

Copy link
Copy Markdown
Contributor

Independent Windows 11 MSVC + dual-GPU review of 47ae4c98b5 (PASS, AI-assisted, synthetic tests only, no game data).

Environment

  • OS / Toolchain: Windows 11 x64, MSVC 19.52.37029 (x64, Ninja, full Windows D3D12 runtime ON), CMake 4.3.1-msvc1, Vulkan loader 1.4.363, VK_LOADER_LAYERS_DISABLE=~implicit~.
  • GPU 1: NVIDIA GeForce RTX 3070 Ti (driver 621.24, Vulkan 1.4.357).
  • GPU 2: Intel(R) UHD Graphics 770 (Xe-LP, driver 101.6129, Vulkan 1.3.295).

Build & Code Audit

  • Built cleanly with MSVC (0 new warnings) across image_view_cache_test, vk_command_replay_test, vk_queue_test, d3d12_view_slices_test, d3d12_draw_test, and d3d12_clear_formats_test.
  • Audited runtime/src/image_view_cache.h and runtime/src/vulkan_backend.h:
    • All 6 key fields (image, aspect, mip, layer, layers, format) match the prior std::tuple key and all views_ accesses remain protected under views_mutex_ (or ~VulkanContext).
    • Handle reuse after erase_image works cleanly (by_image_ and views_ stay in sync).
    • Non-blocking note: in ImageViewCache::insert(), by_image_[key.image].push_back(key) runs after views_.try_emplace(key, view), so an OOM exception in push_back could leave an entry in views_ unindexed by by_image_ (negligible in practice since OOM is fatal, just noting for completeness).

Test & Benchmark Results

  • CPU (image_view_cache_test.exe --bench, MSVC): PASS (0 failures, 0 allocations in lookups and destroys):
    • 256 x 2: lookup 36.2 -> 14.6 ns (2.5x), destroy 1,735 -> 135 ns (13x), heap 72 -> 165 B/view
    • 1024 x 4: lookup 56.4 -> 23.8 ns (2.4x), destroy 16,573 -> 182 ns (91x), heap 72 -> 185 B/view
    • 4096 x 4: lookup 72.2 -> 25.9 ns (2.8x), destroy 69,982 -> 243 ns (288x), heap 72 -> 187 B/view
    • 16384 x 2: lookup 92.2 -> 25.1 ns (3.7x), destroy 174,530 -> 296 ns (590x), heap 72 -> 176 B/view
    • 2048 x 32: lookup 119.4 -> 49.0 ns (2.4x), destroy 443,975 -> 1,163 ns (382x), heap 72 -> 217 B/view
  • RTX 3070 Ti (ctest -R "^(image_view_cache|vk_command_replay|vk_queue|d3d12_view_slices|d3d12_draw|d3d12_clear_formats)$"): 6/6 PASS (0 validation errors on vk_command_replay, d3d12_view_slices, d3d12_draw, d3d12_clear_formats with LEONIDA_VK_VALIDATION=1).
  • Intel UHD Graphics 770 (same CTest filter): 5/6 PASS (image_view_cache, vk_command_replay, vk_queue, d3d12_view_slices, d3d12_draw; 0 validation errors under LEONIDA_VK_VALIDATION=1; the only diff in d3d12_clear_formats is the pre-existing Intel 101.6129 sRGB ±1 LSB + depth/stencil rect-clear driver issue addressed separately in vulkan_replay: use cleared aspectMask for depth/stencil rect-clear attachment views #7634).

@pes7

pes7 commented Nov 23, 2026

Copy link
Copy Markdown

Complementary to this, from reading vulkan_backend.h while chasing the per-draw prepare cost: the lookup is not only a std::map with a six-field tuple key, it also takes views_mutex_ on every call, including a pure hit:

VkImageView view(const ResourceBinding& r, const VkImageSubresourceRange& range) {
    std::lock_guard lock(views_mutex_);
    const auto key = std::make_tuple(r.image, range.aspectMask, ...);
    if (const auto it = views_.find(key); it != views_.end()) return it->second;

prepare_draw calls it once per bound render target plus once for depth (vulkan_replay.h), so a frame with 10k draws and 3 targets serialises ~40k lock/unlock pairs through one mutex even when nothing is created. D3D12 lets an app record command lists on several threads, so on a many-core machine that is a scaling wall that hashing alone does not move; std::shared_mutex with a shared lock on hits (a miss takes the exclusive one and re-checks), or a per-thread cache of the last few keys, would take it out.

A measurement note, since it affects how this change can be validated: I tried to confirm the hash-map delta in replay_cpu_bench (which mirrors this cache) and it does not show there — with the handful of view keys that bench has, std::map measured 132-137 ns of prepare for a draw against 155-157 ns for an unordered_map with a six-field hash (3 runs each, same build), i.e. hashing costs more than the search when the table is tiny. Filling the cache first (--views N) is what would make the comparison meaningful; my attempt at that could not be read on a loaded machine, so it is not shipped. If you have a quiet machine and a frame with many distinct views, a number from it would help review this.

@pes7

pes7 commented Nov 23, 2026

Copy link
Copy Markdown

Correction to my earlier note here, because I measured it and the mutex turned out not to be the problem — please ignore that part when reviewing.

I added a threaded mode to replay_cpu_bench on my side (--threads N: N threads record their own lists against one Scene, the view cache modelled exactly as vulkan_backend.h:view() does it, mutex included) and ran the frame workload 1/2/4 threads twice: once with the std::lock_guard, once with that line removed and nothing else changed, same build settings, same machine:

threads with the mutex without it
1 1.00x (1182 ns/command) 1.00x (1094 ns/command)
2 1.84x 1.61x
4 2.74x 2.81x

So the lock costs nothing measurable at 4 threads, and the sublinear scaling (~2.8x on 4 threads) has some other cause. That kills the std::shared_mutex suggestion I made above: the single-mutex-per-lookup pattern is not what limits parallel recording here, at least at this workload and on this machine (which was busy — the absolute numbers are ~2.5x slower than a quiet run, so only the ratios are worth reading).

What is left, and worth measuring before anyone changes that code: with the mutex gone the scaling does not improve, so the limit is elsewhere — allocator contention, the shared Scene lookups the bench does per command, or the bench's own bookkeeping. A profile of the threaded run would say which, and until then I would not touch views_mutex_ for performance.

The threaded mode itself is not in this PR; it needs its determinism story (the self-test asserts on counters that several threads increment) before it is worth carrying.

@eizispark

Copy link
Copy Markdown

Tested 47ae4c9 merged onto main (867d922) on AMD Radeon RX 9070 XT, Adrenalin 26.11.1 (LLPC / Vulkan 1.4.359), Windows 11:

  • cmake --build runtime/build targeted (image_view_cache_test, d3d12_draw_test, d3d12_clear_test, d3d12_depth24_draw_test, d3d12_m2_textured_test, d3d12_present_test, d3d12_translated_draw_test): clean build
  • ctest (image_view_cache, d3d12_clear, d3d12_present, d3d12_translated_draw, d3d12_m2_textured, d3d12_draw, d3d12_depth24_draw): 7/7 passed (14.89 s)

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