graphics: prototype native GPU PerVertex replay and shader caches #715
No reviewers
Labels
No labels
bug
documentation
duplicate
enhancement
GPU
GUI
help wanted
question
Shaders
Video
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/KytyPS5--KytyPS5!715
Loading…
Reference in a new issue
No description provided.
Delete branch "gh-pr/715/head"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
@carbonimax on GitHub · 2026-09-19 10:28 UTC · original
carbonimax:codex/native-pervertex-cache→main· +6233 −1397 · 60 files · 22 commits · closed without mergingCurrent status — draft (2026-10-01)
This is the historical opt-in Kyty-side prototype. The current integration work uses generic PerVertexKHR support in an isolated MoltenVK/SPIRV-Cross build, with the public extension still closed and a restricted experimental contract. The Kyty prototype is disabled in that integration. This PR is retained as a draft for its implementation and regression evidence; it is not currently proposed for merging. The evidence below applies to the historical prototype and does not establish complete Vulkan support or qualify the new integration.
The opt-in PerVertex path lowers vertex/fragment shaders in native C++, unpacks and captures vertices on the GPU, and replays per-corner values. Transformed SPIR-V and Vulkan driver pipelines are cached persistently. Rebuilt entry-point interfaces preserve descriptor arrays,
OpArrayLength, push constants, and private globals when moving to SPIR-V 1.5.This update handles two input layouts encountered during startup of the game: more than eight attributes, and an unsigned integer attribute previously receiving a float
OpStore. The unpack descriptor now fits twelve attributes in the same 128-byte push-constant block. Signed/unsigned 8/16/32-bit components retain their bits, integer defaults and sign extension; capture stores use the original scalar/vector type. The observed failing format wask16_16_16_16UInt.Scope
KYTY_PER_VERTEX_PROTOTYPE=1.Validation
The isolated branch includes upstream
mainat8b095ca. On macOS x86_64/Rosetta:kyty_emulator,shader_cfg_tests,per_vertex_transform_tests, andper_vertex_gpu_execution_testsbuild.per_vertex_transform_tests: exit 0.shader_cfg_tests --per-vertex: exit 0, including CPU integer decoding and defaults.per_vertex_gpu_execution_tests: exit 0 on Apple M4 Pro with the mesh-capable MoltenVK build. Covers ten/twelve attributes, signed/unsigned widths 1–4, 8/16/32-bit components, out-of-bounds defaults, typed capture SPIR-V, full synthetic capture/replay, and cache checks.shader_cfg_testssuite stops earlier at the existingwide-bufferSPIR-V size budget: 923 words / 233 instructions versus limits of 807 / 211. A full-suite pass on the updated isolated branch is not claimed.Integration evidence and limits
An integration checkout containing other pending fixes passes the intro and title screen, accepts input, and displays the save-slot selection screen. The previously failing integer-input shader now validates and submits draws. After selecting New Game, execution stops at a separate image-view minimum-LOD requirement unsupported by the current MoltenVK build. Two save-card models also show black horizontal stripes; visual correctness and playability are not confirmed.
These integration observations do not establish that this PR alone boots the game. Related integration fixes include #633, #640, #643, #685, #721, #727, #735, #741, and #761. This PR does not add a minimum-LOD workaround or include local storage-backing diagnostics.
@coderabbitai[bot] on GitHub · 2026-09-19 20:41 UTC · original · edited 2026-10-01 16:05 UTC
📝 Walkthrough
Walkthrough
Adds a GPU-native per-vertex rendering prototype. The change transforms vertex and fragment shaders, embeds unpack and replay SPIR-V, executes supported draws through compute and graphics pipelines, and adds disk and driver-cache handling. Pipeline descriptors and draw routing support prototype programs. CPU, GPU, cache, shader-detection, CMake, and CI test coverage is added.
Suggested reviewers:
nmzikPriority: ➖ Normal
Change: Feature
Merge Risk: 🟡 Moderate · up to
54855The optional rendering path still fails on reachable shaders and draw configurations. These issues should be fixed or explicitly accepted before merge.
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Docstring Coverage
Explanation
Docstring coverage is 6.98% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 86 functions across 15 files. (4 skipped: 3 unsupported, 1 too large.)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share
Comment
@coderabbitai helpto get the list of available commands.@coderabbitai[bot] on GitHub · 2026-09-19 20:41 UTC · original
On
CMakeLists.txtline 390 (outdated):🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 13292
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 48655
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 13028
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 13849
Guard
per_vertex_gpu_execution_testson Apple platforms.EXCLUDE_FROM_ALLdoes not make an explicitly requested target portable. The supported Windows toolchain cannot compilePerVertexGpuExecutionTests.cppbecause it includes POSIX-only<dlfcn.h>. Define this Apple/MoltenVK test only whenAPPLEis true.♻️ Proposed guard
📝 Committable suggestion
@ -0,0 +61,4 @@std::map<uint64_t, Original> originals;std::map<std::pair<uint64_t, uint64_t>, PerVertexPrototypePrograms> variants;PerVertexUnpackPipeline s_unpack_pipeline {};bool s_unpack_initialized = false;@coderabbitai[bot] on GitHub · 2026-09-19 20:41 UTC · original
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 21204
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 50371
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 50371
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 28760
Bind the per-vertex caches to the
GraphicContextlifetime. WhenKYTY_PER_VERTEX_PROTOTYPEis enabled, a qualifying draw populates the process-globalvariantsands_unpack_pipelinecaches. These values contain Vulkan handles, butRenderContextandPipelineCacheteardown does not destroy them. The handles therefore remain allocated after context teardown and can leak until device or process teardown. Add a lifecycle reset that destroys all cached handles with the owningGraphicContext::device, clears both maps, and resetss_unpack_initializedbefore device teardown. The cache keys also contain no device identity, so they must not be reused across devices.@ -0,0 +300,4 @@static_cast<unsigned long long>(key.first),static_cast<unsigned long long>(key.second));return nullptr;}@coderabbitai[bot] on GitHub · 2026-09-19 20:41 UTC · original
🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win
Cache the rejection so an unsupported pair is analysed only once.
When
DerivePerVertexLayoutfails, the function returnsnullptrwithout recording anything invariants.ExecutePreparedDrawcallsGetPerVertexPrototypeProgramson every draw whose first vertex stage is a logical vertex stage. Each of those calls re-runs twospvtools::SpirvTools::Disassemblepasses over the full vertex and pixel modules, then the regex scans inDerivePerVertexLayout.For a title whose per-vertex pixel shader is not supported, this repeats per draw call, per frame.
Record the rejection in a negative-result set keyed by the same
{vs.id, ps.id}pair and returnnullptrimmediately on later calls.@ -0,0 +44,4 @@// Obtain vertex buffer from GPU cache without host readbackconst uint64_t vtx_total_bytes = static_cast<uint64_t>(input.stride) * input.num_records;auto [vtx_buf_ptr, vtx_offset] = cache.ObtainBuffer(input.addr, vtx_total_bytes, false);@coderabbitai[bot] on GitHub · 2026-09-19 20:41 UTC · original
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Clamp the vertex-buffer range before obtaining the buffer.
Line 44 computes
vtx_total_bytesdirectly from the guest descriptor fieldsinput.strideandinput.num_records, then passes it tocache.ObtainBuffer. A guest descriptor can declare a record count far larger than the mapped region.The standard vertex path guards this.
AcquireVertexBuffersinrenderDraw.cpppasses every range throughLibs::LibKernel::Memory::ClampRangeSizebefore callingObtainBuffer. This prototype path skips that step, so a malformed or simply large descriptor requests an oversized host allocation.Apply the same clamp here.
🛡️ Proposed fix
📝 Committable suggestion
@coderabbitai[bot] on GitHub · 2026-09-19 20:41 UTC · original
On
src/graphics/host_gpu/renderer/perVertexPrototypeDraw.incline 239 (outdated):🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win
The capture pass dispatches one invocation per workgroup.
LowerVertexToComputeemitsOpExecutionMode <main> LocalSize 1 1 1, so this dispatch createscountworkgroups that each run a single invocation. Withcountbounded at 65535 by line 34, that is up to 65535 workgroups per draw. GPUs schedule at wavefront granularity, so 63 of every 64 lanes idle.The unpack pass at line 220 already uses
LocalSize 64 1 1with(count + 63) / 64groups. Apply the same shape to the capture shader: emitLocalSize 64 1 1, derive the invocation index fromgl_GlobalInvocationID.x, and add an early return when the index reachestotal_invocations.@coderabbitai[bot] on GitHub · 2026-09-19 20:41 UTC · original
On
src/graphics/host_gpu/renderer/perVertexTransform.cppline 283 (outdated):🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Attribute widths assume contiguous
%in_attr_Nindices.Line 261 sizes
attr_widthsbynum_attrs, and the loop at line 262 probes%in_attr_0through%in_attr_{num_attrs-1}. The set of indices actually found comes fromattr_indices, which is sorted but never checked for contiguity. If the source declares%in_attr_0and%in_attr_2,num_attrsis 2,%in_attr_1is not found soattr_widths[1]keeps the default 1, and%in_attr_2receives noOpStoreat all. The capture pass then reads an uninitialized attribute.The vertex-buffer guard in
perVertexPrototypeDraw.incchecksinput.attr_indices[i] == i, but that constrains buffer slots, not the shader-side%in_attr_Nnumbering.Reject the shader when
attr_indicesis not exactly0..num_attrs-1.🛡️ Proposed guard
@ -0,0 +513,4 @@}if (l == "OpReturn" || l == " OpReturn") {out_lines.insert(out_lines.end(), end.begin(), end.end());}@coderabbitai[bot] on GitHub · 2026-09-19 20:41 UTC · original · edited 2026-09-20 11:34 UTC
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 14116
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 31410
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 14346
Scope capture setup and epilogue to
main_name.LowerVertexToComputeinsertsstartafter the firstOpLabelandendbefore every matchingOpReturn. If the module contains a helper function, capture instructions can be inserted into that helper. The transformed module can then use function-local IDs across functions and fail assembly or validation. If the helper appears first,main_namecan also receive nostartblock.Track the enclosing entry function and require that state for both
startandendinsertion.🐛 Proposed fix to scope setup and epilogue to the entry function
✅ Addressed in commit
7fe93a8@ -1042,0 +1053,4 @@primitive_restart_enable);return;}}@coderabbitai[bot] on GitHub · 2026-09-19 20:41 UTC · original
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
🔎 Supported by static analysis
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 10963
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 17899
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 1027
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 983
Guard prototype eligibility before routing.
ExecutePreparedDrawselectsExecutePerVertexPrototypewhen the vertex stage is logicalVertexandGetPerVertexPrototypeProgramsreturns a program. The cached shader pair can then be used by a draw that fails the prototype's checks, including non-eTriangleListtopology, primitive restart, multiple vertex buffers, unsupported attributes, or a vertex-instance count above65535. In non-KYTY_FINALbuilds, those checks callEXIT_IF, which invokes the exit handler instead of allowing the standard draw path. InKYTY_FINALbuilds,EXIT_IFis disabled, so the prototype path receives unsupported input without these guards. Move the reusable eligibility checks into a boolean predicate and route to the prototype only when it returnstrue. Keep theEXIT_IFchecks inExecutePerVertexPrototypeas defensive checks.🐛 Proposed structure for the routing decision
CanExecutePerVertexPrototypeshould contain the draw-dependent checks currently written asEXIT_IFinperVertexPrototypeDraw.inclines 11-34 and returnfalsewhen a check fails.📝 Committable suggestion
@coderabbitai[bot] on GitHub · 2026-09-19 20:41 UTC · original · reviewed
Actionable comments posted: 8
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
Review profile: CHILL
Plan: Advanced
Run ID:
077e0695-fdc9-4a07-8313-b1eeecba40bf📥 Commits
Reviewing files that changed from the base of the PR and between
f100f785daanddd958d02ba.📒 Files selected for processing (21)
.github/workflows/build.ymlCMakeLists.txtsrc/common/threads.cppsrc/common/threads.hsrc/generate_version.cmakesrc/graphics/host_gpu/renderer/perVertexEmbeddedSpv.hsrc/graphics/host_gpu/renderer/perVertexPrototype.cppsrc/graphics/host_gpu/renderer/perVertexPrototype.hsrc/graphics/host_gpu/renderer/perVertexPrototypeDraw.incsrc/graphics/host_gpu/renderer/perVertexTransform.cppsrc/graphics/host_gpu/renderer/perVertexTransform.hsrc/graphics/host_gpu/renderer/pipeline/descriptors.cppsrc/graphics/host_gpu/renderer/pipeline/pipelineCache.cppsrc/graphics/host_gpu/renderer/pipeline/pipelineCache.hsrc/graphics/host_gpu/renderer/pipeline/shaders.cppsrc/graphics/host_gpu/renderer/render.hsrc/graphics/host_gpu/renderer/renderDraw.cppsrc/kytyGitVersion.h.intests/PerVertexGpuExecutionTests.cpptests/PerVertexTransformTests.cpptests/shaderCfgTests.cppIncluded review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
@carbonimax on GitHub · 2026-09-20 02:34 UTC · original
Follow-up
7d17838adds the exact PerVertex input format observed in the game:0x47(k16_16_16_16Float), four 16-bit components at attribute offset 20 with stride 28.The change keeps the scope to Float16 only, generates the unpack SPIR-V from checked-in GLSL, and covers signed zero, subnormal, normal, infinity, and NaN conversion on CPU plus finite Float16 fixtures on MoltenVK.
Validation on an isolated checkout of this PR:
kyty_emulator,shader_cfg_tests,scalar_provenance_tests,per_vertex_gpu_execution_testsspirv-val --target-env vulkan1.2: passedA bounded integration run reached GPU completion of the first PerVertex draw without DeviceLost. That runtime proof also included other open integration changes, so it does not by itself qualify this PR in isolation. The black screen remains and the later subgroup-function failure is a separate issue.
@coderabbitai[bot] on GitHub · 2026-09-20 20:24 UTC · original · reviewed
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
Review profile: CHILL
Plan: Advanced
Run ID:
dbe9c80f-b114-483a-8d47-8244e1eedbc7📥 Commits
Reviewing files that changed from the base of the PR and between
7fe93a8f09and548553ae5c.📒 Files selected for processing (12)
.github/workflows/build.ymlCMakeLists.txtsrc/common/threads.hsrc/graphics/host_gpu/renderer/perVertexPrototypeDraw.incsrc/graphics/host_gpu/renderer/perVertexTransform.cppsrc/graphics/host_gpu/renderer/pipeline/pipelineCache.cppsrc/graphics/host_gpu/renderer/pipeline/pipelineCache.hsrc/graphics/host_gpu/renderer/render.hsrc/graphics/host_gpu/renderer/renderDraw.cpptests/PerVertexGpuExecutionTests.cpptests/PerVertexTransformTests.cpptests/shaderCfgTests.cppIncluded review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
@coderabbitai[bot] on GitHub · 2026-09-20 20:24 UTC · original
On
src/graphics/host_gpu/renderer/perVertexTransform.cppline 423 (outdated):🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift
Declare the narrow vector result type instead of assuming
%v2float/%v3floatexists.OpVectorShuffleneeds a result type id. Line 421 builds that id as"%v" + width + "float", which relies on the disassembly friendly name of anOpTypeVector %float 2or%float 3declaration in the source module. A vertex shader with onlyvec4and scalar attributes declares no 2- or 3-component float vector, so the id is undefined andtools.Assemblefails. InKYTY_FINALbuilds theEXIT_IF(!tools.Assemble(...))guard inperVertexPrototype.cppis compiled out, so the path continues with empty bytecode.Emit the needed vector types under
%capture_names, and deduplicate them against the source the same way%capture_uvec2/%capture_uvec3are handled at lines 502-516.🐛 Sketch of the fix
Then reference
%capture_vec<w>in theOpVectorShuffle, and reuse the existing replacement loop pattern to drop the declaration when the source already declares that type.@Cosmo on GitHub · 2026-09-25 17:46 UTC · original
Wouldn't it be better to implement this as a MoltenVK PR?
@carbonimax on GitHub · 2026-09-26 11:57 UTC · original
I agree that generic PerVertexKHR support would be better implemented in MoltenVK/SPIRV-Cross. The current PR is an opt-in application-side prototype with a restricted draw contract, so it would need to be generalized rather than moved unchanged.
MoltenVK already has vertex-output capture machinery for tessellation, which looks like a useful starting point to investigate. A sensible next step would be to extract a standalone Vulkan reproducer and assess an upstream implementation. Kyty-specific input handling and application-side caching could remain separate.
Would you prefer keeping this PR as a draft while that approach is investigated?
@carbonimax on GitHub · 2026-10-01 16:05 UTC · original
@Cosmo Following up on the direction discussed above: this PR is now a draft. The active work has moved to generic PerVertexKHR support in MoltenVK/SPIRV-Cross; the application-side prototype is disabled in the current Kyty integration. That implementation remains experimental, with the public extension closed and no claim of complete Vulkan conformance.
The branch and its historical tests remain available. The PR description now separates that prototype evidence from the current integration, so it should not be treated as ready to merge.
@wuboo on GitHub · 2026-10-02 19:28 UTC · original · edited 2026-10-02 19:43 UTC
Thanks for this stack. I have been running Astro Bot (PPSA21564) on it on an M3 Max (macOS 26, Rosetta 2, MoltenVK) and profiling the first minutes of a new game. Some notes that may save you time.
Fix you may want: 16 vertex attributes in the prototype unpack. The unpack push constants are sized for Vulkan's 128-byte minimum (12 attribute descriptors), so a VS with 15 attributes exits. Astro Bot hits this right after the intro. MoltenVK allows 4096 bytes. The patch widens the descriptor array to 16, grows the packed count from 4 to 5 bits so 16 does not wrap to 0, and skips a draw past 16 (logged once per hash) instead of exiting. One commit on top of this PR's head (
33a30b4c), with tests updated:github.com/wuboo/KytyPS5@575d3b9a(branchwuboo:pv-prototype-16-attributes).per_vertex_transform_testspass on that branch; the GPU execution test passed on my integration stack.Where the GPU time goes (first level, after fixing the SSE4a traps, see #839):
pv-unpack→pv-capture→ replay pass per draw) carries about 75–85% of GPU time per frame: ~290 prototype draws and ~9.5 M "vertices" per flip in the heavy part of the level. Per-command-buffer timestamps put it at roughly replay 120 / capture 72 / unpack 64 ms per flip. MoltenVK only samples timestamps at encoder boundaries, so this is per-stage, not per-shader.v_interp_movP10/P20. Most of these are manual interpolation of packed f16/snorm16 halves, mixed with ordinaryGetAttribute. MoltenVK's SPIRV-Cross rejectsPerVertexKHRin MSL, so a native path is not available.Things that did not help, measured A/B on the same binary:
SET_UCONFIG_REG_INDIRECT/INDEX. Keeping them open halved the passes for +3%. Skipping the flush on UCONFIG writes also broke rendering.What did correlate with frame rate was the number of prototype draws itself (dropping two VS hashes worth of draws gave +55%). My current guess is the dependent compute → compute → render transitions per draw, roughly 870 per frame, rather than shader cost. I'm measuring barrier counts next and will report back if grouping the compute stages of consecutive draws helps.
@wuboo on GitHub · 2026-10-06 04:34 UTC · original
Follow-up from macOS (M3 Max, Rosetta 2, MoltenVK), Astro Bot: a change on top of the prototype path that measurably helps here, in case it's useful for this PR.
Fused unpack into capture. Today every prototype draw runs an unpack dispatch that decodes the VS vertex attributes into an
attribute_buffer(plus anid_buffer), a barrier, then the capture dispatch that reads them back. With the change, the capture shader decodes the V#/format and the index itself from the raw guest buffers. That removes per draw one dispatch, one barrier, one descriptor set and two transient buffer allocations. VertexIndex/InstanceIndex are computed in the shader.Commits (two, on our macOS stack, behind
KYTY_OPT_ON=pv_fused_unpack, default off):wuboo:pv-fused-unpackCorrectness: a GPU test compares the capture records of the old and new paths bit for bit for 7 draw shapes (linear, indexed 16-bit, instancing, first_vertex, negative and positive vertex_offset, out-of-range vertices) × 4 formats (float32x3, unorm8x4, unorm16x2, half4). Frame diffs in the game show no regression; scene-to-scene differences we saw were timing, not image changes.
Performance (two off/on pairs per scene, same power conditions):
On this host the gain comes mostly from the CP thread (fewer allocations/dispatches per draw under Rosetta), not from GPU time. It may matter less on native x86, but the per-draw work it removes is the same.
@carbonimax on GitHub · 2026-10-10 22:57 UTC · original
Closing: superseded by the MoltenVK/SPIRV-Cross PerVertexKHR work (KhronosGroup/MoltenVK#2858, KhronosGroup/SPIRV-Cross#2699). The branch stays available for reference.
Pull request closed