Skip to content

perf(agc): keep shaders off host imports on NVIDIA's Windows driver and cut per-draw CPU - #20315

Closed
simnJS wants to merge 22 commits into
boykopovar:mainfrom
simnJS:perf/agc-host-import-staging-and-draw-cpu
Closed

simnJS wants to merge 22 commits into
boykopovar:mainfrom
simnJS:perf/agc-host-import-staging-and-draw-cpu

Conversation

@simnJS

@simnJS simnJS commented Nov 15, 2026

Copy link
Copy Markdown
Contributor

What

Draft, opened early so the direction is visible and others can try it. It is testable today and will keep moving; the follow-up steps listed at the end will come as separate pull requests, and I am happy to split this one into a series in whatever order suits review.

The problem. A PS5 title's GPU reads and writes the game's memory directly. AnyPS5 imports that memory with VK_EXT_external_memory_host and lets shaders use it in place. On NVIDIA's proprietary Windows driver, shader access to an imported host range is very slow while a buffer copy to or from the same range is fast (measured on an RTX 4080 SUPER: shader stores into an import about 1.5 GiB/s, shader reads 35 to 50 us per MiB, vkCmdCopyBuffer about 19 GiB/s). Once that is out of the way, the frame is bound by the driver's own CPU cost per draw, not by the GPU.

What this branch does, 22 commits, each mechanism behind its own kill switch documented in docs/dev/ENVIRONMENT.md:

Keeping shaders off host imports. The copy-back choice and the input twins are decided per driver, as DrawInputsInPlaceUsable already does, and switch on for NVIDIA's Windows driver only; the other entries change the staging path wherever a driver stages:

  • 0a62088146 copy staged regions back with a buffer copy on NVIDIA's Windows driver (APS5_CHANGED_COPY_BACK / APS5_NO_CHANGED_COPY_BACK). Still needed after perf(agc): bind the changed copy-back's buffers through push descriptors #15792: forcing the compute copy-back on this branch drops the scene below to 7 fps with 130 ms of GPU time per frame.
  • a3c8e26598 bound the staging shadows of cached builds and re-stage refused regions.
  • 85007498b8 hand a staged region's shadow over to the next dispatch in the batch (APS5_NO_STAGING_HANDOVER).
  • 426fbd20e2 copy draw inputs behind a pending GPU write on the GPU (APS5_NO_DRAW_INPUT_GPU_COPY).
  • d53f6d8eba share one staging shadow per guest region and land only the copy-backs a dispatch reaches (APS5_NO_SHARED_STAGING_SHADOWS).
  • bb736a43ec upload single-key storage images behind a pending GPU write on the GPU (APS5_NO_SINGLE_KEY_GPU_UPLOAD).
  • ea00d54b8d, 14968eb1a0 serve read-only dispatch inputs from device-local twins of their host imports, refreshed only when the write tracker says the range changed (APS5_NO_INPUT_TWINS).

Driver CPU per draw (all drivers):

  • 105998d546, f2dbae986e reuse a draw's resource and target proofs while nothing they read moved (APS5_NO_DRAW_PROOFS, APS5_VERIFY_DRAW_PROOFS), and read the clock only when profiling.
  • 83488a6232, abaae73388 reuse a shape's remembered stages across moved user words, vertex tables included (APS5_NO_DRAW_SHAPE_USER_WORDS, APS5_NO_SHAPE_VERTEX_INPUT_STAGES).
  • cce2baa353 learn a draw's relocation where the draw finishes. With APS5_DRAW_PIPELINE the queue worker drained the finisher before every draw that followed a cache miss, which serialised the three threads; a third of the worker's time was that drain.
  • 560761e833, b1a8ed0533 run pipelined work in the collect epoch its queue worker held and walk a recipe draw's surfaces on the finisher (APS5_NO_SHARED_COLLECT_EPOCH, APS5_NO_FINISHER_PRECOLLECT). Measured as neutral on their own so far; kept as groundwork.

Diagnostics and tooling:

  • f2b220a97b write a diagnostic line with one call and keep prints off the GPU mutex.
  • 57199a5356, d00992c576 counters for pipelines built at draws and for the write-watch calls of collects (APS5_PIPELINE_STATS=2).
  • b3691289ef APS5_UNPACED_FLIPS=1 lifts the emulated vblank cap for benchmarks.
  • 4d31007572, 719fda99e6, 97bbe79aeb a pipeline cache test and the debt fragments.

Where it stands. Same machine throughout: NVIDIA GeForce RTX 4080 SUPER, driver 621.01, Windows 11 (10.0.26300), Ryzen 9 7950X3D, 1920x1080. These figures were taken at earlier points of this same stack, before its last rebase; the summary lines and traces in the form the Performance report asks for are not attached yet and current main has not been measured, so read them as where things are, not as the required comparison.

Title, scene Before This stack
Card Shop Simulator (PPSA36301), street after New Game about 6 fps, then 1 to 2, on 0f4538fa02 41 fps default; 52 to 58 average with APS5_DRAW_PIPELINE=1 APS5_PIPELINE_DISPATCH=1 APS5_PIPELINE_DISPATCH_MISSES=1; 49 to 68 uncapped
Subnautica (PPSA02453), Creative, near the lifepod not measured 23 to 24 fps default, about 29 with the pipeline switches
Balatro (PPSA21402) not measured locked 59.9; 250 to 475 uncapped (with an earlier form of the unpaced switch)

GPU busy time is 9 to 12 ms per frame on the first title and 16 to 18 ms on Subnautica, so both are CPU-bound in the driver: on the first title, about 18 to 20 us of CPU per draw in each of the three pipeline threads. The draw count of the first scene varies from 400 to 830 between launches, which is why the fps ranges are wide; I now compare per-draw cost on agc_frame_replay captures instead.

What comes next (in progress, as separate pull requests): per-resource versions in place of the global proof stamp, write tracking by page protection for memory that stays clean, retained draw sites so a draw seen before only pushes what changed, and keeping staged surfaces in device memory between a retile and the dispatch that reads them.

How to try it. Convert a title as usual with this branch's libraries. APS5_DRAW_PIPELINE=1 APS5_PIPELINE_DISPATCH=1 APS5_PIPELINE_DISPATCH_MISSES=1 gives the three-thread pipeline; each APS5_NO_... switch above turns one mechanism off to isolate a regression. Reports from AMD, Intel and Linux are especially welcome: apart from the two driver-gated mechanisms, this touches code every driver runs, and none of it has run anywhere but the machine above.

Tested

Windows 11, NVIDIA GeForce RTX 4080 SUPER (621.01). The three titles above were played from their menus into a scene and checked by screenshot; rendering looks correct in each. Focused AGC and VideoOut tests on this branch: 245 run with ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1, 244 passed, 1 skipped (agc_driver_host_write_shadowed_unit, Linux only). tools/check_conventions.py --base origin/main, tools/env_reference.py --check and tools/debt_fold.py --check pass.

Not done yet: the validation-layer comparison with main (no Khronos layer installed on this machine), the summary lines and traces of main and of this branch, any run on another vendor or on Linux or macOS, and tools/pr_overlap.py.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt and the licence notice of code adapted from upstream (see AGENTS.md)
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: NVIDIA GeForce RTX 4080 SUPER, driver 621.01, Windows 11 (the validation-layer comparison is still to do)
  • AI-assisted: yes

Notes on the checklist. Based on main as of 5cc140a and merges cleanly with main today; my own #18388 and #18390 are in the same area and I will close or rebase them against this. "One topic" is left unticked on purpose: this is a stack, opened as one draft so it can be measured as a whole, and it can be split. AI-assisted: written with Claude. Mythos 5.2 did the analysis, the orchestration and the most critical code, Opus agents the rest; it is still working on the next steps. I am responsible for every line.

…ndows driver

A staged buffer region is copied back into its host import by a compute pass that stores only the
bytes the shader changed. NVIDIA's Windows driver runs shader stores into a host import far slower
than a buffer copy: TCG Card Shop Simulator (PPSA36301) on Windows 11 with an RTX 4080 SUPER copies
about 131 MiB back per frame in game, 63 ms per frame with the compute pass and 7 ms with
vkCmdCopyBuffer (APS5_NO_CHANGED_COPY_BACK=1); the same scene runs at about 6 frames per second
with the compute pass and at 17 to 32 for its first minute with the buffer copy.

The device decides once (ChangedCopyBacksUsable, Context::changedCopyBacks): the whole written
range is copied back with VK_DRIVER_ID_NVIDIA_PROPRIETARY on Windows and the changed bytes
everywhere else. APS5_CHANGED_COPY_BACK=1 uses the compute pass and APS5_NO_CHANGED_COPY_BACK=1 the
buffer copy on any device, the second winning. agc_changed_copy_backs_driver checks the decision
per driver and host. Whether AMD's or Intel's Windows drivers show the same has not been measured.
…fused regions

A cached build keeps the device-local shadows of its staged regions, and the resource cache was
bounded by its entry count only. In TCG Card Shop Simulator (PPSA36301) on Windows 11 with an RTX
4080 SUPER the shadows of cached builds filled the 954 MiB live shadow bound within about a minute
of play. Every later region was refused a shadow and bound in place, about 10 ms of GPU time per
dispatch on NVIDIA's Windows driver, and the refusal stayed for as long as the build was cached:
about 640 ms of GPU time per frame, 1.4 frames per second.

ResourceCache::Insert now evicts its least recently used builds with shadows while they hold more
than half of the live shadow bound (StagedByteBudget, StagingShadowLimit), as it already does for
image table elements. StagingDecisionsCurrent fails the proof of a build whose refused region now
fits under three quarters of the bound, so the build is made again with its shadow. The default
bound goes from a sixteenth to an eighth of the device-local heap budget: with a sixteenth the
cache share was 477 MiB, the builds of a frame were evicted and rebuilt, and the scene ran at 10
to 12 frames per second against 17 to 18 with 1000 MiB.

With the buffer copy-back of the previous commit the scene holds 11 to 23 frames per second over
240 s with 1.9 GiB of device memory in use. No test covers the cache share yet, and the two
fractions come from this one title.
… the batch

A compute build whose written region is staged copies the region in from its host import before the
dispatch and back after it. TCG Card Shop Simulator (PPSA36301) records, inside one batch, runs of
dispatches that stage the same regions: about 38 MiB of distinct regions took 178 to 252 MiB of
copies each way per frame, 20 to 31 ms of GPU time on an RTX 4080 SUPER with NVIDIA's Windows driver.

With a plain copy-back the recorder now keeps the copy-back pending in the open batch
(Recorder::DeferCopyBack) and lands it wherever recorded work could observe the import: next to
every flushDeferredDispatch call that is not CloseRunOwing, and at Submit. A dispatch that stages
exactly the same range of the same import and writes at least the same sub-ranges claims the entry
(ClaimCopyBacks): its copy-in reads the written sub-ranges from the previous shadow, or nothing when
it is the same buffer, the rest of the region still comes from the import, and its own copy-back
replaces the entry. Address-based builds, draws and the changed-bytes copy-back keep the previous
path. APS5_NO_STAGING_HANDOVER=1 turns it off; the [buffers] staging handover line of
APS5_PROFILE_DRAW counts handovers, skipped and redirected copy-ins, elided and landed copy-backs.

In the same scene 289608 copy-backs were elided and 88915 landed, staging costs 4 to 5 ms of GPU
time per frame, and the title runs at 34 to 42 frames per second on entering the game and 21 to 27
later, against 20 to 23 and 11 to 18 with the two previous commits. agc_driver_staging_handover and
agc_driver_staging_handover_queue_zero cover six dispatches over one region on a compute queue and
on queue 0, a CPU store between two dispatches and a taker that fails after the handover.
Where draw inputs are not bound in place (NVIDIA's Windows driver), a vertex range a dispatch wrote
in the open batch was read on the CPU: CopyDrawInput waited for the producing batch through the
flush hook and copied the bytes into a fresh host-visible buffer. In TCG Card Shop Simulator
(PPSA36301) on an RTX 4080 SUPER the draw committer spent about 35 ms per frame in
Graphics.Draw.vertex_upload, almost all of it that wait, with the queue worker blocked behind it.

Such a range is now copied out of its host import into a device-local vertex buffer with
vkCmdCopyBuffer, recorded in the open batch after the producer (Recorder::RecordDrawInputCopies,
GpuCopiedDrawInput). The recorder remembers the copies by address; a pending write over a range
outdates its copy, and a draw prepared while no render pass is open refreshes every outdated range
at once, so a frame's copies cost about one group and no pass break. A copy is reused while the
registry generation holds and the write tracker shows no store. Labels, queued stores, copied
writers, ranges outside an import and refused device-local allocations keep the CPU copy, as do
index buffers and zero-padded fetches. APS5_NO_DRAW_INPUT_GPU_COPY=1 turns it off; the
[draw-inputs] line of APS5_PROFILE_DRAW counts copies, reuses, pass breaks and fallbacks by reason.

In the title about 34 ranges and 11 to 13 MiB are copied per frame in 0.7 ms of GPU time, the wait
is gone from vertex_upload and the draw class falls from 7-8 to 3.2-3.6 ms of GPU time per frame.
The frame rate of that scene does not move, because staging copies bound it there.
…e copy-backs a dispatch reaches

The staging handover chained only adjacent dispatches over the same regions: ClaimCopyBacks cleared
every taker and the dispatch then landed every pending copy-back it had not claimed, so a title that
alternates between groups of regions landed each group for the other. And every build owned its own
shadow of a region, so a handover between two builds still recorded a device-local copy. In a busy
scene of TCG Card Shop Simulator (PPSA36301, RTX 4080 SUPER, NVIDIA's Windows driver) staging took
271 to 334 MiB in and 170 to 266 MiB back per frame, 10 to 16 and 8.6 to 14.4 ms of GPU time, with
523376 copy-backs landed against 326340 elided.

A dispatch whose reach is known (every binding a guest buffer, shader data, a flattened SRT or the
GDS, no HTILE clear, no lease) now lands a pending entry only when one of its regions, written
ranges or indirect arguments overlaps the entry's region and it does not claim it; other entries
stay pending. Every other choke point lands everything as before. A dispatch joins a run only when
no pending entry would have to land for it. Builds that defer their copy-backs take the shadow of a
region from a registry keyed by device, range and usage, so they bind the same buffer, the handover
between them copies nothing, and live shadows follow the distinct regions; the resource cache budget
and the kept-bytes bound count a shared shadow once. APS5_NO_SHARED_STAGING_SHADOWS=1 keeps private
shadows. The [buffers] staging landings line of APS5_PROFILE_DRAW names what landed each entry.

In the same scene staging falls to 10 to 19 MiB each way and 0.6 to 1.0 ms per frame, with 653155
copy-ins skipped, none redirected, 105740 copy-backs landed and 36 MiB of live shadows; GPU time per
frame goes from 37-52 to 16-22 ms under the profile switches. Without them the title runs at 50 to
52 frames per second on entering the game and 29 to 40 later, against 36 to 44 and 16 to 35.
agc_driver_shared_staging_shadows covers alternating programs and groups, a fill and a submit
between two users, half-overlapping ranges, a refused allocation and a failing use.
…the GPU mutex

The MinGW-w64 start-up code makes stderr unbuffered, and std::fprintf is
__mingw_fprintf, which hands every character to fputc: a line reached the
operating system one character per WriteFile. Other threads cut it mid-word,
and a print made while the GPU mutex was held stopped presentation for as long
as the stream took.

- Every library links SingleWriteStdio.cpp with --wrap for __mingw_fprintf,
  __mingw_vfprintf, __mingw_printf and __mingw_vprintf: the call formats into a
  buffer and passes it to one fwrite.
- libc sets the buffer size UCRT keeps for an unbuffered standard stream from 2
  to 1, so fwrite and fputs no longer write a text of odd length as all but its
  last byte and then that byte. The streams stay unbuffered.
- The trophy load report is collected and written once.
- The texture cache budget, the [texture] totals and the [staging] adaptive
  decisions go through the profile output thread; the adaptive staging gate
  collects its lines under its mutex and hands them over after it.
- APS5_TRACE_DISPATCH_IO queues one line per dispatch through AsyncLog: the
  driver's queue, submission and shader with the device's groups and resources.
- ShaderResources::Describe checks that the DCC keys are readable before it
  reads them.

Tested: host_print_single_write, agc_dispatch_io_trace, agc_adaptive_staging,
log_file, log_macros, agc_async_log, agc_async_log_fatal, agc_profile_output,
the standard stream and trophy tests, agc_driver_recorder_tests in its 142
registered modes, agc_driver_shared_staging_shadows_tests,
agc_driver_staging_handover_tests and agc_driver_draw_input_gpu_copy_tests in
theirs (Windows 11, MinGW-w64 GCC 15.2, UCRT).
…e on the GPU

In TCG Card Shop Simulator (PPSA36301) the draw committer refreshes a 1080p colour target once per
frame whose DCC keys hold the comp-to-single code (0x10) after the title's clear kernel rewrote its
texels in the open batch. StorageTexture::upload proved the surface uniform by reading the first
texel of every 256-byte block through GuestMemory::ReadCommitted (ProvedSingleUniform, about 8.4 MiB
per upload), and read the whole surface twice more when it was not; the flush hook then submitted
the open batch and waited for every batch in flight, under the GPU mutex. Stack samples put 7.7 % of
the committer's time in that Sync and about 16 % in the whole refreshResidentTarget path.

When recorded GPU work still writes the texels, such an upload no longer reads them
(StorageTexture::singleKeyRoute):
- A word fill noted over the whole surface as its newest write (PendingSingleFill) gives the texel,
  and the image is cleared with it as before. Like PendingKeyProof, the proof holds while the write
  stamps and the newest write note over the surface are unchanged and the fill's batch has not
  signaled (SingleProofHolds).
- Any other writer has the surface detiled out of its host import in the open batch, through the
  direct upload path with its barrier, pending-read note and kept image, by a TextureDetile.comp
  variant that reads every element from the first element of its 256-byte block (SINGLE_BLOCK,
  DetileWindow::singleBlocks). The image holds byte for byte what ReadTextureSurface and the CPU
  detile give, uniform or not.
Memory the write tracker does not watch, a surface without a host import and a mip or layer not at
a 256-byte offset keep the CPU read. The direct upload also records the queued DCC key stores over
the surface before it reads the import. APS5_NO_SINGLE_KEY_GPU_UPLOAD=1 turns both off; the
[storage] line of APS5_PROFILE_DRAW counts the uploads decided on the GPU, those cleared from a fill
and those left to the CPU by reason. Not yet measured in the title.

agc_storage_single_key_upload(_off) cover a simulated writer (mixed and uniform blocks), a pending
word fill, a newer note and a signaled batch dropping the fill proof, and a surface without an
import, on both detile variants; agc_driver_single_key_gpu_upload(_off) a real compute writer and a
word fill ahead of a storage image write, with the texels checked after the write-back; and
agc_detile_small_elements the single-block detile of 1- to 16-byte elements in buffer and image
form against the CPU expansion.

Tested: agc_driver_recorder_tests in its 144 registered modes, agc_driver_single_key_gpu_upload,
TextureFormat and the other agc_driver_graphics_tests modes, ResidentTargetRegisterClear,
DccKeySharing, DccKeysFirstWrite, DccKeyPresync, SampledClearKeys, SgprPatternFillKeys,
FillCoverKeys, PresentKeyWriterWait, LinearTargetResident, agc_driver_shared_staging_shadows_tests,
agc_driver_staging_handover_tests and agc_driver_draw_input_gpu_copy_tests in their modes
(Windows 11, MinGW-w64 GCC 15.2, RTX 4080 SUPER). The Vulkan validation layer is not installed on
this machine.
…ey read moved

A resource-cache template proved current by a full Revalidate, and the
resident image a color target slot's lookup returned, keep that proof on
their thread while the collect epoch, ProofSerial, the pending registry
serial, the depth surface serial and the unwatch serial are unchanged. A
template also needs the Version of every storage image it reads (sources
of its views included), unreleased textures, held native depth views, no
stale depth plane over its ranges, the host import table and its staging
decisions; a target also needs the same ColorTarget, device and a cached
image. Every driver store, write-back, completion label, copied writer,
non-draw commit and GPU-lock hold by another thread moves ProofSerial; a
storage image a draw or dispatch writes moves its Version; a CPU store is
seen at the next collect epoch, as the collect memo already sees it. A
proof is taken only after the fast proof passed, never for templates with
BDA, staged copies, depth copies, reuse lookups or compared unwatched
memory. The opt-in epoch proof of APS5_DRAW_PIPELINE skipped the per-use
depth copy refresh and staging copies and did not follow storage images
written again; it now takes these proofs.

A dispatch that lists a copied writer moves ProofSerial, as a draw does.

APS5_NO_DRAW_PROOFS=1 restores the full check on every draw;
APS5_VERIFY_DRAW_PROOFS=1 runs it beside every reuse and counts the ones
that differ. Under APS5_PROFILE_DRAW the [rescache] draws line counts
reuses, proofs, misses by reason and verification results.
…filing

The committer timed every commit for the [draw] and [commits] lines, and
every DrawTimer read the clock at construction, though both are printed
only under APS5_PROFILE_DRAW or APS5_PIPELINE_STATS.
… their host imports

NVIDIA's Windows driver reads host memory slowly from a shader: in a standalone micro-benchmark on
an RTX 4080 SUPER, 50 skinning-like dispatches over 34560 vertices cost 2 to 8 us each with every
buffer device-local and 114 to 121 us each with the inputs read in place from imported host memory,
about 35 to 50 us per MiB touched. In TCG Card Shop Simulator (PPSA36301) one skinning program runs
27 to 51 times per frame at 174 to 268 us each, reading static vertices and skin weights and the
bone matrices of the frame in place from their imports.

A read-only region of a compute build that lies in a host import, that no element of the build
writes and that no pending write, copy-back, label or queued store covers is now bound to an input
twin: a device-local buffer per device and guest range, shared by the builds that bind it. A use
copies the range out of the import into the twin with a vkCmdCopyBuffer in the open batch, after
the pending copy-backs over it and with a pending read noted, and skips the copy while the twin is
current: filled from the same import, the registry generation unchanged, no tracker block of the
range written since the fill (Recorder::CopyStillCurrent, now shared with the draw input copies), no
write note over it since and nothing pending over it now. So static inputs are copied once and
per-frame inputs once per change, not once per dispatch.

A refresh rewrites the same buffer: its leading barrier orders it after every earlier reader on the
queue, so cached builds and recipes keep their descriptor sets, Revalidate records the refresh
through RecordStagingCopies, and a build's shared ownership keeps its twin alive. A cached build
whose twin is behind pending work copies behind that work and leaves the copy untrusted; a twin
copied on eight uses in a row is given up for 600 frames and its builds are rebuilt in place, and a
region left in place for want of a twin is rebuilt with one once one is available. Live twins are
bounded by a sixteenth of the device-local heap budget (APS5_INPUT_TWIN_MIB), the resource cache
keeps those of its builds within three quarters of it, and the reclaim path drops idle twins and
then evicts builds holding twins, so a full heap degrades to in-place binding.

The choice is made once per device beside the draw-input one (InputTwinsUsable, Context::inputTwins):
on with NVIDIA's Windows driver, APS5_INPUT_TWINS=1 and APS5_NO_INPUT_TWINS=1 force it, the second
winning. The [buffers] input twins line of APS5_PROFILE_DRAW counts twins made and shared, copies
and their bytes, refreshes, reuses, misses by reason and resident bytes; the copies are the
input-twin-copy class of [gputime]. agc_driver_input_twins covers an unchanged input over many
dispatches and frames, CPU and driver stores between dispatches and inside one batch, an input
behind a pending GPU write, a region both read and written, the budget, eviction, refused device
memory, an untracked range and the kill switch; agc_input_twins_driver covers the driver decision.
A draw whose register key has no cache entry falls back to the draw remembered for its shape (the
key without user words) and reuses one of its captured stages only when every user word the stage
uses equals the remembered one. In TCG Card Shop Simulator (PPSA36301) 85 % of the lookups find no
entry, because user words move from draw to draw, and that fallback still captured 1.3 stages per
draw, about 9 us of walk and materialization each draw on the queue worker. Stage data positions
never apply there: they exist only for flat SRT leaves, and ComputePureFlatSlots marks every slot
that feeds a buffer, image or sampler descriptor as not pure.

A shape now remembers up to APS5_DISPATCH_VARIANTS draws, most recently used first, and a stage of
any of them is reused when each used word that differs is one of:
- a word the SRT walk used as a base and never as a value (relocatableWords): the runs read through
  it move with it and are compared with memory, and its forwarded copies are patched;
- a buffer V# base or record count held in user SGPRs (valueWords, the tags of the relocation
  aliases), when the base keeps its low two bits and the size its tail, the two fields the buffer
  specialization reads: the bound descriptor is patched;
- a word the walk did not read that the compiled stage only forwards (forwardedWords, new): its
  push data or ShaderData slot is patched, as the masked result memo does.
Any other differing word, a null pointer, or memory that differs at the moved addresses captures
the stage as before. An unsynced read of the runs rejects a remembered stage before the full
validation, which still decides. A draw that had to capture a stage is added to its shape when that
stage's identity (code variant, words it depends on, captured words) was seen before; a shape whose
added draws are dropped unused pauses the additions.

APS5_NO_DRAW_SHAPE_USER_WORDS=1 keeps one draw per shape and the equal-words rule. The
[draw-cache] shape user words line of APS5_PROFILE_DRAW counts the stages reused by rank and by
kind and the stages captured by reason. APS5_VERIFY_DRAW_DATA_HITS also compares the bindings and
forwarded words of a moved stage with its full build.

agc_driver_draw_shape_user_words covers four buffers alternating through one shape, a moved table
with equal and with other words, a pointer whose high word moves, a fifth buffer beyond k, the
classification of moved words and the pause; it and the data-hit, reuse and relocation tests also
run with the switch set. Stages with header vertex inputs are not tagged for relocation and a V#
inside a table still captures; the effect on the title is not measured.
A draw whose register key has no cache entry left its key, alias and shader identity in one
Driver member, and the next draw learned the relocation shape and alias from the inserted entry
before its own lookup. With APS5_DRAW_PIPELINE the entry is inserted on the draw finisher, so that
next draw first drained the finisher whenever the member was set. Most draws miss the cache, so
the queue worker waited for nearly every draw it had just handed off and the finisher overlapped
almost nothing. The single member was also why the drain was needed at all: without it the next
miss would have overwritten the record before the finisher's admission check read it.

The record now travels with the draw in its DrawTail. cacheDrawStages passes it to admitDrawKey
and, right after insertDrawEntry, learns the shape and alias from it under drawCacheMutex, on
whichever thread finishes the draw. The drain and the member are gone.

A lookup may now read a shape or alias that a still-pending draw has yet to teach. That can only
lose a reuse: relocateDrawEntry accepts a move only through the donor variant's own relocatable,
callee and value words, and the relocated variant's moved runs are still compared with memory.
Same-key and empty-shape lookups still drain through DrawFinisher::PendingKey. Every access to
drawRelocations, drawAliases, drawRelocationTrials and drawRelocationCounters stays under
drawCacheMutex.
…t twin builds take draw proofs

A cached compute build bound to input twins checked each twin in full at every use: the recorder's
pending-write, copy-back, label and queued-store queries, two twin registry locks, and
Recorder::CopyStillCurrent, whose write-watch collect walks the whole range once per collect epoch.
In agc_driver_input_twins on an RTX 4080 SUPER (NVIDIA's Windows driver), a dispatch over a 2 MiB
twin costs 2.5 to 4.6 us within one collect epoch, as without twins (2.4 to 2.8 us), but 15 to 20
us when an ordering point precedes it: the collect of the 2 MiB range in a new epoch alone takes 12
to 13 us, about 6 us per MiB; the rest of the full check measures about 0.3 us.

Every driver store (GuestMemory::SetStoreHook, called by storeOwn and markWritten) and every queued
label over a twin's range now outdate it, as a write note does, and every change of a twin (fill,
outdate, demotion, clear) moves its serial. A current twin therefore has nothing pending over it,
and its check skips the recorder's queries. A twin found current keeps that verdict, shared by the
builds that bind it, while the queue thread's collect epoch, its serial, the registry generation,
UnwatchSerial, the frame and the import buffer hold: later uses skip the check without a lock.
Within one epoch the collect memo already keeps this thread from walking the range again, so the
verdict misses nothing the full check would have seen, except a page another thread walked (the
draw proofs' caveat). StagingDecisionsCurrent reads a twin's demotion without the registry lock.

A template with input twins may now take a draw proof: only when each twin is current and its
serial is the one its own last check or fill saw, and the proof holds while those serials and the
registry generation do (DrawProofMiss::InputTwins), so a held proof implies no refresh is due.

APS5_NO_DRAW_PROOFS=1 checks every use in full; APS5_VERIFY_DRAW_PROOFS=1 runs the full check, the
recorder's queries included, beside every memoised verdict and every check that found a twin
current, counts the full check's refresh of a proved twin as a difference, and prints a
[draw-proofs] verify line for either. The [buffers] input twins line counts uses served by a
memoised verdict against uses checked in full, with the time of each, and verified verdicts.
agc_driver_input_twins covers 400 dispatches of one epoch over a twin two programs share (one full
check), a 2 MiB input across ordering points, a driver store, a CPU store behind an ordering point
and a recorded write inside one epoch, and a build that takes a proof over a twin, loses it to a
recorded write and takes it again; it gains verify, unstaged verify and unproved modes.
The pipeline store now counts the graphics pipelines it builds outside a
journal replay (on the thread that records the draw) apart from those the
replay builds, with their build time, in PipelineStoreCounters and in a
[pipelines] line every 10 s. The line also states the journal's replay
(loaded, built, present, rejected, failed, running or finished).

The [pipecache] line counts the replay's own builds as misses, so a warm
run's first window reads as a burst of draw misses; the new line tells the
two apart. It and the [pipeline-journal] summary are printed under
APS5_PROFILE_DRAW or under APS5_PIPELINE_STATS, whose values other than 1
keep graphics pipeline libraries and the draw pipeline's hand-off, so a
run can see whether pipelines are still built during play.

The journal tests check that a draw's first pipeline counts as built at
the draw, that the replay's counts as a replay build, and that the next
run's draw of the same configuration builds nothing.
A cache file whose Vulkan header names another device, with a valid
checksum, is reported and not given to the driver, the run starts with an
empty cache without an error, and its save replaces the file.
… thread

A configuration neither the journal replay nor an earlier draw built is
compiled by CachedPipeline on the thread that records the draw, and later
draws wait behind it.
…words

A draw without a cache entry reuses the stages remembered for its shape, but a stage with header
vertex inputs was never tagged for relocation, so any used user word that moved on it captured the
stage again. Its vertex stage info comes from the vertex buffer and attribute tables those words
point at, its decode reads sat among the runs it validates at the old addresses, and its compiled
result keeps the V# of each vertex attribute, so a moved table pointer could not be followed.

Such a stage is now tagged like the others, with its decode reads kept after its sorted SRT runs and
its table pointer words recorded (offset by the hidden user words the decode uses, which the fixed
mask lacked on a stage whose first user SGPR is 0). When a remembered stage's table pointer moves,
the draw decodes the tables again at the new address, once per stage, and reuses the stage when the
decoded inputs keep their count, destinations, formats, component selects and strides: the fresh
decode reads replace the remembered ones among the runs validated against memory, the draw uses the
fresh vertex stage info, and the V# bases and record counts that differ are patched into a copy of
the compiled vertex attributes, which the vertex upload reads per draw. Other moved words follow the
existing rules, so a relocatable pointer on such a stage now relocates too. A table pointer the walk
reads but cannot relocate, one the stage reads at run time without a forwarded slot, a decode that
fails or differs in anything else, and a decode read changed in place under an unmoved table still
capture the stage. A captured stage's identity leaves its table pointers out and keeps its decoded
layout. Relocation aliases still refuse every move on a stage with vertex inputs.

APS5_NO_SHAPE_VERTEX_INPUT_STAGES=1 restores the untagged stages, and APS5_NO_DRAW_SHAPE_USER_WORDS=1
implies it. The [draw-cache] shape user words line counts the stages reused with re-decoded tables,
the stages with vertex inputs reused (with patched V# bases) and captured, the new capture reasons
and the kind of moved word that refused them. APS5_VERIFY_DRAW_DATA_HITS captures such a stage too,
compares its runs regardless of order and its vertex attributes with the full build, and counts and
prints a difference instead of aborting.

agc_driver_draw_shape_user_words covers the classification and rebasing of such a stage, and a
vertex stage with a header input drawn through a moved vertex buffer table holding the same V#, a
V# naming another vertex buffer, a moved attribute table, another stride, another format word and a
table changed in place; it also runs with the new switch. The effect on a title is not measured.
A profile of the draw committer puts a quarter of its busy time in the
GetWriteWatch calls behind GuestMemory::CollectWrites, yet nothing counted
them: APS5_COUNT_MAPPING_QUERIES, a build-time switch, covers only the
private-allocation branch of WindowsMappings::Collect. Without the number of
calls there is no way to tell whether a change to the collect memo removed
walks or only moved them.

Every GetWriteWatch and ResetWriteWatch a collect makes (private allocations,
resident runs, the reset of fresh resident pages) now moves a relaxed atomic
counter that GuestArenaCollectWatchCalls_nid_no_patch returns. GuestMemory
charges the calls made on the committer thread (the one MarkProofThread
marks) to it: every walk runs under the tracker lock, so the counter's
difference across a walk is that walk's. GuestMemory::CollectCounted returns
both with the collect epoch bumps and the collect-memo hits.

The [guestmem] line of APS5_PROFILE_DRAW prints the totals. The draw
pipeline's 10 s report, printed under APS5_PROFILE_DRAW or
APS5_PIPELINE_STATS, gains a [collects] line with the calls, the committer's
share, the epoch bumps and the memo hits of those 10 s: APS5_PROFILE_DRAW
keeps draws off the draw finisher, so the pipeline as it runs in a game is
only visible under APS5_PIPELINE_STATS. agc_collect_memo_generation checks
that a walk is counted, that a memo hit is not, and that a walk on the
marked thread is charged to it.
A collect of epoch e is answered by any walk of the block made at or after
e, by whichever thread. The draw finisher and the committer did not take the
worker's epoch: DrawPipeline::FollowEpoch bumped a fresh one on each of them
whenever the worker's epoch token moved. A fresh epoch is newer than every
walk the worker and the finisher had made for the same draw, so each stage
walked the same ranges again, and the committer's GetWriteWatch calls ran
under the GPU mutex.

Every committer item and every finisher job now carries the epoch of the
thread that queued it (GuestMemory::HeldCollectEpoch, read whether or not the
collect memo is on), and the committer and the finisher adopt it before
running it (GuestMemory::AdoptCollectEpoch, which never moves a thread back).
FollowEpoch no longer bumps. A job the finisher queues on the committer
carries the epoch the finisher adopted, which is the worker's at the hand-off.

An item follows in the command stream the ordering point that started its
epoch and precedes the worker's next one. Recorded inline, the worker would
have checked it in that same epoch, answered by any walk made since the
epoch began; the committer now applies exactly that rule to it. A CPU store
made after such a walk is seen from the next epoch on, which is the order
the collect memo documents for a store made while a submission runs. A
store ordered after the item by a label cannot be visible yet, since the
committer writes that label after the item. Items that never called
FollowEpoch (labels, stores, DMA, fills, sample dumps, submission ends) used
whatever epoch the committer last followed, possibly one older than an
ordering point the worker had passed before queuing them; they now take the
worker's epoch too.

Epoch-keyed memos on shared objects (resource proofs, storage image and
mirror refreshes, input twin verdicts, untracked compares) can now pass
between the worker, the finisher and the committer within one epoch, as
they already could with the presenter, which adopts the newest epoch a
worker bumped. Those written under the GPU mutex by a thread other than the
committer carry the ProofSerial that thread's lock acquisition moved; the
others are keyed by global serials. The debt file lists the residue.

APS5_NO_SHARED_COLLECT_EPOCH=1 restores the fresh epochs. The [collects]
line then counts the finisher's and the committer's bumps again, which the
shared epoch removes from the collect epoch count.
agc_collect_memo_generation checks that a thread that adopts another
thread's epoch reuses its walk, never moves back and walks again in its own
newer epoch; agc_driver_draw_pipeline_retired_items checks the epoch the
committer and the finisher run their work in, in both modes.
With the shared collect epoch, a range the worker or the finisher walked in
an item's epoch is a memo hit on the committer, but the committer still made
the first walk of every range none of them touched. For a draw recorded from
a draw recipe those are the template's described ranges, which ProveCurrent
collects when the template's proof is not held, and each color target's
surface and DCC keys, which StorageTexture::refreshProved collects when the
target's proof is not held. Both proofs are keyed by the collect epoch, so
the first draw of each new epoch walks them, under the GPU mutex that
commitDraw takes first.

A draw recipe now lists those ranges when it is built: the template's
described ranges (fixed once its build completes, the ranges
ShaderResources::PrecollectSurfaces walks before a dispatch's lock), and the
surface and key range of each color target that is not an array (an array
target refreshes only the layers it draws). The recipe stays immutable. The
draw finisher walks the list just before handing the draw over, in the
epoch the committer adopts for it, so the committer's collects of those
ranges are memo hits. A walk only turns CPU writes into block stamps sooner;
the committer's checks are unchanged and walk whatever the list misses.
Draws finished on the worker are left alone, to keep the walks off the
worker.

The finisher walks only with the shared collect epoch and the collect memo
on: in an epoch of its own, or without the memo, the committer would walk
the same ranges again.
APS5_NO_FINISHER_PRECOLLECT=1 leaves the walks to the committer. A walk
holds the tracker lock, so a committer collect that misses can now wait for
a finisher walk.
…chmarks

Every flip waits in VideoOutDriver::processFlip until the emulated vblank
count reaches lastFlipVblank + flipRate + 1, so a title that renders faster
than 59.94 Hz is still held to it (VideoOut.Flip.vblank_wait takes most of a
light title's frame) and every A/B measurement of a driver optimisation
saturates at 60 fps.

APS5_UNPACED_FLIPS=1 skips that wait, whatever the flip rate: a flip
completes as soon as it has been presented. Nothing else changes. The
presenter still handles flips one at a time in submission order,
lastFlipVblank still records the vblank count at the flip, and the flip
status, buffer labels, buffer-reuse waits and flip events are updated at
completion as before. The vblank clock is not sped up: vblank and
pre-vblank events, sceVideoOutWaitVblank, the vblank status and the
reported refresh rate keep the output's 59.94 Hz (119.88 Hz) cadence, so a
title that waits for the vblank itself stays paced by its own choice.

The swapchain's default fifo mode would then hold presents to the host
display's refresh, so with the switch set and ANYPS5_PRESENT_MODE unset the
device picks immediate, else mailbox, and says on stderr which mode it
uses and when the surface only offers a refresh-bound one. An explicit
ANYPS5_PRESENT_MODE still wins, and ANYPS5_FPS_LIMIT still applies.

The window title FPS and the trace summary's presents and frame_ms time
presenter events with the host clock, so they report the flip rate without
change; the summary records the variable with the other APS5_ ones, and
page 2 of the performance overlay now shows UNPACED FLIPS.

Unset, empty or 0 keeps today's behaviour; any other value fails the open
of the video output with an error naming the variable.

Tests: video_out_flip_unpaced and video_out_flip_paced run 24 flips one
after another; with the switch they complete within fewer than 12 vblanks,
without it each one a vblank after the last. Both check the flip status,
the flip events and that vblank waits keep 59.94 Hz. The parser, the
present mode default and the overlay line have host tests.
The perf(agc) and perf(log) commits of this branch edited
docs/dev/debt/libSceAgcDriver.md directly; the debt file now changes only
through a fragment in docs/dev/debt/changes/. The file is back to main's
text, and docs/dev/debt/changes/integ-rebased-2.md holds the same edits:
one change of the Device-local staging entry and the nine added entries,
their text unchanged.

Folded with tools/debt_fold.py, the file holds the same entries and the
same text outside entries as before; only the place of the added entries
changes, each going after the last entry of its section that links the
same file, as the fold places them.
@github-actions github-actions Bot added libc build docs prx agc libSceAgc* perf Performance change perf numbers missing perf pull request without a before and after summary line labels Nov 15, 2026
@github-actions

Copy link
Copy Markdown

This pull request is labeled perf, so it needs the summary line of a capture on main and one with the change, from the same title, scene and machine, as the Performance report form asks. Please paste both aps5-summary.jsonl lines, attach the two traces and add the output of tools/trace_digest.py.

This was referenced Dec 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agc libSceAgc* build docs libc needs rebase Conflicts with main, rebase needed perf numbers missing perf pull request without a before and after summary line perf Performance change prx

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants