Skip to content

Runtime: keep the Vulkan pipeline cache between launches (D3D-704) - #7360

Closed
aslan2142 wants to merge 2 commits into
ProjectLeonida:mainfrom
aslan2142:d3d704-pipeline-cache-persist
Closed

aslan2142 wants to merge 2 commits into
ProjectLeonida:mainfrom
aslan2142:d3d704-pipeline-cache-persist

Conversation

@aslan2142

@aslan2142 aslan2142 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Claimed in the coordination issue as D3D-704: #7231 (comment).

What and why

  • Until now, the device's VkPipelineCache was destroyed at teardown without being saved. A PSO compiled in one session was compiled again in the next.
  • cherryinbubbles-ops reported this in Coordinating who works on what (41) (moved to #7231) #7049 (comment). On an RTX 5050 Laptop, 64 synthetic compute PSOs took 16.67 ms to create with an empty application cache and 1.37 ms with a saved one.
  • With this change, device teardown saves the cache and the next device loads it. This adds to Runtime: use the Vulkan pipeline cache produced by the build (D3D-34) #367's offline seed (pipeline_cache.bin) and does not replace it.
  • The cache is also saved in checkpoints while the device lives. Yoshi-OOF showed on the retail boot stack (Windows, RTX 5070 Ti) that runs can end before device teardown: killed by a debugger, crashed or timed out. A teardown-only save kept nothing from those runs.
  • I wrote this implementation myself. I did not use the patch archive attached to that finding.

Design

  • Where: pipeline_cache_runtime_<vendor>_<device>.bin (hex IDs, e.g. pipeline_cache_runtime_1002_164e.bin).
    • It goes beside the executable, next to the seed. LEONIDA_PIPELINE_CACHE_DIR puts it somewhere else, and a missing folder is created.
    • The vendor and device are in the name so that two GPUs in one machine don't overwrite each other's file.
  • Load (on the first PSO, as before):
    • Each file is used only when its VkPipelineCacheHeaderVersionOne matches this device: headerSize, headerVersion, vendorID, deviceID and pipelineCacheUUID.
    • When both the seed and the saved file match, the saved file is merged into the seed's cache with vkMergePipelineCaches.
    • A truncated, junk, empty or foreign file (another GPU, or another driver's UUID) is logged and skipped. Device creation and PSO creation never fail because of it.
  • Save (in ~Device, after vkDeviceWaitIdle and before vkDestroyPipelineCache):
    • It is skipped when the cache data is header-only (llvmpipe stores nothing).
    • It is also skipped when the vkGetPipelineCacheData size is the same as at the last save, or right after loading. An in-memory cache only grows, so the same size means nothing was added.
    • Otherwise the cache is read with the existing pipeline_cache_snapshot (which handles VK_INCOMPLETE) and written with the existing write_pipeline_cache_file. That writes a temporary file in the same folder and then renames it over the old one.
    • A failed save is logged and leaves the previous file untouched.
  • Checkpoints (while the device lives):
    • One worker thread per device saves the cache through the same temporary-file-and-rename path.
    • It runs only when pipelines were created since its last checkpoint. A counter covers every compute and graphics pipeline created with the cache, including the graphics variants built at draw time.
    • It runs at most once per LEONIDA_PIPELINE_CACHE_CHECKPOINT_S seconds (default 60). 0 turns checkpoints off; teardown still saves.
    • Counting a creation takes a short lock and wakes the worker. Pipeline creation never waits for a write.
    • Only the worker writes. Teardown stops it, waiting for a write in progress, before its own final save, so writes never overlap.
    • vkGetPipelineCacheData runs with no lock while other threads create pipelines. Its pipelineCache is not externally synchronized (spec, "Threading Behavior"; no externsync in vk.xml). vkCreate*Pipelines' pipelineCache is externally synchronized only with VK_PIPELINE_CACHE_CREATE_EXTERNALLY_SYNCHRONIZED_BIT, which this cache does not use.
    • A checkpoint over a cache that did not grow writes nothing. A failed one is tried again an interval later.
    • The first checkpoint is logged, then at most one line per 5 minutes, with the number of checkpoints in between.
  • Opt-out: LEONIDA_PIPELINE_CACHE_PERSIST=0 neither reads nor writes the file, checkpoints included. The seed is still used.
  • Code:
  • Size: the saved file also contains the seed's entries. With a full-corpus seed it is about as large as the seed, and it is rewritten only when pipelines were added. There is no size cap.

Tests

  • pipeline_cache_persist_test needs no GPU and runs on every OS.
    • Header checks: a matching header; a header-only cache; wrong UUID; wrong vendor; wrong device; truncated (31 bytes, empty, null); wrong headerSize or headerVersion; junk.
    • Saves: header-only (no file); grown (whole cache written and readable); unchanged (no write); vkGetPipelineCacheData failing; the snapshot throwing.
    • A failed write keeps the old file byte for byte and leaves no staging file. On Linux the folder is made read-only; on Windows a reader holds the file without FILE_SHARE_DELETE.
    • LEONIDA_PIPELINE_CACHE_CHECKPOINT_S parsing: whole seconds and 0; empty, signed, fractional, non-numeric and over-long values fall back to 60.
    • Rate limit and counter on an injected clock: not due without a creation; due only once the interval has passed; nothing new after a save; a failed checkpoint retried an interval later; never due with 0.
    • Log limiter: the first line, then one per 300 s with the count of skipped checkpoints.
    • The worker on short intervals:
      • no checkpoint without a creation;
      • one checkpoint after creations, then none while nothing new is created;
      • at most one per interval under a steady stream of creations (3 in 1 s at 300 ms);
      • 100 creations during a 300 ms save finish in under 100 ms, and saves never overlap;
      • stop() waits for a save in progress and none starts after it;
      • a checkpoint writes a valid file through the real save path, and one over an unchanged cache writes nothing.
  • d3d12_pipeline_cache_persist_test runs on a device, through the Xbox proxy, with cs_user_data.comp. Each session creates a layer device and a compute PSO, then releases them.
    1. With no file, one is written and its header matches the device.
    2. The next device loads it (saved_bytes equals the file size). The same PSO adds nothing, so the file is not rewritten (same bytes and modification time).
    3. Files from another driver, truncated, junk and empty files are skipped, the PSO is still created, and teardown replaces each with a valid file.
    4. When the save target is a directory, the save fails and is logged. Teardown finishes cleanly and leaves no staging file.
    5. With LEONIDA_PIPELINE_CACHE_PERSIST=0, the file is neither read nor written, also with 1 s checkpoints and the device kept alive for 2.5 s.
    6. With LEONIDA_PIPELINE_CACHE_CHECKPOINT_S=1, a checkpoint writes the file while the device lives. Its header matches, vkCreatePipelineCache takes it on the test's device, and teardown leaves it alone.
    7. The next device loads that checkpoint. The same PSO adds nothing, so one checkpoint runs and writes nothing (same bytes and modification time), and no other runs in the next 2.5 s without a creation.
    8. With LEONIDA_PIPELINE_CACHE_CHECKPOINT_S=0, nothing is written during 2.5 s with the device alive, and teardown still saves.
    • On a driver that stores nothing beyond the header (llvmpipe), the test prints SKIP and returns 77.
  • I checked the seed + saved file merge once with a local variant of the test that put the saved file beside the exe as pipeline_cache.bin. Both loaded (seed 1552 saved 1552), the merge succeeded and the PSO was created. That variant is not committed, because the seed path is fixed beside the executable.
  • Both tests fail on main: the header and pipeline_cache_sources don't exist there, and main writes no file.

GPU and driver

  • RADV, AMD Radeon integrated GPU (gfx1036, RDNA2, 1002:164e), Mesa 26.3.1, under Wine 11.22. The tests were cross-built with mingw-w64 and selected with MESA_VK_DEVICE_SELECT=1002:164e MESA_VK_DEVICE_SELECT_FORCE_DEFAULT_DEVICE=1.
    • d3d12_pipeline_cache_persist_test: passed (1552-byte cache saved, loaded and left unchanged).
    • d3d12_compute_test: passed.
  • Checkpoints, RADV gfx1036 under Wine 11.22, cross-built with clang for mingw and selected with MESA_VK_DEVICE_SELECT=1002:164e!:
    • d3d12_pipeline_cache_persist_test: sessions 1 to 5 passed before the checkpoint commit; all 8 sessions pass after it. The checkpoint wrote 1552 bytes before teardown.
    • pipeline_cache_persist_test: passed before and after.
    • The only validation error was again Wine's own VUID-vkCreateDevice-ppEnabledExtensionNames-01387. No windows were opened.
  • llvmpipe (Mesa 26.3.1, LLVM 23.1.5) under Wine:
    • d3d12_pipeline_cache_persist_test: SKIP, because llvmpipe stores nothing.
    • d3d12_compute_test: passed.
  • Validation: I set VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation on the host, because the layer is not visible to Wine otherwise.
    • The only error was Wine's own VUID-vkCreateDevice-ppEnabledExtensionNames-01387, which every run under Wine shows.
  • Linux native (GCC, Ninja): the full portable runtime build succeeds, and pipeline_cache_persist, pipeline_cache_file and pipeline_cache_snapshot pass in ctest.
    • After the checkpoint commit those three pass again in ctest. pipeline_cache_persist_test is also clean under ThreadSanitizer (clang) and passed 8 repeated runs.
  • Python checks: test_docs_env_vars, test_docs_repeated_lines, test_docs_table_ids and test_build_runtime_cmake pass.
    • test_text_write_line_endings fails on tools/leonida_tui.py and tools/wave_diff.py. This PR doesn't touch them.

Not tested

  • The Windows-native MSVC build (/W4 /permissive-); CI will show it.
  • NVIDIA and Intel drivers, and native Windows file locking in practice. The Windows path of the unit test only ran under Wine.
  • A full-corpus seed merged with a large saved file: load and save times with multi-GiB caches, including how long a checkpoint of a several-hundred-MB cache takes on the worker.

Relation to other work

Checklist

  • No game data: checked. The tests use the synthetic cs_user_data.comp and hand-built FSSM marker words.
  • No keys, decryption or online services.
  • Claimed in the coordination issue (D3D-704).
  • Tests added (pipeline_cache_persist, d3d12_pipeline_cache_persist).
  • Docs updated (docs/d3d12_vulkan.md).

AI-assisted (Claude Code, Claude Opus 5.5).

Device teardown now writes the device's VkPipelineCache to
pipeline_cache_runtime_<vendor>_<device>.bin beside the executable (or in
LEONIDA_PIPELINE_CACHE_DIR), and the next device's first PSO takes it in
under the same header check as ItsNotRexed#367's seed, merged into the seed's cache
with vkMergePipelineCaches.

- The save goes through the pipeline checker's atomic writer (temporary
  file, then rename): a failed save leaves the previous file as it was.
- Nothing is written when the cache did not grow since it was loaded, or
  holds only the header.
- A truncated, foreign or junk file is logged and left out; the device
  starts without it and replaces it at teardown.
- LEONIDA_PIPELINE_CACHE_PERSIST=0 neither reads nor writes the file.

Tests: pipeline_cache_persist_test (header checks, teardown writes, no GPU)
and d3d12_pipeline_cache_persist_test (round trip on a device).

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

Copy link
Copy Markdown
Contributor

Independent Windows + GPU test of 32232957a: pass.

Setup: Windows 11 x64, MSVC 19.44.35220 (RelWithDebInfo, Windows SDK 10.0.26100.0), NVIDIA GeForce RTX 3080 (10de:2206, driver 32.0.16.2124 / 621.24), Vulkan SDK 1.4.363.1, no game files.

  • pipeline_cache_persist_test.exe: PASS (exit 0) — pipeline cache persistence: header checks and teardown writes behave.
  • d3d12_pipeline_cache_persist_test.exe: PASS (exit 0) — all 5 sessions passed on RTX 3080 (saved/loaded 11,882 bytes, invalid/truncated/foreign-driver cache replaced, failed save preserved previous file, LEONIDA_PIPELINE_CACHE_PERSIST=0 opt-out respected).

AI-assisted review/test.

@ciagnij

ciagnij commented Nov 23, 2026

Copy link
Copy Markdown

Independent native Windows check of 3223295 applied to main 1924c8f. Windows 11 Pro build 26300, MSVC 19.44.35223 x64 RelWithDebInfo, Vulkan Headers 1.4.363, glslang 16.6.0. pipeline_cache_file, pipeline_cache_snapshot and pipeline_cache_persist passed, including the Windows locked-file case.

Adapter Driver d3d12_pipeline_cache_persist d3d12_compute
Desktop RTX 5070 Ti NVIDIA 621.14 PASS, saved and reloaded 11,979 bytes PASS
Ryzen 9 9950X3D integrated Radeon Graphics AMD 26.1.1 PASS, saved and reloaded 3,048 bytes PASS

Both devices passed the unchanged-cache, malformed-cache replacement, failed-save and opt-out checks. This was a small synthetic cold/warm round trip, with no full-corpus seed or game files. AI-assisted (Codex).

@Envyre

Envyre commented Nov 23, 2026

Copy link
Copy Markdown

Code read of 3223295 (not run). On the size note in the description (the saved file contains the seed's entries, no cap): one way to avoid the duplicate without a cap is to create new pipelines against a second, empty VkPipelineCache, merge it into the seed's cache for lookups, and save only the second one at teardown, so the runtime file holds just what this machine compiled and a corpus seed is never rewritten. (Merging is one-way, so lookups would need care; a direction, not a drop-in.)

Smaller: d3d12_vulkan_device.cpp now includes runtime/test/pipeline_cache_file.h and pipeline_cache_snapshot.h, so the runtime depends on files in the test folder; moving them to runtime/src would keep that direction clean.

AI-assisted (Claude Code).

@skorex

skorex commented Nov 23, 2026

Copy link
Copy Markdown

Of the three PRs for D3D-704 (#7360, #7384, #7396), this one looks like the one to keep: it is claimed under the D3D-704 ID in #7231, it is mergeable, and it has been checked independently on native Windows + MSVC (RTX 3080, RTX 5070 Ti, AMD iGPU).

Worth porting from #7396 before it lands: the framed/hashed session file, the save gated on creation feedback rather than cache size, and the merge with another session's save. One open point: the saved file includes the seed, so with the 3.8 GB corpus seed every session that adds a pipeline rewrites ~3.8 GB. @Envyre's suggestion above (a second, empty cache saved on its own) would fix that.

@hiddenblur

Copy link
Copy Markdown

Side-by-side check of #7396 (efd81f79d) and #7360 (32232957a), since both serve D3D-704 (and #7384 too, not reviewed here). Windows 11, MSVC (VS 18) via CMake + Ninja, NVIDIA RTX 3080, driver 32.0.16.1088, pinned Vulkan-Headers 6802bb47; no game files.

Tests: #7396 pipeline_cache_store_test, pipeline_cache_file_test and d3d12_pipeline_cache_persist_test pass; #7360 pipeline_cache_persist_test and pipeline_cache_file_test pass. #7360's GPU test isn't built here (no glslangValidator). In #7396's GPU test: 16 PSOs, session 1 with no file 212 ms of creation and 0 hits, session 2 from the saved file 0.69 ms and 16/16 hits, and after two sessions saved in parallel the next one gets 24/24.

Damaged file after a valid header (the case #7360 passes to the driver and #7396's LPCS frame rejects first): a probe made a real 90,684-byte cache from the same 16 no-op SPIR-V shaders, then gave damaged copies with the 32-byte header intact to vkCreatePipelineCache and created the 16 pipelines again. NVIDIA refused 7 of 8 outright, with no crash: truncated to half, last byte cut, only 16 payload bytes, 64 bytes inverted mid-payload or at the start, last quarter zeroed, random payload. It accepted the eighth, one bit flipped near the end, and served 15/16 from it (the damaged entry was recompiled). Same result on two runs. So on NVIDIA the header-only check in #7360 is safe, and #7396's hash is defence in depth; other drivers are untested.

Differences that matter more:

#7396 #7360
integrity frame with byte count and hash, read with ReadFile Vulkan header only, then the driver
two sessions at once merges the other session's save first last writer wins
full ~3.8 GB seed over the 1 GiB cap: saves nothing (logged, LEONIDA_PIPELINE_CACHE_MAX_MB) no cap: rewrites ~3.8 GB after any session that adds a pipeline
build seed paths resolved once, file identity checked, no save if the seed changed separate per-GPU file, never the seed
other tests LEONIDA_PIPELINE_CACHE=off set in CTest leave pipeline_cache_runtime_*.bin in the build folder
headers moves pipeline_cache_file.h / pipeline_cache_snapshot.h to runtime/src includes them from runtime/test

The last-but-one row in both is the open problem: because the cache is saved whole, the seed's entries go into every session file, so with a full-corpus seed one PR saves nothing and the other rewrites gigabytes. Keeping the session's own misses in a small cache of their own (and merging it with the seed at load) would give a file the size of what the session learned.

AI-assisted. Synthetic shaders only, no game files.

@Yoshi-OOF

Copy link
Copy Markdown

Independent Windows 11 / RTX 5070 Ti (621.24) observation on the retail boot stack: the debugger-bounded loading runs can end before device teardown. A local checkpoint of the real runtime cache (not this PR’s teardown code) grew from the 399,382,983-byte build seed to 698,588,474 bytes, with the same Vulkan header identity. A fresh gta6rt.exe process loaded the full checkpoint successfully. This confirms the value of retaining actual runtime-produced cache data for this path; per-pipeline application-cache hits and a visible game frame have not been established by this test. No cache or game data attached.

…(D3D-704)

A run that never reaches device teardown (killed by a debugger, crashed,
timed out) kept nothing with a teardown-only save. Each device now has one
checkpoint worker thread that saves the cache through the same atomic
temporary-file-and-rename path while the device lives.

- A checkpoint runs only when pipelines were created since the last one
  (a counter over every compute and graphics pipeline created with the
  cache, draw-time graphics variants included), and at most once per
  LEONIDA_PIPELINE_CACHE_CHECKPOINT_S seconds (default 60; 0 turns
  checkpoints off, and teardown still saves).
- Counting a creation is a short lock that wakes the worker; creation
  never waits for a write. Only the worker writes; teardown stops it,
  waiting for a write in progress, before its own final save.
- vkGetPipelineCacheData runs on the worker with no lock: its
  pipelineCache is not externally synchronized, and vkCreate*Pipelines'
  is only with VK_PIPELINE_CACHE_CREATE_EXTERNALLY_SYNCHRONIZED_BIT, which
  this cache does not use.
- A checkpoint over a cache that did not grow writes nothing; a failed one
  is tried again an interval later. The first checkpoint is logged, then
  at most one line per 5 minutes.
- LEONIDA_PIPELINE_CACHE_PERSIST=0 turns all of it off.

Tests: pipeline_cache_persist_test (interval parsing, rate limit and
counter on an injected clock, log limiter, the worker on short intervals)
and d3d12_pipeline_cache_persist_test (a checkpoint written and taken by
Vulkan before teardown and loaded by the next device; no write when
nothing new; no checkpoint with 0 or with PERSIST=0).

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

Copy link
Copy Markdown
Contributor Author

Thanks @Yoshi-OOF. Runs that end before device teardown are a gap a teardown-only save can't cover, and your 399 MB → 699 MB checkpoint shows how much those runs lose.

Commit c31c8ca adds checkpoints while the device lives:

  • One worker thread per device saves the VkPipelineCache through the same temporary-file-and-rename path as teardown.
  • It runs only when pipelines were created since the last checkpoint. A counter covers every compute and graphics pipeline created with the cache, including draw-time graphics variants.
  • It runs at most once per LEONIDA_PIPELINE_CACHE_CHECKPOINT_S seconds (default 60). 0 turns checkpoints off; teardown still saves.
  • Pipeline creation never waits for a write: counting a creation is a short lock that wakes the worker.
  • Only one write is ever in flight. Teardown stops the worker, waiting for a write in progress, and then does the final save.
  • vkGetPipelineCacheData needs no lock against concurrent creation: its pipelineCache is not externally synchronized, and this cache is not created with VK_PIPELINE_CACHE_CREATE_EXTERNALLY_SYNCHRONIZED_BIT.
  • A checkpoint over a cache that did not grow writes nothing. A failed one is retried an interval later.
  • The first checkpoint is logged, then at most one line per 5 minutes.
  • LEONIDA_PIPELINE_CACHE_PERSIST=0 still turns everything off, checkpoints included.

Tests (RADV gfx1036 under Wine 11.22, cross-built with clang for mingw, plus Linux native):

  • d3d12_pipeline_cache_persist_test, all 8 sessions pass (5 before this commit):
    • with LEONIDA_PIPELINE_CACHE_CHECKPOINT_S=1, a checkpoint wrote the 1552-byte cache before teardown, vkCreatePipelineCache took it, and the next device loaded it;
    • a checkpoint after a creation that added nothing wrote nothing, and none ran without a creation;
    • with 0, or with LEONIDA_PIPELINE_CACHE_PERSIST=0, nothing was written while the device lived.
  • pipeline_cache_persist_test (no GPU) covers the rate limit and counter on an injected clock, and the worker on short intervals. That includes creations not waiting for a slow save, no overlapping writes, and a failed save being retried. It passes on Linux in ctest, under ThreadSanitizer and under Wine.
  • The validation layer reported only Wine's own VUID-vkCreateDevice-ppEnabledExtensionNames-01387.

Not measured: how long a checkpoint of a several-hundred-MB cache takes on the worker. A run on your setup with the default 60 s would show that.

AI-assisted (Claude Code, Claude Opus 5.5).

@YordiLorenzo

Copy link
Copy Markdown

Tested c31c8ca on RTX 4070 SUPER, NVIDIA 621.01, Windows 11 Pro: pass

  • Build RelWithDebInfo, MSVC + Ninja, Vulkan SDK: ok
  • ctest -R pipeline_cache with LEONIDA_VK_VALIDATION=1: 4 passed
  • d3d12_pipeline_cache_persist -V: session 1 saved 11910 bytes, session 2 loaded them and left the file alone, the checkpoint save before teardown worked too

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.

9 participants