gpu: compile recorded shader programs ahead of their first draw #1311
No reviewers
Labels
No labels
bug
documentation
duplicate
enhancement
GPU
GUI
help wanted
question
Shaders
Video
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/KytyPS5--KytyPS5!1311
Loading…
Reference in a new issue
No description provided.
Delete branch "gh-pr/1311/head"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
@NeySlim on GitHub · 2026-10-09 15:27 UTC · original
NeySlim:perf/shader-cache-ahead→main· +1782 −72 · 10 files · 8 commits · closed without mergingProblem
Kyty translates each new guest shader to SPIR-V on the GPU command thread when a draw or dispatch first uses it, and none of this work survives the run. In God of War Ragnarök (PPSA08332), a new game compiles about 1,900 shader programs in its first 12 minutes. Even in a second run of the same build, with the driver caches warm, the GPU command thread still spends 30 s on them (
TranslateProgram25.1 s,CompileProgram5.1 s), in stalls of up to 1.6 s per frame in gameplay. The Vulkan pipeline cache only covers the driver part.Change
_PipelineCache/<title>.shaders.binat exit and at most every 60 s while new programs appear, through a uniquely named temporary file and an atomic rename (concurrent instances never mix their data), with a checksum per record (a damaged tail is dropped). The file is tied to the device and driver, and toKYTY_GRAPHICS_CACHE_VERSION: a hash of the sources undersrc/graphics(paths and contents), the compiler identity and the build type, computed bygenerate_version.cmakeat each build into the generatedkytyShaderCacheVersion.h, because the recorded inputs are derived by code across the graphics tree. Since the key comes from the sources, this cache also works in builds from a modified tree. The Vulkan pipeline cache key is left as it is on main.AgcCreateShader), its recorded programs are queued to worker threads (a quarter of the hardware threads, 1 to 8). A worker translates, emits the SPIR-V and creates the shader module from the recorded inputs, with the same compile options as the command thread.Test
ShaderCacheFileFormat: round trip, other signature, truncated record, damaged record.ShaderCachePersistence: a first cache compiles a compute program with a buffer specialization and saves it; a second cache reloads the record, compiles it on a worker when the shader is mapped, and its lookup adopts it without compiling (same program info, pipeline created); a record still pending is compiled once by the caller; a file with another signature is ignored.ShaderCacheGraphicsPrograms: the same for a vertex and a pixel program of one draw.ShaderCacheRecordPadding: equal fields give identical records whatever the padding bytes of the input info and the resource specialization hold (records are written field by field).ShaderCacheConcurrentWaiters: a recorded program that the lookup thread compiles itself is in flight until it ends, and a concurrent waiter wakes only after it; a lookup from a second thread is refused (ShaderCacheLookupThread).ShaderCacheRecordPaddingalso checks that the queue of an async compute program (read by GETREG) survives the record with the same program key.ShaderCacheSwappcRecord: a recorded SWAPPC program is not compiled ahead from its own code.ShaderCachePersistencealso checks that a second cache created and destroyed meanwhile does not remove the first cache's shader map observer.They run with
--pipeline-cache-only(ctestpipeline_cache) and in the full run, and are skipped in non-Release builds. They fail without the adoption ("the lookup compiled the program again") and without the recording ("the recorded program was not reloaded").Validation
Linux, Ryzen AI Max+ 395, Radeon 8060S, Mesa RADV 26.2.3. God of War Ragnarök, new game, two runs in a row per build, Mesa disk cache emptied before the first run of each build, GPU clock forced high. The second runs compare as follows (T0: gameplay reached; the runs do not reach exactly the same content):
The 1,927 recorded programs are compiled on the workers while the game boots: 42 s of CPU time on one thread (measured offline), 16 s of it captured on the workers before the first gameplay frame of a third run. In that third run, with the GPU clock governor left alone, the clock stayed between 2.1 and 2.3 GHz (10th percentile and median) through the cutscene and gameplay; in an earlier profile of a run without this cache on the same machine, compilation bursts had held it at 600 MHz for up to 80 s.
The measured builds also kept the Vulkan pipeline cache across rebuilds (a separate change, not part of this PR); within a second run of the same build that makes no difference, the driver cache is warm in both columns.
First runs are unchanged: with empty driver caches the command thread spends 184 to 191 s compiling, 157 s of it in the driver.
shader_recompiler_compute_tests, one case per process: same results asorigin/main(627 of 637 cases pass on both; the same 10 fail on this RADV setup).pipeline_cache,resource_trackingandresource_materializationpass.Not tested on Windows or macOS. The workers use
std::jthreadand astd::condition_variablelike the existing GPU threads; the cache file is replaced withstd::filesystem::rename, which replaces an existing file on Windows too, and Kyty opens files with delete sharing on Windows.Related
#988 stores the recompiler output (plans and SPIR-V) on disk. This PR stores only the inputs and compiles them again with the running build, so a record is only used when it gives the program key of the draw, like a program compiled earlier in the same run.
AI use
I used Claude Code (AI agent) to profile the compilation, design and write the change and the tests, and run the measurements and tests above on my machine. I reviewed the diff and the results; the agent then separated this change from the pipeline cache one and ran the tests above again.
@coderabbitai[bot] on GitHub · 2026-10-09 15:30 UTC · original · edited 2026-10-21 23:04 UTC
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
d4e48d0c-c935-4586-abce-6027b57b4580📥 Commits
Reviewing files that changed from the base of the PR and between 508fe10cb61cf0bc2eceeb14dd70f6bbac2fd596 and 5447e4da636a0f05819be084aa340b126ee08bd1.
📒 Files selected for processing: 3
CMakeLists.txtsrc/graphics/host_gpu/renderer/pipeline/pipelineCache.cpptests/ShaderRecompilerComputeTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review.
📝 Walkthrough
The change adds a versioned, persistent shader-recipe cache alongside the Vulkan driver cache. It records compiled shader programs, queues cached recipes after shader mapping, and supports background compilation and program adoption. The cache format validates signatures, record hashes, and payload data. Build configuration generates a graphics cache version, and tests cover cache parsing, persistence, and background compilation.
Suggested reviewers:
jeanpaul87Priority: ➖ Normal
Change: Feature
Merge Risk: ⚪ Minimal · up to
5447eThis change adds a persistent shader cache that compiles recorded programs in the background before their first draw. No concrete merge-blocking defect remains in the reviewed changes, and the reported cache and GPU test results match main.
Pre-merge checks:
4 ·
1
Full details: Docstring Coverage
Explanation
Docstring coverage is 12.82% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 78 functions across 6 files. (2 skipped: 1 unsupported, 1 too large.)
Resolution
Write docstrings for the functions missing them to satisfy the coverage threshold.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share
Comment
@coderabbitai helpto get the list of available commands.@jeanpaul87 on GitHub · 2026-10-09 15:46 UTC · original · edited 2026-10-09 15:48 UTC
On
src/graphics/host_gpu/renderer/pipeline/pipelineCache.cppline 613 (outdated):Could copying the whole struct here accidentally include uninitialized padding bytes? I'm wondering if that might cause the hash to change for identical inputs. Should we zero it out with memset before copying the data?
@jeanpaul87 on GitHub · 2026-10-09 15:47 UTC · original
On
src/graphics/host_gpu/renderer/pipeline/pipelineCache.cppline 760 (outdated):If we have two ProgramCache instances alive at the same time (like in the tests), won't destroying one accidentally clear the observer for the other? Should we maybe check if this instance actually owns the observer before setting it to null?
@jeanpaul87 on GitHub · 2026-10-09 15:48 UTC · original · approved these changes
@ -349,3 +436,3 @@lookup_key.code_size = static_cast<uint32_t>(params.code.size());BuildStageStaticKey(input_info, lookup_key.static_state);auto entry = programs.find(lookup_key);auto entry = programs.find(lookup_key);@jeanpaul87 on GitHub · 2026-10-09 15:52 UTC · original
I noticed we read from and write to the programs map (.find() in Get and .emplace() in Adopt) without holding any mutex. Since standard unordered_map isn't thread-safe, if multiple GPU threads call this at the same time, won't this corrupt the map and crash the emulator? Should we add a dedicated lock around programs?
@ -483,0 +584,4 @@lock.unlock();result = CompileJob(job.recipes, hook);lock.lock();stats.compiled += result ? result->permutations.size() : 0;@jeanpaul87 on GitHub · 2026-10-09 15:52 UTC · original
If a thread steals a queued job to compile it directly here, it breaks out of the switch and immediately sets the state to Taken. Since it completely skips setting the state to Done and never calls job_done.notify_all(), won't any other threads currently stuck in WaitForJob sleep forever and cause a deadlock?
@jeanpaul87 on GitHub · 2026-10-09 15:53 UTC · original · requested changes
@NeySlim on GitHub · 2026-10-09 16:25 UTC · original
On
src/graphics/host_gpu/renderer/pipeline/pipelineCache.cppline 613 (outdated):Thanks, good catch. The program key itself was built from the fields (
BuildStageStaticKey), not from these bytes, but the padding did reach the file and the per-record checksum: identical inputs could give different bytes, and leftover stack data was written to disk. Fixed in e1e1997c04: the stage input info and the resource specialization are now written field by field (bools as one byte, enums as their underlying type), so no padding or runtime pointers are stored, and decoding rejects a size mismatch or an invalid bool. The newShaderCacheRecordPaddingtest builds each structure over memory filled with two different patterns and checks that the records are identical; it fails with the oldmemcpy.@NeySlim on GitHub · 2026-10-09 16:25 UTC · original
On
src/graphics/host_gpu/renderer/pipeline/pipelineCache.cppline 760 (outdated):Thanks, you're right, and a compare-and-clear alone would not have been enough: the second cache's
Loadalso replaced the first cache's observer. Fixed in e1e1997c04: the shader map now keeps a list of observers; each cache adds itself inLoadand removes only its own entry in its destructor (under the observer mutex, so a running notification ends first).ShaderCachePersistencenow creates and destroys a second cache while the first one is alive, then maps the shader and checks that the first cache still compiles its recorded program; this fails with the single observer.@ -349,3 +436,3 @@lookup_key.code_size = static_cast<uint32_t>(params.code.size());BuildStageStaticKey(input_info, lookup_key.static_state);auto entry = programs.find(lookup_key);auto entry = programs.find(lookup_key);@NeySlim on GitHub · 2026-10-09 16:25 UTC · original
Thanks for checking this.
GetandAdoptonly run on the thread that looks programs up, the GPU thread:GuestGpu::ThreadRunprocesses the graphics queue and all compute queues on that one thread, andGetGraphicsPrograms/GetComputeProgramare only called fromRenderExecutorthere. That was already the contract on main (programsand thelookup_keyscratch member had no lock before this PR). The workers never touchprograms: they only read recipes and store job results underjob_mutex, and the lookup thread moves a result intoprogramsitself. To make this explicit, e1e1997c04 adds a check: the first thread that looks up a program owns the cache, and a lookup from any other thread exits with an error (tested byShaderCacheLookupThread).@ -483,0 +584,4 @@lock.unlock();result = CompileJob(job.recipes, hook);lock.lock();stats.compiled += result ? result->permutations.size() : 0;@NeySlim on GitHub · 2026-10-09 16:25 UTC · original
Thanks, good point. With a single lookup thread, no other thread can wait in
WaitForJobon a job that this thread took, but the state handling was still inconsistent: the taken job was not counted as running, soWaitForBackgroundCompilationcould return while it was still compiling. Fixed in e1e1997c04: a job compiled by the lookup thread now goes through Running and Done like a worker job (running count,job_done.notify_all()) before it is adopted (Taken);WaitForJobwakes on any state other than Running; at shutdown, jobs that never started go back to Dormant and waiters are woken. The newShaderCacheConcurrentWaiterstest holds that compilation in a hook (semaphores, no sleeps), checks that it is in flight, and checks that a concurrentWaitForBackgroundCompilationreturns only after it ended; it fails without the change.@NeySlim on GitHub · 2026-10-09 16:26 UTC · original
@jeanpaul87 thanks a lot for the review! All four points are addressed in e1e1997c04, with a test for each (details in the threads). Could you take another look when you have time?
@ -43537,0 +43908,4 @@seen_by_waiter = cache.GetProgramStats().compiled;});waiting.acquire();release.release();@coderabbitai[bot] on GitHub · 2026-10-09 16:32 UTC · original · edited 2026-10-09 16:49 UTC
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 3478
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 7496
Synchronize with the actual background wait before releasing compilation.
The proposed
waiter_startedsignal would still occur beforecache.WaitForBackgroundCompilation(). The waiter can be descheduled after that signal, so!waiter_returned.try_acquire()can pass before the waiter reachesjob_done.wait. Add a test-only synchronization point around the actual blocking wait. Release compilation only after that point confirms that the waiter is blocked, then join both threads and check the final count.✅ Confirmed as addressed by @NeySlim
@coderabbitai[bot] on GitHub · 2026-10-09 16:32 UTC · original · reviewed
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
bf18b76f-6b80-4d86-a014-83d1e834e36c📥 Commits
Reviewing files that changed from the base of the PR and between 4972f8e048cbf2bf0d7d9ba8563b474e68458ec9 and e1e1997c04ff437963f2757e43ffe821bccff27e.
📒 Files selected for processing (7)
src/graphics/host_gpu/renderer/pipeline/pipelineCache.cppsrc/graphics/host_gpu/renderer/pipeline/pipelineCache.hsrc/graphics/host_gpu/renderer/pipeline/shaderCacheFile.cppsrc/graphics/host_gpu/renderer/pipeline/shaderCacheFile.hsrc/graphics/shader/shader.cppsrc/graphics/shader/shader.htests/ShaderRecompilerComputeTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review.
@ -43537,0 +43908,4 @@seen_by_waiter = cache.GetProgramStats().compiled;});waiting.acquire();release.release();@NeySlim on GitHub · 2026-10-09 16:49 UTC · original
Good point, thanks. Fixed in 37d846135d:
PipelineCache::SetBackgroundWaitHookadds a test-only hook thatWaitForBackgroundCompilationcalls underjob_mutexright beforejob_done.wait, telling whether it is about to block (nothing runs when the hook is unset). The test releases the compilation only after this hook has run, so the compilation can end only once the waiter is blocked in the wait, and it checks that the waiter did block. With the old handling of a job taken by the lookup thread, the test now fails at "waiter blocked".@ -43537,0 +43908,4 @@seen_by_waiter = cache.GetProgramStats().compiled;});waiting.acquire();release.release();@coderabbitai[bot] on GitHub · 2026-10-09 16:49 UTC · original
@NeySlim, thanks for fixing this. Calling the hook underjob_mutexbeforejob_done.waitcloses the scheduling gap. The"waiter blocked"check also tests the failure case identified in this finding.If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
✅ Review thread resolved.
You are interacting with an AI system.
@NeySlim on GitHub · 2026-10-09 19:03 UTC · original
Rebased on main after the SWAPPC linking (
1818aae5,3e9f88bf), the GETREG queue fields (bb5edbd4) and the inline sampler planning (8c813865). I checked every input these add to program translation against the record (new commit b73560ff):async_compute(GETREG queue fields) is a new compute input field. It is part of the program key, but the field-by-field record missed it: a recorded async program would have been compiled on a worker as graphics compute. It is now recorded;ShaderCacheRecordPaddingchecks it survives with the same key.RefreshShaderSource), which the record does not hold. Such programs are no longer recorded, and a worker refuses a recorded one instead of translating its code alone; the draw compiles it as before. New testShaderCacheSwappcRecord.973809cd,5b68a26c,3b1a9470,488c0aca) are derived from the guest code and the resource specialization, both already recorded.Mutation checks redone (adoption, recording, async field, SWAPPC guard, stolen job, waiter hook, lookup thread, observer scope): each fails or hangs its test.
pipeline_cache,resource_tracking,resource_materializationpass; GPU suite one case per process: 602 of 612 on both this branch and main. Body updated.@NeySlim on GitHub · 2026-10-13 22:35 UTC · original
Rebased on main. Programs compiled ahead now take maintenance8_enabled from the device like the draw path (
460a196f), so recorded shaders with dynamic sample offsets get the same SPIR-V and validation. GPU suite unchanged vs main (627/637, same 10 failures here).Pull request closed