perf(agc): reuse cached draw stages when only buffer base addresses moved #5609
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/5609"
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?
Imported from boykopovar/AnyPS5. Originally posted by TheAggie on 2026-10-14T01:02:29Z.
What
Second step for #4054, stacked on #4943. That PR finds a cached draw when the user-data pointers moved and the data behind them is equal. A guest driver that keeps its buffer descriptors in a table reached through such a pointer (RADV's descriptor sets) still missed on every draw whose buffers moved, because the descriptor's base address is among the words a stage is validated against.
bufferBaseSlotsfield of a result, and its Linux-only size asserts expect the grown structs.AnyPendingOverlapsconsults the pending image range index first. The state the filter compares against is kept per command buffer, in the recorder batch's open render pass: it is reset when a new pass starts and marked unknown after the back-face and second-channel splits and after stencil replay (which sets the stencil reference itself).APS5_VERIFY_DRAW_DATA_HITS=1) is left to that verification instead of being reused.APS5_NO_DRAW_RELOCATION=1turns the relocation off,APS5_NO_DRAW_STATE_FILTER=1the dynamic state filter.Only the commits after #4943's head are this PR.
Tested
Windows 11, NVIDIA GeForce RTX 5070 Ti, MinGW-w64 GCC 15.2.0, rebased on main
940eba9a2.ctest: 1270 of 1292 pass, 14 skipped.guest_call_trace_abort,windows_backtrace_reportandagc_driver_store_over_untrackedfail, and fail the same way on plain main here.agc_driver_prepared_shaders_debugfailed once in a parallel run and passes alone. Three newer tests,agc_driver_prepared_graphics_prebuild_0/_1andundeliverable_host_exception, fail under my test runner because it skips their environment changes and pass pattern; run with those, all three pass.ShaderDiskCache.cpponly compile on Linux. I have no Linux build; I compiled the structs under MinGW libstdc++ on x86_64, where all asserted sizes match.agc_shader_disk_cache's result round trip now also sets and comparesbufferBaseSlots.agc_driver_draw_cache_moved_buffer: a pixel shader loads a buffer descriptor through a user-data pointer and reads its colour from that buffer. Once the draw has been seen twice, drawing it again with the descriptor's base changed, with the same or other contents, hits the cached draw. It fails withAPS5_NO_DRAW_RELOCATION=1.main940eba9a2, this PR and #4943 against the same build without them (both with the same local changes the frontend needs to boot, immediate present, audio muted, three alternating unprofiled runs): audio produced at 34.5%, 35.7% and 35.6% of real time without, against 45.7%, 44.1% and 42.8% with.4430780bd(without #5216) plus local changes outside this PR that the frontend needs to boot. #4943 alone against #4943 plus this PR, same local base, one thread,ANYPS5_PRESENT_MODE=immediate, two unprofiled runs each: audio produced at 43.6% and 43.4% of real time against 57.6% and 57.9%. One profiled run each: queue worker 41.5 µs against 30.7 µs per draw packet; stage captures per 10 s 92,728 in 185,141 draws against 14,859 in 238,439; draws with every stage reused 75% against 96.8%.APS5_VERIFY_DRAW_ENTRIES=1, which captures every hit again and compares: 0 stages differed in every report (118,722 hits in the largest).Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed in TechnicalDebt.mdfiles or images added to the repository (attach them to this PR)🤖 Generated with Claude Code
Imported from boykopovar/AnyPS5. Originally posted by CnRJay on 2026-10-14T02:10:03Z.
Review: COMMENTED
Per-stage relocation is a sensible next step after #4943. The verify mode (
APS5_VERIFY_DRAW_ENTRIES=1, 0 differing stages) is good evidence for the demo. I found two correctness gaps that the demo probably doesn't reach, and one gap in the evidence.1. The content hash stops at 64 words of each read. In
relocatedContentKey, each(offset, words)read is hashed ascount = std::min<std::size_t>(words, MaxContentWords).wordsis the length of a run thatlearnPendingRelocationderives fromvariant.runs, which follow the captured regions. A descriptor table reached through a relocatable base can easily be longer than 64 dwords; eight 8-dword T#s are already 64. Words past the first 64 are then never compared. A table that moved, with the same first 64 words and different descriptors after them, produces the same alias key and reuses the donor stage with stale descriptors. Either hash the whole run (in chunks ofMaxContentWords), or ban the register inlearnPendingRelocationwhen a run is longer than the limit, so such a stage stays on the capture path.2.
RecordedDrawStateis one process-wide object with no lock.recordedDrawState()returns a function-local static thatapplyandsetLibraryStateread and write without synchronization. Therecorded.commands == commandscheck only protects against a different command buffer when two command buffers are recorded one after the other. Suppose two queue workers record concurrently (the measurements say "one thread", so I assume multi-threaded recording is a supported mode). Thread A checks thatrecorded.commandsis its own buffer, thread B then stores its own viewport and stencil values, and A compares its new values against B's. A then skips avkCmdSet*whose value differs from what A's command buffer actually holds, so state set for one queue's draws leaks into another's. Keeping this state per command buffer (in the recorder's batch, next tocommands) avoids both the race and the handle comparison.thread_localwould also work if a command buffer is only ever recorded on one thread. Besides that, the filter looks right:Beginre-applies everything withknown = false, and the two other graphics binds resetrecorded.commands.3. The
MaxAliaseslimit clears both maps outright.drawStageDonors.clear()/drawDecodes.clear()at 16384 entries means a title that crosses the limit loses every donor at once. For several frames, every moved draw then goes back to full capture. That is exactly the stall pattern this PR is trying to remove, and it would show up as a periodic hitch rather than a lower average. An LRU, or evicting the oldest half, keeps the steady state. At least a counter in the profile output would make the cliff visible.Evidence:
aps5-summary.jsonllines plus traces captured with noAPS5_PROFILE_*switch that the Performance report form asks for.The summary lines of #4943 alone and of #4943 + this PR, on the same machine, would make the claim checkable. So would a run on a second title that doesn't use a RADV-style descriptor-set layout, which would show that the extra per-draw content hashing (
CopyMappedplus the hash of every relocatable read) costs nothing where relocation never hits.Also, since only the commits after #4943's head belong to this PR,
Depends on: #4943should be filled in the checklist, if it isn't already.Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-14T10:41:07Z.
Review: CHANGES_REQUESTED
Reviewed against the diff; two correctness problems, and the PR still needs a rebase once #4943 lands.
DrawRelocate.cpprelocatedContentKey: each read is hashed asmin(words, MaxContentWords)(64). A descriptor table longer than 64 dwords that moved, with the same first 64 words and different descriptors after them, gets the same alias key and reuses the donor stage with stale descriptors. Hash the whole run in chunks, or stop treating the register as relocatable inlearnPendingRelocationwhen a run is longer than the limit.Pipeline.cpprecordedDrawState(): a function-local static with no lock, read and written byapply/setLibraryState. With two queue workers recording, therecorded.commands == commandscheck does not stop one worker comparing against the other's viewport/stencil values and skipping avkCmdSet*its command buffer needs. Keep this state per command buffer (next tocommandsin the recorder's batch) or make itthread_localif recording is single-threaded; please say which holds.MaxAliases:drawStageDonors.clear()/drawDecodes.clear()at 16384 drops every donor at once, so every moved draw goes back to full capture for a while. Evict the oldest part instead, or at least count it in the profile output.aps5-summary.jsonllines of #4943 alone vs #4943 + this PR, plus one title without a RADV-style descriptor layout showing the extra hashing costs nothing, would make it checkable.Welcome back once these are addressed.
Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-14T13:04:26Z.
Review: CHANGES_REQUESTED
Thanks for the update. The 64-word hash and the all-at-once eviction are fixed (chunked hashing,
dropEveryOtherwith theevictedcounter). One point from the last review is still open:Pipeline.cpp:690recordedDrawState()is still a function-localstaticwith no lock. With two queue workers recording, therecorded.commands == commandscheck does not stop one worker comparing against the other's viewport/stencil values and skipping avkCmdSet*its own command buffer needs. Keep the state per command buffer (next tocommandsin the recorder's batch), or make itthread_localif recording is single-threaded; please say which one holds.Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-14T13:18:44Z.
Review: CHANGES_REQUESTED
Thanks for the rebase. The 64-word hash and eviction fixes are in; one point from the last review is still open:
Pipeline.cpp:690recordedDrawState()is still a function-localstaticwith no lock. With two queue workers recording,recorded.commands == commandsdoes not stop one worker comparing against the other's viewport/stencil values and skipping avkCmdSet*its own command buffer needs (and the writes race). Keep the state per command buffer (next tocommandsin the recorder's batch), or make itthread_localif recording is single-threaded; please say which one holds.Imported from boykopovar/AnyPS5. Originally posted by TheAggie on 2026-10-14T13:30:06Z.
@CnRJay thanks for the review. Rebased onto
main7181fe94d(on top of #4943's new head) and force-pushed.Content key cut off at 64 words. Fixed: a read is now hashed whole, 64 words at a time, with its offset and length mixed in. For the record, a cut-off key could not make a stale stage be reused, because a candidate is still compared word by word before it is taken; what it cost was two different buffers sharing a key and pushing each other out.
RecordedDrawStateis process-wide and unlocked. Not changed in this push. Recording into a command buffer already happens under the GPU mutex, so the state is not touched by two threads at once.thread_localwould be wrong here: the queue worker and the committer record into the same command buffer in turn, and the filter has to see what the other one set. If you would rather not rely on that, I can move the state into the recorder object so its lifetime and its lock are the recorder's.Clearing a whole map at the limit. Fixed: at the limit every other entry is dropped instead of all of them, for the stage donors and the decodes here and the aliases in #4943, and the
[draw-relocate]line reports how many were dropped.Evidence. Unprofiled captures with
APS5_TRACE_SECONDS=60:30, Crazy Taxi attract demo in RetroArch/Flycast,ANYPS5_PRESENT_MODE=immediate, same machine, runs alternated. Base ismaina14ae8e23plus the local changes the frontend needs to boot (not in either PR). Fromaps5-summary.jsonl:I will be plain about the middle row: on current
main#4943 alone does not move this workload. A profiled run shows it hits about 40% of draws, but on this base almost every draw copies a whole 2 MiB guest buffer into a snapshot (about 12,500 copies and 16 GB a second), and a cache hit still makes that copy. This PR reuses the snapshot when nothing wrote between draws (e92089d9f) and turns most draws into hits that skip the stage captures. I have not measured those two apart, so I can't say how the gain splits between them. The 27% to 38% in #4943's description is from the older base and says so; I will add this result there too.I have not yet run a title that does not go through RADV; none of my test titles uses Sony's own graphics driver, so that part is still owed.
The dependency is unchanged: this PR depends on #4943, and only the commits after that PR's head belong to it.
This push also fixes the Linux build that @Raghav314 reported on #4943: the size asserts in
ShaderDiskCache.cppand the result encoder now coverbufferBaseSlots.AI-assisted (Claude Code).
Imported from boykopovar/AnyPS5. Originally posted by TheAggie on 2026-10-14T15:36:44Z.
Restructured, no change in behaviour: the commit that reuses draw snapshots across draws nothing wrote between is now its own PR, #5906. It helps every Windows title, not only the relocation path here. On
mainalone it takes the Crazy Taxi demo from 5.8% to about 26.5% of real time, since on Windows each draw otherwise copies a 2 MiB buffer that is almost always unchanged.This branch now carries #5906's two commits under its own, so it depends on #4943 and #5906. Since #5906 went up separately it has a gentler eviction (every other entry at the limit), a recorder-level test, and the debt line for #1441 updated. All three are in this branch too. Both branches are rebased onto
main84b01f9cd.AI-assisted (Claude Code).
Imported from boykopovar/AnyPS5. Originally posted by mrfelek on 2026-10-14T16:13:09Z.
Data point from a title whose buffer base addresses move on every draw. Diablo II: Resurrected (PPSA03912, 01.039.000), Linux, RTX 3080 Ti (NVIDIA 615.71.09), in game (Rogue Encampment). Build:
main84b01f9cdplus #1186 (A). B = A plus #4943 (head 1c72efdc9) and this PR (head d6abd5555), before the split into #5906; C = A plus #4943 only. Three alternating runs of each, presents per 10 s: A 39.7 / 41.0 / 39.1; B 33.3 (a startup dip in its first window) / 40.0 / 39.7; C 39.4 / 40.3 / 39.3. This PR adds nothing measurable on top of #4943 here, and the draw-cache hits per 10 s are about 201 for B against about 377 for A and about 220 for C.What changes per draw on this title: one stage's user-data word 0x090 changes on essentially every draw (59,959 of 60,000), and that stage holds inline V#s (base, stride and count, format) whose bases advance by a fixed step: word 0x08c over four consecutive draws is
5b199b00,5b19a000,5b19a500,5b19aa00(step 0x500). So the base addresses do move, which is the case this PR targets, yet the hit rate does not rise. If it helps to know why, I can trace one draw's stage match and report where it falls out.AI-assisted; the runs are from my machine.
Imported from boykopovar/AnyPS5. Originally posted by CnRJay on 2026-10-14T19:11:49Z.
Thanks. I checked:
Recorder::Commandsasserts the GPU mutex, so recording is serialized and the static isn't raced in practice. You're also right that the worker and the committer share a command buffer, which rules outthread_local. Nothing inPipelinestates that, though. AGuestMemory::AssertGpuLockHeld("Pipeline::apply")inrecordedDrawState()would pin it, and it costs nothing unlessAPS5_ASSERT_GPU_LOCKis set. Moving the state into the recorder, as you offered, works too. I'll leave that choice to @adriadam10.Imported from boykopovar/AnyPS5. Originally posted by JAB-dev on 2026-10-14T22:23:22Z.
Besiege (PPSA20313),
mainat7003eda5dplus the draft that imports resident direct memory through a section alias on Windows, with and without this PR (bf7ad5679, merged onto that main), Windows 11, RTX 4070 SUPER, 1080p: title screen 21.5 / 21.3 -> 19.8 / 21.1 FPS (no change). Draw-cache lookups per 10 s with this PR: about 94,000, of which about 87,700 find no entry and about 4,250 hit, the same as without it.Imported from boykopovar/AnyPS5. Originally posted by TheAggie on 2026-10-15T16:10:01Z.
@adriadam10 @CnRJay on the
recordedDrawStatestatic: it is now per command buffer, stored in the recorder's batch.PassDrawStatelives in the batch's open render pass (Batch::RenderPass). It is reset wheneverStartDrawPassstarts a new pass, and handed to the draw throughDrawPassStart.Pipeline::Begin/Continuetake a pointer to it. The one-off draw path that records its own command buffer passes none, so nothing is filtered there. No state is shared between threads or between command buffers.While moving it I found one more case the old filter got wrong: stencil replay sets the stencil reference with
vkCmdSetStencilReferencedirectly, behind the filter's back, so a following draw in the same pass could skip a reference it needed. The state is now marked unknown after a replay, the same as after the back-face and second-channel splits.The rebase also needed a fix for upstream's stage-data hits: with
APS5_VERIFY_DRAW_DATA_HITS=1our per-stage reuse took the stage before it could be verified (agc_driver_draw_cache_reuse_verifycaught it). Such stages are now left to the verification.AI-assisted (Claude Code)
Imported from boykopovar/AnyPS5. Originally posted by CnRJay on 2026-10-15T18:20:51Z.
Thanks. Per command buffer, inside the batch's render pass, is the right home for it, and it removes the question of which thread records. The stencil replay that bypassed the filter is a good catch.
Two data points so far show no gain from this PR on top of #4943: @mrfelek's Diablo II (hits went down) and @JAB-dev's Besiege (87,700 of 94,000 lookups still miss). Both titles still pay the per-draw content hashing of relocatable reads. If the alias path never hits in a title, that hashing is pure overhead. Counting the hashed bytes per draw on the
[draw-relocate]line, next to the hits, would show what it costs in those titles.Imported from boykopovar/AnyPS5. Originally posted by JJenkx on 2026-10-18T06:19:51Z.
I integrated the eight commits through
09238da820onto mainccb0c092683alocally and found two compatibility issues in the regression tests:agc_driver_draw_cache_moved_bufferrendered the moved buffer correctly but reported zero cache hits. It passed withAPS5_NO_SRT_TAPE=1. Main's SRT tape path did not populate the newreadInstructions,operandReads, orsourceLeadsmetadata. The tape also needs to retain operand nesting through invariant phi, read-first-lane, and extracted composite values, and roll metadata back when it falls back to the interpreter.agc_driver_mesh_draw_relocationreported four differing-front-stage misses.cloneVariant()did not copy themeshIndexDescriptoradded on main. Copying it fixes that test.The two follow-up commits are available for reuse:
Validation on Linux/RADV: full
libsbuild; 17/17 focused tests covering disk-cache plans, moved buffers with pixel readback, draw-cache reuse (including verification), mesh relocation, read-first-lane, and optimized pipeline readback. WithAPS5_VERIFY_SRT_TAPE=1, the suite passes with zero tape/interpreter mismatch diagnostics. The three moved-buffer/draw-relocation/mesh-relocation tests also pass withAPS5_NO_GPL=1.These are integration/correctness results, with no title-performance claim. The linked branch also contains unrelated Snoopy bring-up dependencies; the two linked commits are the relevant follow-ups.
AI-assisted: yes (Codex).
Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-20T08:27:04Z.
Review: CHANGES_REQUESTED
This no longer merges with
mainand the conflicts are in logic, not adjacency:DrawRelocate.cpp,Pipeline.cpp,SrtDescriptorEvaluation.cpp,SrtEvaluator.cppandShaderDiskCache.cpp.Besides the rebase, two things break against current
main(reported by @JJenkx on Linux/RADV, mainccb0c0926, with commits to reuse):SrtTape.cpp(new onmain) does not populate the newreadInstructions,operandReadsandsourceLeadsmetadata, soagc_driver_draw_cache_moved_bufferreports zero cache hits (it passes withAPS5_NO_SRT_TAPE=1). The tape also has to keep operand nesting through invariant phi, read-first-lane and extracted composites, and roll the metadata back when it falls back to the interpreter:github.com/JJenkx/AnyPS5@fd1745db9ccloneVariant()does not copy themeshIndexDescriptoradded onmain, soagc_driver_mesh_draw_relocationmisses on the differing front stage:github.com/JJenkx/AnyPS5@32b211b48aPlease rebase onto
main, include those two fixes (or equivalents), and checkagc_driver_draw_cache_moved_buffer,agc_driver_draw_cache_relocationandagc_driver_mesh_draw_relocationwith and withoutAPS5_NO_SRT_TAPE=1.Imported from boykopovar/AnyPS5. Originally posted by JJenkx on 2026-10-20T19:51:44Z.
The tape-provenance repair discussed above is now published as 572fe318ce, with a differential tape/interpreter regression. The regression fails without the repair and passes with it. The rebased integration branch preserves the prerequisite authorship from this PR and #6539.
Source links, reproduction command and matched-main test results: five matching tests pass on main
2185dbf92e; six pass on integration572fe318ce, including this PR's moved-buffer regression. Both logs have zero VUID errors, missing-layer warnings or skips (RX 6650 XT, RADV 26.2.4, Arch Linux). This supplies reviewable source for the earlier report; no game FPS claim. AI-assisted: yes.Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-21T10:27:03Z.
Review: CHANGES_REQUESTED
This still does not merge with
main: the rebase conflicts in logic in the first of its eight commits (DispatchCache.hpp,Pipeline.hpp,Pipeline.cpp) and again inDrawRelocate.cpp,SrtEvaluator.cpp,SrtDescriptorEvaluation.cppandShaderDiskCache.cpp. Resolving it means deciding how the relocation metadata interacts with code that landed after you branched, so it needs you.Please rebase onto
mainand include:SrtTape.cpppopulatingreadInstructions,operandReadsandsourceLeads, keeping operand nesting through invariant phi, read-first-lane and extracted composites, and rolling the metadata back when the tape falls back to the interpreter. @JJenkx published a repair with a differential tape/interpreter regression:github.com/JJenkx/AnyPS5@572fe318ce(their integration branch: https://github.com/JJenkx/AnyPS5/tree/fix/descriptor-relocation-integration). Reuse it or an equivalent.cloneVariant()copyingmeshIndexDescriptor(github.com/JJenkx/AnyPS5@32b211b48a), soagc_driver_mesh_draw_relocationhits on the differing front stage.Then run
agc_driver_draw_cache_moved_buffer,agc_driver_draw_cache_relocationandagc_driver_mesh_draw_relocationwith and withoutAPS5_NO_SRT_TAPE=1.Imported from boykopovar/AnyPS5. Originally posted by EagleBearerYS on 2026-10-22T06:04:00Z.
@TheAggie a merge-order note: #9396 (a draft) changes the draw relocation alias map that this PR replaces with per-stage donors (
drawStageDonors,drawDecodes). In #9396 an alias names the draw key it was learned for instead of holding the cached entry, so an evicted entry isn't kept alive through it, and a draw that hits through an alias moves its donor to the front of the cache's LRU. As this PR conflicts withmainat the moment, #9396 proposes going first, and this PR's donor maps would take the same two rules when it rebases; I can put that change on a branch of my fork for you to take. If this PR lands first instead, #9396 moves both rules to its donor maps. If you'd rather this one went first, say so and #9396 will list it under Depends on.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-23T03:04:16Z.
Review: CHANGES_REQUESTED
Reviewed — changes requested
Changes are required before merge: prevent creation of a partial relocated draw entry when any stage lacks an eligible donor.
What I ran
Reviewed head
09238da8206e0aa70d8966c69f822c297da36308. Read the prepared description, commits, diff and manifest, plus targeted source for draw relocation, cache lookup/capture, descriptor metadata, pipeline dynamic state, pending image overlap, the moved-buffer test and shader disk cache. No build or tests were run. The author reports Windows 11 testing and performance captures; these were not independently run here.Results
Findings
Blocking
DrawRelocate.cpp:271publishes a relocated entry even whencompleteis false. In that case, rejected or unavailable stages remain empty, but the entry is still returned with the donor decode.Draw.cpp:105-108then treats any non-null entry as a cache hit candidate, and lookup marks a stage-size mismatch as a miss; later stage reuse can consume only the matching subset. This can turn partial donor availability into a draw built from an inconsistent set of relocated and newly compiled stages. Return without publishing the relocated entry unless all required stages are available and valid, or make the caller fall back to a full decode/build when relocation is incomplete.Non-blocking
None.
Not verified
No build, test suite, Vulkan device run, Linux build, or performance capture was performed. The description’s test and performance results are author-reported. All changed files listed as
reviewedin the manifest were present and read via the prepared diff; targeted repository source reads are listed above. Excluded files were not inspected individually.To get this to a good state
Require complete, valid donor coverage before returning a relocated draw entry, then rerun the moved-buffer and draw-cache tests on the updated head.
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.