Skip to content

fix(kyty): keep GPU writes when a request for more layers replaces an image - #293

Open
SleglJan wants to merge 2 commits into
simnJS:AnyKytyfrom
SleglJan:kyty-expand-gpu-written-layers
Open

SleglJan wants to merge 2 commits into
simnJS:AnyKytyfrom
SleglJan:kyty-expand-gpu-written-layers

Conversation

@SleglJan

Copy link
Copy Markdown
Contributor

What

TextureCache::FindImageImpl frees the cached image it found when that image's subresources compare below the request's (resources <) and creates the requested image from guest memory. FreeImage does not write a GPU-written image back, so what the GPU wrote to it since its last write-back is lost: the new image holds the older guest bytes.

  • A GPU-written image (IsGpuModified()) found there with as many levels as the request, that is with fewer layers, is now expanded with ExpandImage, as ResolveOverlap already does for a same-format request with more subresources: the new image is loaded from guest memory, the old image is copied into its first layers and then freed. Other images are freed as before. IsGpuModified() stays set after a write-back by DownloadImageMemory, so an image already written back is expanded too.
  • kyty_shim_image_write_back_alias gets a check: a GPU-written image of 1 level and 4 layers, then a request at the same address for 6 layers in another format, once R32Uint → R8G8B8A8Unorm and once B8G8R8A8Unorm → R8G8B8A8Unorm with one guest format, k8_8_8_8UNorm (B8G8R8A8Unorm is the host format ResolveHostFormat picks for a render target of it with ChannelOrder::kAlt). The first 4 layers must keep the written bytes, the other 2 must hold the guest memory, and the image must stay GPU-written. A third case requests 2 levels and 6 layers; that image must be loaded from guest memory alone. Without the fix the check fails with "a request for more layers dropped the GPU-written layers".

