perf(agc): reuse sampled snapshot byte buffers across cache entry replacement #8026
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/8026"
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 NFSS10 on 2026-10-19T18:06:08Z.
What
The sampled-texture cache stores one guest-byte snapshot per surface. While a surface's storage image is still pending on the GPU the entry is a view (no bytes); once the image flushes and the CPU samples the surface, the entry becomes a snapshot (with bytes). Render targets hit both states every frame, so the entry alternates view → snapshot → view. On each alternation the old snapshot's buffer was destroyed and a new one allocated and zero-filled, only to be completely overwritten by the re-read: for a 4K surface (31.9 MiB) that is ~3.2 ms of the ~6.5 ms each re-snapshot costs, ~40 times per second in steady state — about 13% of the draw committer's wall clock.
This PR started as a per-entry buffer hand-off (
carried); while the review ran, #6982 landed and frees tracked snapshot buffers >256 KiB right after upload, which removed the buffer the hand-off would have carried for exactly the surfaces this PR targets. The mechanism is therefore reworked on top of #6982: the drop site it added — and replacement entries whose buffer cannot be adopted in place — park the freed buffer in a size-classed spare pool (TextureCache::spare) instead of returning it to the allocator, and the next snapshot of a matching size takes the spare instead of allocating and zero-filling. The pool is bounded by one constant,SpareSnapshotBytes(512 MiB); past it the oldest spare is freed, which is main's behaviour for every buffer.ClearCachedTexturesempties the pool with the cache.This also resolves the retention concern from review (@wachi35676): no cache entry keeps a guest-byte buffer beyond its creation/lookup path — view entries hold nothing — so host memory no longer accumulates through the cache; the only bound required is the pool's cap.
Correctness rests on a pre-existing invariant, now made explicit and pinned by tests:
ReadTextureSurfaceoverwrites the whole span on every branch before any consumer can read it:ReadCommitted/copyCommittedfor uncompressed andClearSinglesurfaces,FillDccClearfor DCC clear keys. This PR makesFillDccClearzero the span on every decline path and zero the trailing partial element after the element loop, so the span is fully defined on every return for every caller (previouslyReadTextureSurfacewas the only caller ignoring its return, and a declined or partial fill left stale recycled bytes readable).ExpandSingleBlocksexpands within the already-filled span.Tests pin both contracts on pre-poisoned inputs:
fillContractTests(decline-zero and tail-zero,tests/TextureFormat.cpp, run byagc_driver_graphics) andrecycleTests(snapshot → replace with changed snapshot through the recycle path → write original content back → the cache must serve a remade texture; a stale recycled buffer would compare equal to guest memory and be served, so the assertion detects exactly the failure mode @ebosido444-ai described;tests/execution/SampledCacheBudget.cpp, run byagc_driver_sampled_cache_budget).No title-specific condition: any title that re-snapshots rendered surfaces reuses pooled buffers; where the pool has no fit — or for titles that never snapshot — behaviour is exactly main's.
Tested
Windows 10.0.22631, Bendy and The Ink Machine (PPSA27616), chapter 1 steady state, 3840x2160, same machine and scene, unprofiled: one run of
main2fee39f1band one run of this change (89cc8368d), each built from a clean tree, captured back to back.aps5-summary.jsonlwindow lines. main:this PR:
tools/trace_digest.py— main:seconds 45:30 from present 1034: 289 presents, frame p50 103.4 / p90 106.7 / p99 110.9 / max 113.2 ms, GPU busy 33.1 ms per present
AMD Radeon RX 7900 GRE, AMD proprietary driver 25.6.1 (LLPC), Windows 10.0.22631, 3840x2160, commit
2fee39f1b3, dropped: yesthis PR:
seconds 45:30 from present 1017: 372 presents, frame p50 78.7 / p90 83.0 / p99 120.9 / max 265.2 ms, GPU busy 32.9 ms per present
AMD Radeon RX 7900 GRE, AMD proprietary driver 25.6.1 (LLPC), Windows 10.0.22631, 3840x2160, commit
89cc8368df, dropped: yesMedian frame 103.4 → 78.7 ms (-24%), p90 106.7 → 83.0 ms (-22%), throughput 289 → 372 presents per 30 s (+29%), GPU busy unchanged (33.1 → 32.9 ms per present; the CPU feeding it was the limit). Window p99/max for this PR include two
Vulkan.GraphicsPipelinePrebuildstalls (265 / 256 ms, shader-prepare thread, first-use pipeline prebuild — outside this change's path; the main window had none in range). Steady-state 5 s intervals show p99 81–94 ms for this change against 107–114 ms for main. The earlier numbers in this PR's history (vsmain3bb15be, p50 -14%) predate #6982 — both sides have been re-measured above against currentmain. (dropped: yeswith worker event loss occurs on both runs.)Traces attached: aps5-trace-2fee39f1b344-27932.json.gz (main), aps5-trace-89cc8368df7e-22280.json.gz (this PR).
Unit tests pass: agc_driver_graphics (fillContractTests), agc_driver_sampled_cache_budget, agc_driver_sampled_cache_budget_memory, agc_driver_sampled_cache_budget_without_storage_image_multisample, agc_driver_image_cache_bits, agc_driver_image_table_cache, agc_driver_image_table_cache_bounds, agc_driver_resource_cache_growth, agc_dcc_key_sharing, agc_display_buffer_dcc, agc_driver_msaa_dcc_state.
python3 tools/check_conventions.py --base upstream/mainpasses.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-19T18:06:22Z.
This pull request is labeled
perf, so it needs the summary line of a capture onmainand one with the change, from the same title, scene and machine, as the Performance report form asks. Please paste bothaps5-summary.jsonllines, attach the two traces and add the output oftools/trace_digest.py.Imported from boykopovar/AnyPS5. Originally posted by ebosido444-ai on 2026-10-19T22:10:43Z.
The zero-fill you are assuming away is load-bearing in one place:
ReadTextureSurfacediscardsFillDccClear's return value (DccMetadata.cpp:776), and that function declines forClearRegisterand for any formatLayoutFordoes not handle (DccMetadata.cpp:671), leaving the span exactly as it arrived. With a recycled buffer that is now the previous surface's texels instead of zeros, uploaded silently into the texture. Second, the fill loop stops atoffset + element.size() <= bytes.size()(DccMetadata.cpp:686), so a trailing partial element also keeps stale bytes where it used to keep zeros.Make the invariant explicit rather than assumed: on
false,std::fillthe span with zeros (or throw) before returning, and cover the trailing partial element the same way. Then add one test that snapshots a surface, forces it back to a view entry, snapshots again with a size-equal stale buffer, and asserts the texels equal the guest bytes — otherwise a 6-line change in a correctness-sensitive cache rests on a hit-rate log from one title.AI-assisted: yes.
Imported from boykopovar/AnyPS5. Originally posted by wachi35676 on 2026-10-19T23:13:07Z.
NVIDIA and AMD iGPU runs of
12655e4fa, and one note on host memory.Windows 11 Home 26300, WinLibs GCC 15.2.0, Release,
BUILD_TESTING=ON,main9127ea36dwith this head merged. GPUs: RTX 5070 Ti (NVIDIA 617.42) and the AMD Radeon iGPU (RDNA2,1002:13c0, AMD proprietary driver 2026.04.17,ANYPS5_GPU=AMD). Run withANYPS5_REQUIRE_VULKAN=1.agc_driver_sampled_cache_budget*,agc_driver_image_cache_bits,agc_driver_image_table_cache*,agc_driver_resource_cache_*andagc_dcc_key_sharing;agc_driver_depth_compare_copy;uint8x4color target tests;agc_driver_image_sample_*.maintoo.main9127ea36d. The cache tests pass.agc_driver_depth_compare_copyfails withthe guest block is not write-watchedafter WSL reportsasynchronous userfaultfd write protection failed, which is a limit of the environment.From the code, the overwrite claim holds:
copyCommitted(GuestMemory.cpp:2275) zeroes the destination before it copies the committed ranges, so stale recycled bytes cannot survive in unmapped pages.Texturecopies the span into staging at once (std::memcpy(staging->Bytes().data(), snapshot.data(), ...)).Host memory. "The guest-memory footprint is unchanged" holds only while a surface keeps alternating:
carriedbuffer for as long as the entry lives.accountedcovers device bytes only, and it is 0 for a view of a cached storage image.admitTexturekeepsaccounted == 0entries until the cache passes its 125% ceiling.So a render target that is snapshotted once and then only sampled as a view keeps its buffer in host memory, 31.9 MiB at 4K, where
mainfreed it. A size or age limit oncarriedwould bound this. I did not measure it in a title.AI-assisted: yes (Claude Code); results above were run on this machine.
Imported from boykopovar/AnyPS5. Originally posted by NFSS10 on 2026-10-20T18:50:13Z.
Both findings verified against the code and fixed in
d046ddee8.Tests added:
On the suggested recipe (snapshot → view entry → snapshot again): I could not drive the view → snapshot transition in this harness without a DCC fixture — a view entry serves every source-less uncompressed lookup and holds its image alive, so it is only replaced when DCC keys intervene (StorageImageServesKeys/MetadataMoved, the fast-clear case). Both adoption branches funnel into the same entry assignment and the same ReadTextureSurface full-span read that the tests above pin. Happy to add a DCC-key fixture as a follow-up if you want that path covered end to end.
Note: since this review, #6982 landed on main and the buffer-reuse mechanism was reworked on top of it (bounded spare pool instead of the per-entry carried hop — separate comment on the PR). The invariant and tests above are unchanged.
Imported from boykopovar/AnyPS5. Originally posted by NFSS10 on 2026-10-20T18:50:56Z.
Thanks for the cross-GPU runs and for spelling out the retention scenario — it was correct, and it is now structurally gone rather than merely bounded.
While merging current main I found #6982 (perf/agc-drop-tracked-texture-snapshot) had landed: it drops >256 KiB tracked snapshot buffers right after upload, which also made carried ineffective for exactly the surfaces this PR was measured on (the buffer it would carry was already freed at creation).
The rework replaces carried entirely: the drop site, and replacement buffers that cannot be adopted directly, are parked in a size-classed spare pool instead of being freed, and the next snapshot of that size takes the buffer back. No cache entry holds a guest-byte buffer past its creation/lookup path anymore — view entries hold nothing — so the accounted == 0 retention you described cannot occur. Host memory is bounded by one constant, SpareSnapshotBytes (512 MiB); past it the oldest spare is freed, which is main's behaviour for every buffer. ClearCachedTextures empties the pool too.
Your point that no test covers the recycling itself stands — recycleTests (
66e8ffd7e) now pins the staleness contract of a recycled size-equal buffer; details in the reply to @ebosido444-aiImported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-20T20:32:34Z.
Review: CHANGES_REQUESTED
Thanks for reworking this on top of #6982 and for pinning the fill contract with tests. One blocker:
ShaderResources.cpp:270-295,parkSnapshot/spare: the pool keeps up to 512 MiB of guest-byte buffers alive on every driver untilClearCachedTextures. #6982 freed exactly these buffers because they grew to GBs of host heap (Uncharted, 2.7 GB), and the cache budget does not count them. A bound is stated, but the description gives no peak RSS before/after on a large workload (the Bendy capture shows frame time only). Please add peak RSS (working set) formainand this change on the same scene, plus one on a big-surface title or a stress scene where the cache churns, and either lower the cap to what the measurements justify or scope the pool (for example only for the surface sizes that re-snapshot every frame, and release spares that go unused for N presents).Checked and fine:
ReadTextureSurfaceoverwrites the whole span on every branch (ShaderResources.cpp:963,Texture.cpp:2681),FillDccClearnow zeroes declined and trailing-partial spans, andfillContractTestspins both. NoterecycleTestsalso passes onmain; it guards against stale bytes but does not pin the reuse itself, so a counter or a check of the pool size after a replacement would show that the spare path runs.Imported from boykopovar/AnyPS5. Originally posted by NFSS10 on 2026-10-20T23:37:56Z.
Peak RSS measured on Bendy (same scene, same machine, sampler polling PeakWorkingSet64/PrivateMemorySize64 every 250 ms, clean back-to-back builds). This environment has no big-surface title, so the second data point is an extended churn scene (level1 held for 340 s instead of 95 s) instead of a second title.
89cc8368dbb925032cThe short-scene delta is inside main's own run-to-run spread (4397–4433 MiB). On the extended scene the unscoped pool's gap over main widened from 121 to 195 MiB while running (+25 MiB/min, heading for the cap); after scoping the gap is constant (~105 MiB — the actively re-snapshotting working set): the change's late-phase drift (+35 MiB) now matches main's (+29 MiB). Private memory: main 9936–9998 MiB, change 9942 short / 10118 extended (±100 MiB run noise).
Per your either/or I did both:
Reuse is now pinned in tests: recycleTests asserts the second same-size snapshot takes the parked spare (TextureCacheUsage().spareEntries == 1 after it — without the take it would be 2), and a new spareAgeTests (placed after the CountPresent-sensitive tests) asserts a spare idle past the window is released and one within the window is taken. TextureCacheUse now reports spareEntries/spareBytes, so the pool's bytes are visible to tests and profiling. These fail without the pool, unlike before.
Perf re-validated on the scoped build, Bendy same scene vs the main baseline in the description: p50 80.6 / p90 85.3 / p99 89.1 ms, 369 presents vs 103.4 / 106.7 / 110.9, 289 — −22% p50, −20% p90 and p99, +28% presents, GPU busy unchanged (33.7 vs 33.1 ms).
{commit:bb925032c0cd,dirty:false,env:{APS5_PAD_INPUT_FILE:,APS5_TRACE_DIR:,APS5_TRACE_SECONDS:45:30,APS5_TRACE_SUMMARY_EVERY:5},gpu:AMD Radeon RX 7900 GRE,driver:AMD proprietary driver 25.6.1 (LLPC),os:Windows 10.0.22631,resolution:3840x2160,title_id:PPSA27616,content_version:01.000.002,window:{spec:seconds 45:30,first_present:1164,ms:30000.894},presents:369,frame_ms:{p50:80.624,p90:85.269,p99:89.094,max:104.765},gpu_busy_ms_per_present:33.684,trace:aps5-trace-bb925032c0cd-2932.json.gz}
Full agc_ suite on the final build: 834/838 pass; the 4 failures are the pre-existing baseline verified on main (image-array alignment vs this mingw's COFF limit, lookup_log_fits_build, and the two replay-tool exes that fail to load).
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-21T00:14:59Z.
@adriadam10 NFSS10 answered your change request at 23:37Z: the pool is now scoped to 256 MiB, with RSS numbers. They measured a churn scene in place of the big-surface title you asked about. Our code review of
bb925032c0is clean otherwise. Is that enough for you, or do you still want the big-surface run before this goes in? We'll leave your review as it is until you say.Imported from boykopovar/AnyPS5. Originally posted by thuanquang on 2026-10-22T08:58:28Z.
@NFSS10 @adriadam10 Here is data from a second title for the cost this PR targets, and an alternative for the dropped case that keeps no buffer.
PPSA14363 (METAL GEAR SOLID Master Collection Vol. 1) samples its three 24 MiB linear PS1 render targets after every synchronous draw into them. So the dropped path (tracked, over 256 KiB) runs hundreds of times per 10 s in MGS1's PS1 opening. I timed it locally on
main+ #9115. Per 10 s: zero-filling the vector takes 340 to 390 ms,ReadTextureSurface160 to 180 ms, the memcpy into the stagingBuffer155 to 180 ms, and the rest of theTexturebuild about 25 ms.The spare pool here removes the zero-fill. The branch thuanquang:perf/snapshot-read-into-staging (
3506b8b6a) skips the vector forUncompressedkeys.ReadTextureSurfacereads the surface straight into the pooled stagingBufferthat the upload already takes, and a newTextureconstructor uploads thatBufferas it is. So the zero-fill and the memcpy both go, and nothing new is kept after the upload: the stagingBuffergoes back to theBufferPool, as it does today. DCC-keyed andClearSinglesnapshots keep the vector.All of these ran on one machine and scene: RX 6700 XT, AMD driver 26.10.1, Windows 11 26200, Ryzen 5 5600X. The base is
maind6eafa54d+ #9115 #9188 #9202 #9373, which the title needs to reach this scene. OnlylibSceAgcDriver.prxchanges between the rows. The caches were warm and nothing else ran on the PC. Each capture usedAPS5_TRACE_SECONDS=120:30, inside MGS1's PS1 opening:libSceAgcDriver.prx(local merge in the summary line)Resources.Completein the window387822a8e)eb25524a1)5e41602cd)Each row is one capture. Two more untraced 240 s runs per side, base and base + branch, agree: 187 to 190 presents per 10 s without the branch and 228 to 235 with it.
The branch changes the same lines as this PR (the entry construction and the drop site), so the two conflict. Would you rather fold it into this PR, or should I open it separately? If it stays separate, the pool here would still serve the kept and DCC-keyed snapshots. Unless you say otherwise, I'll open it separately tomorrow, with a note on the overlap.