A request reaches this branch with a format other than the cached image's when ResolveOverlap returns the cached image at the same address because the two formats are view-compatible (ImageViewOps::FormatsCompatible: the same compatibility class, for uncompressed color formats the texel block size). In series R and the run on the stack below, every expansion had a pixel format different from the request's. For such pairs TextureCache::CopyImage copies with vkCmdCopyImage (the backing formats have the same block size), so the bits stay as they are, as in a view of the old image in the new format. Image::CopyImage copies level by level and layer by layer by index; with equal level counts (this PR's condition) and the same pitch, height, block size, tile mode and type (that path of ResolveOverlap), a layer starts at the same guest offset in both images.

In 007 this is one way the water goes missing (#98). With diagnostic switches that make the missing water likely, the water was missing in 2 of 2 runs without the change and present in 4 of 4 with it (series W2 in Tested; one-sided Fisher p = 1/210 = 0.005 against the 6 runs without it under the same forcing: the 2 of series W2 and the 4 of series W). In those runs without the change, the branch freed 4 GPU-written 129×129 R32Uint layered images in the logged window, 3 of them in the frame before the area opens; with the change it expanded them.

Known limits:

  • A GPU-written image with fewer levels than the request is still freed without a write-back, as before. With a different level count every level starts at a different guest offset: levels are stored smallest first, so level 0 of a longer chain starts after the smaller levels, and later layers move with the slice size. A copy by index would put the old image in the wrong place. In one 340 s run of 007 (see Tested) that was 8,546 of the 8,548 GPU-written images the branch found; it expanded the other 2. In the runs of series W2 every image declined (5,562-7,385 per run) had 1 level and 1 layer and was requested with 9 or 10 levels, at sizes from 640×360 to 1920×1080.
  • Each expansion adds a copy of the old image into the new one, and the new image is GPU-written, so the GC or a readback can write it back later, which a re-created clean image never needed. The base loads the new image from guest memory in full as well, after its free.
  • As for ResolveOverlap's expansions, the old image is refreshed first (RefreshCopySource). A CPU-dirty old image that is multisampled or uses video-out compression stops with EXIT there, where the base freed it. Not seen in 007.
  • Among the other frees without a write-back, not changed here: ResolveOverlap frees an idle image at the requested address with the same block extent and block size when the tile mode differs, or the mip layout at equal subresources, and an idle overlapping image that starts at or below the requested address, is not a level or layer of the request and holds the request as none of its levels or layers; the texture GC frees GPU-written images it cannot download (SafeToDownload() false).

Tested

007 First Light (PPSA11386), Linux (CachyOS, kernel 7.3.4), Ryzen 9 7950X3D, AMD Radeon RX 9070 XT (RADV GFX1201, Mesa 26.2.6). Release builds, SDL_VIDEODRIVER=x11, scripted pad input, one save and route, shader caches warmed from one earlier run, the local 5-byte title patch and the setup described in #98.

This PR is based on 7de61e3451. Its condition was narrowed in review: an earlier version expanded every GPU-written image found in the branch, whatever its level count, and with different level counts its copy by index put the old image in the wrong place (levels are stored smallest first). Series R and W below ran that earlier version; the other runs use this PR's condition. Builds and settings:

This PR changes no file that #278 or #290 change. #289 changes the same two files in other places; git merge-tree merges the two without conflict.

Water is judged from 60 s of video recorded from 150 s after the title starts: the mean luma of the water region over the gameplay frames, missing below 22 (here 3.4-15.3 when missing, 23.8-30.0 when present). On the diagnostic build a run also needs the per-frame rate of the water's draw group in the diagnostic log below 0.35 to count as missing. The rules of every series were fixed before its runs.

Series W2, this PR's condition on the diagnostic build, in the order without / with / with / without / with / with, 300 s per run. Rule: the forcing is reproduced if at least 1 of the 2 runs without the change is dry; the change prevents it if none of the 4 with it is dry. Planned test: Fisher's exact test, one-sided, of the runs with the change against all runs without it under this forcing on this build line today (these 2 and the 4 of series W).

Without the change With it
Water region luma 15.3 / 11.3 29.8 / 29.6 / 23.8 / 29.6
Water missing 2 of 2 0 of 4
GPU-written 129×129 R32Uint images freed by the branch, logged window 4 / 4 0 in every run
Images expanded by the branch, logged window 0 4 in every run, all of them 129×129 R32Uint
GPU-written images freed by the branch, logged window 558 / 418 521 / 470 / 251 / 533, each with a level count other than the request's
  • Result: reproduced, and prevented. Fisher's exact test against the 6 runs without the change: one-sided p = 1/210 = 0.005.
  • The third run with the change (23.8) is closer to the threshold than the others; its area opened later than in every other run of series W and W2, and the rate of the water's draw group was normal (0.716; 0.705-0.712 in the other W2 runs with the change).

Series W, the earlier version on the diagnostic build, in the order without / with / with / without / with / with / without / with / with / without, 300 s per run. Rule: the forcing is reproduced if at least 2 of the 4 runs without the change are dry; the change prevents it if none of the 6 with it is dry.

Without the change With the earlier version
Water region luma 11.7 / 3.4 / 14.9 / 12.3 29.7 / 29.6 / 29.6 / 29.6 / 29.7 / 29.5
Water missing 4 of 4 0 of 6
GPU-written 129×129 R32Uint images freed by the branch, logged window 3 / 4 / 4 / 3 0 in every run
Images expanded by the branch, logged window 0 535 / 555 / 558 / 603 / 582 / 531
  • Result: reproduced, and prevented. Fisher's exact test on 4 of 4 against 0 of 6 (computed after the runs): one-sided p = 1/210 = 0.005.
  • In all 10 runs every 129×129 R8G8B8A8Unorm, R32Uint or R32Sfloat and 640×640 R32Uint image the branch freed or expanded in the logged window, and every such image created on those frames, had 1 level (counted after the runs from the diagnostic log), so this PR's condition expands the same 129×129 images. The other expansions of the earlier version it would mostly decline (see the run on the stack below).
  • The second run without the change (3.4) lacked the detector's gameplay start and was scored by the planned fallback: the same region and threshold, with gameplay taken to start 60 frames after the end of the loading stall.

Series R, the earlier version on the stack, in the order without / with / with / without / with / without / without / with, 340 s per run, no forcing. FPS is the median of the window-title FPS over 200-300 s. Character band (the one-frame black band of #289) and one-frame black squares are counted per 10 s of gameplay by the frame-difference detector used in #98, over the 30-34 s of gameplay after the area has loaded. VRAM and GTT are the card's (sysfs, every process), peak over the span of the counter lines. Rule: no regression if the median FPS with the change is at least 0.97 × the median without and its minimum at least 0.95 × the minimum without, and the medians of both counts with the change are at most the maximum without.

Without the change With the earlier version
FPS 41.90 / 41.66 / 44.64 / 42.48 (median 42.19) 43.27 / 41.30 / 41.28 / 41.97 (median 41.63)
Character band per 10 s 1.31 / 1.61 / 0.61 / 0.00 0.63 / 1.00 / 0.62 / 0.62
Black squares per 10 s 0.98 / 1.29 / 3.68 / 1.50 3.14 / 3.00 / 1.56 / 3.44
Peak VRAM, GiB 15.91 / 15.91 / 15.91 / 15.90 15.91 / 15.91 / 15.91 / 15.91
Peak GTT, GiB 3.62 / 3.55 / 3.78 / 3.73 3.46 / 3.64 / 3.61 / 3.64
GPU-written images freed by the branch 6,452 / 8,513 / 6,953 / 6,802 0
Images expanded by the branch 0 8,601 / 8,030 / 6,443 / 8,740
Water missing / present / present / present present in all 4
  • Result: no regression by the rule, for the earlier version. Three of the four runs with it have more black squares (3.00-3.44) than every run without it except one (3.68); exact two-sided Mann-Whitney p = 0.34 (computed after the runs), so 4 against 4 does not separate them. Peak VRAM is at the card's limit in every run, so it does not compare the two.
  • Over the 330 s the counter covered, the expanded images total 54-89 GiB by guest size (167-277 MiB/s); every expansion had a pixel format different from the request, none a different image type, and none came from an image with more levels or layers than the request.
  • Without forcing, the water was missing in one of the four runs without the change and in none with it; that alone is not significant.
  • FPS here is from separate runs (window title), not the in-run KYTY_AB comparison; this PR makes no speed claim.

This PR's condition on the stack, one run, 340 s, switch on; the counter line also counts the GPU-written images the condition declines. Rule fixed before the run: if the condition declines no image, series R applies to this PR as it is. It declined 8,546 GPU-written images (another level count) and expanded 2 (61,440,000 bytes by guest size, a different format from the request), so series R does not carry over as measured; this PR changes far less than the earlier version did. In that run the water was present and the FPS was 42.41 (series R without the change: 41.66-44.64).

This PR's commit on 7de61e3451 alone, two runs of 300 s: water present in both (29.5, 30.0), 28.41 and 29.72 FPS. The earlier version on 7de61e3451 alone, two runs: water present in both, 28.61 and 28.93 FPS.

The regression rule of series R was not run for this PR's condition; the readings for it above are single runs.

Tests (RADV GFX1201):

  • The full test set (110 tests: the Kyty shim tests, agc_kyty_shaders, guest_gpu_fault, guest_host_write_filter) gives the same result per test on 7de61e3451 and on this PR: 107 passed, kyty_shim_rt_corpus skipped, kyty_shim_wave64_cross_lane and kyty_shim_wave_split_written_reads fail here on both. On this PR kyty_shim_image_write_back_alias passes with the new check.
  • The new check alone on 7de61e3451 fails with "a request for more layers dropped the GPU-written layers"; every other test gives the same result as on 7de61e3451. With the earlier version of the change it fails with "an image with fewer levels was copied into the request's layers".
  • kyty_shim_image_write_back_alias also passes on 7de61e3451 and on this PR with VK_LAYER_KHRONOS_validation 1.4.363, ANYPS5_REQUIRE_VULKAN=1, ANYPS5_NO_SHADER_CACHE=1 and VK_LOADER_DEBUG=layer (the layer loaded, per the loader log; no validation messages on either).
  • tools/check_conventions.py --base 7de61e3451 and tools/check_kyty_settings.py pass.

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: AMD Radeon RX 9070 XT, RADV GFX1201, Mesa 26.2.6, Linux (CachyOS, kernel 7.3.4)
  • AI-assisted: yes (Claude Code)

🤖 Generated with Claude Code

… image

When a lookup finds a cached image with fewer subresources than the
request, FindImageImpl frees it and creates the requested image from
guest memory. A GPU-written image whose writes were not written back
loses them there: the new image holds the older guest bytes.

Expand a GPU-written image with as many levels as the request instead,
as ResolveOverlap already does for a same-format request with more
subresources: the new image is loaded from guest memory and the cached
image is copied into its first layers. With equal level counts a layer
starts at the same guest offset in both images, so the copy by index
keeps each layer in place. Other images are freed as before.
@simnJS

simnJS commented Nov 25, 2026

Copy link
Copy Markdown
Owner

The regression checks the byte pattern in the four old layers and the guest contents in the two new ones. There is still a new failure path for images that have both GPU writes and a subsequent CPU invalidation. MarkCpuDirty leaves the GPU-modified bit set, so the new condition can call ExpandImage on such a source. For MSAA, InitializeImage returns without clearing the CPU-dirty bit and RefreshCopySource stops the process. For compressed video-out, RefreshImage can stop even earlier. The previous lookup released the source. Could you restrict expansion to sources the cache can refresh or copy safely, and add a regression covering a GPU-written source invalidated before the larger request? Please keep the existing byte checks for supported sources.

A GPU-written image that a guest write invalidated keeps its GPU-modified
flag, so the fewer-resources branch of FindImageImpl also expands it.
ExpandImage refreshes the source first, and RefreshCopySource stops the
process when the refresh cannot clear the CPU-dirty state: InitializeImage
returns early for a multisampled image, and RefreshImage stops for a
compressed one.

Expand only single-sample uncompressed images, for which the refresh
clears the CPU-dirty state; free the others as before, including clean
multisampled and compressed ones. The new check covers a GPU-written
image invalidated before the larger request: with one sample the
expanded image holds the newer guest bytes in the old layers; with four
samples the lookup returns an image with the requested layers instead
of stopping in RefreshCopySource. The test device now enables
shaderStorageImageMultisample when supported and otherwise limits
storageImageSampleCounts to one sample, as VulkanCreateDevice does, so the
multisampled images the check creates are valid under the validation layer.
@SleglJan

Copy link
Copy Markdown
Contributor Author

Confirmed on 06f8888a38. InvalidateLocked reaches MarkCpuDirty for a GPU-written image (TryInvalidatePartial refuses GPU-modified images), and MarkCpuDirty leaves m_gpu_modified set, so the new condition expands such an image. For a multisampled source InitializeImage returns before RefreshComplete and RefreshCopySource stops; the new check, applied to 06f8888a38, reproduces that stop. For a compressed source RefreshImage stops first; that path is from reading the code.

9ca4f9888e expands only images whose refresh clears the CPU-dirty state: one sample (info and backing) and uncompressed (RefreshesAsCopySource). Other images are freed as before, including clean GPU-written multisampled and compressed ones.

CheckLargerRequestOverInvalidatedWrites makes a GPU-written 4-layer image, writes its guest backing and calls TextureCache::InvalidateMemory over that range, then requests 6 layers in a compatible format (B8G8R8A8 to R8G8B8A8; a same-format request expands in ResolveOverlap instead, a path this PR does not change). It asserts that the image is GPU-modified and CPU-dirty at the request. With one sample, the old layers hold the newer guest bytes and the new layers the guest contents. With four samples, the lookup returns an image with the requested layers; on 06f8888a38 this case stops in RefreshCopySource, while the one-sample case passes there too. A compressed source fails RefreshesAsCopySource and is freed; the test has no compressed case. The existing byte checks are unchanged.

The shim test device now enables shaderStorageImageMultisample when the device has it and otherwise limits storageImageSampleCounts to one sample, as VulkanCreateDevice does. With an earlier version of the check, before that change, the validation layer reported VUID-VkImageCreateInfo-usage-00968 for the multisampled images: ImageUsageFlags adds storage usage when storageImageSampleCounts contains the sample count, and the test device did not enable the feature.

Tests (AMD Radeon RX 9070 XT, RADV GFX1201, Mesa 26.2.6, Linux): the 110 tests that ctest -R '^(kyty_shim_.*|guest_gpu_fault|guest_host_write_filter|agc_kyty_shaders)$' selects (107 Kyty shim tests and the three others) give the same result per test on 06f8888a38 and on this commit, the alias test included; only this commit has the new cases. 107 pass, kyty_shim_rt_corpus is skipped, kyty_shim_wave64_cross_lane and kyty_shim_wave_split_written_reads fail on both. kyty_shim_image_write_back_alias passes with VK_LAYER_KHRONOS_validation, ANYPS5_REQUIRE_VULKAN=1 and ANYPS5_NO_SHADER_CACHE=1 and no validation messages, as on 06f8888a38. With the test change alone on 06f8888a38 it stops with "image copy source remained CPU-dirty after refresh". tools/check_conventions.py --base 7de61e3451 and tools/check_kyty_settings.py pass. The branch merges cleanly into the AnyKyty tip 441382ef20.

007 water smoke (one run, the #98 setup, a build of this commit plus a test-only counter line that is not part of the PR): the water is drawn, with the same detector value as this PR's earlier smoke runs, 28.62 FPS (28.61 and 28.93 there), no error exits. After 9,000 GC ticks the counter shows 2 images expanded by the new condition in FindImageImpl, none refused as multisampled or compressed.

AI-assisted: yes (Claude Code)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants