startup: cache translated graphics pipelines #1641
No reviewers
Labels
No labels
accessibility
awaiting author
bug
documentation
duplicate
enhancement
good first issue
help wanted
invalid
priority: P0
question
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/R0Y00--Xbox2Windows!1641
Loading…
Reference in a new issue
No description provided.
Delete branch "gh-pr/1641/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?
@lambirou on GitHub · 2026-11-24 15:34 UTC · original
lambirou:startup/pso-library-cache→main· +1112 −7 · 6 files · 3 commits · closed without mergingProblem
The translated startup draw path creates a desktop graphics PSO on every run and keeps only an in-process map. A cold run pays the driver's pipeline compile again, and the existing
X2W_SHADER_CACHEcovers translated shader bytecode but not the driver's pipeline blobs.XCL's public
CachedPSOwork (xcl shaders --precompile --pipelines) shows the shape, but this implementation is independent and uses the desktopID3D12PipelineLibraryAPI.Change
src/startup_stubs/graphics_pipeline_cache.h: an optionalID3D12PipelineLibrarycache underX2W_SHADER_CACHE\pso_<adapter>.lib.ID3D12Device::GetAdapterLuidandIDXGIFactory4::EnumAdapterByLuid; hash vendor, device, subsystem, revision and the UMD version. The LUID is not hashed because it can change across boots, but it is a fallback when no DXGI adapter is found.pipeline_forto tryLoadGraphicsPipelinefirst and fall back toCreateGraphicsPipelineStateon a miss, corrupt/truncated blob, driver/adapter mismatch or missingID3D12PipelineLibrary. A cache failure never fails a draw.Flush()at the end of each presented frame, outsidedraw_lock, serializes it once; destruction is the fallback. A version/adapter mismatch drops the old file and starts an empty library.startup_pso_cacheand document the behavior.Safety note:
ID3D12Device1::CreatePipelineLibrarydoes not copy the input blob; it keeps the pointer for the library's lifetime. The helper retains the file buffer untilDropLibrary/Shutdown. Any future change must preserve that ownership rule.Review response
Translation::code_key, so a translator output change cannot reuse an old driver pipeline under the same name. The key schema is bumped to 3.queue_presentcallsflush_pipeline_cache()outsidedraw_lock. A frame with new stores writes the library once; the destructor remains a fallback.adapter identity 3d82a583644e40a1; the value is derived from the device LUID's DXGI adapter and its UMD version. If no adapter is found, the LUID itself is hashed.StorePipelinereturningE_INVALIDARGis counted as a duplicate, not a new store, and no longer marks the library dirty.key * 131mix.translated_code_keyandpipeline_key: two translations with the same title key but different VS/PS bytes must produce different pipeline names.shared_ptrprotected by a mutex, so a present-threadFlush()keeps the old cache alive if the draw thread replaces it after a device change.0xff4080ffand their readbacks match.Verification
Result:
startup_pso_cache ok (library WARP); 1/1 passed. The batch line isPSO batch 8: uncached 2.87 ms, cached cold 2.52 ms (flush 1.35 ms), warm 0.88 ms. The padding control passes, the 36 semantic mutations pass, the adapter identity is not the seed, and the cold and warm pixels both readff4080ff. Five repeated CTest runs passed.docs_links_check.pychecked 18 Markdown files and 393 links;git diff --checkis clean.Rebased onto
origin/main(05092b6e); head591f556e. Windows checks pass on this head.Not tested
X2W_SHADER_CACHEand is not claimed as a speedup at title scale.ID3D12PipelineLibraryon older drivers; an unsupported interface disables the cache and uses the direct path.Reference:
ivall/xcl@930e8b4(xcl shaders --precompile --pipelines, #744), observed 2026-11-24. Public specification used: MicrosoftID3D12PipelineLibraryandD3D12_CACHED_PIPELINE_STATE. Independent implementation: the files above. No XCL code or tables are included.Licence
MIT, as the rest of the repository. The cache uses only the public Microsoft D3D12 API and contains no XCL code, tables, game files or third-party binaries.
AI use: implementation and first verification were drafted by a Codex subagent; the orchestrator reviewed the diff, rebased it, reran the build/CTest and five direct test runs.
@R0Y00 on GitHub · 2026-11-24 16:26 UTC · original
The cache helper covers warm lookup and fallback. In the production path, a cold miss currently serializes and flushes the entire pipeline library while draw_lock is held. Please measure cold-path serialization separately from warm hits on a source-built batch of several distinct PSOs, and include a cached/uncached pixel comparison. If the cold overhead is significant, coalesce persistence or keep disk persistence opt-in while gathering that comparison.
@lambirou on GitHub · 2026-11-24 18:45 UTC · original
@R0Y00 Ready for maintainer review.
Rebased onto
origin/main(578d1e1c); head9998541c; Windows checks pass.The WARP test passes cold, warm, corrupt, disabled and concurrent cases. The key now hashes blend/depth fields rather than raw structures, so ABI padding cannot change the cache name. Physical-GPU and warm-vs-cold load-time measurements remain untested. No game data.
@lambirou on GitHub · 2026-11-24 19:08 UTC · original
Addressed the P2 and the owner's cold-path request on head
a71f8fc5.RenderTargetWriteMaskfrom the hash fails the test.Flush()or destruction serializes it once. The draw path no longer rewrites the whole library per PSO.0xff4080ff, and their readbacks match.Windows checks pass on this head.
@lambirou on GitHub · 2026-11-24 20:45 UTC · original
Addressed the P2 findings on head
f9a88f54.Translation::code_key; schema 3.queue_presentcallsflush_pipeline_cache()outsidedraw_lock; the destructor remains a fallback.GetAdapterLuidandIDXGIFactory4::EnumAdapterByLuid. On WARP the test printsadapter identity 3d82a583644e40a1, not the constant seed. The LUID is only a fallback.StorePipelinereturningE_INVALIDARGis counted as a duplicate, not a new store.The startup_pso_cache test passes 1/1, the 36 field mutations pass, and Windows checks pass on this head.
@tedin7 on GitHub · 2026-11-25 12:53 UTC · original
@lambirou could you rebase this branch onto current
mainand force-push?GitHub reports head
591f556eas conflicting withmain, so it cannot be merged as is.Files that conflict with current
main(cf97bee1):src/startup_stubs/d3d12_draw.inlCommands run locally:
Once it is rebased and CI is green it will be re-checked right away.
AI-assisted; commands listed were executed locally.
@tedin7 on GitHub · 2026-11-24 15:47 UTC · original · reviewed
Reviewed
46a0816df2a957bc23c9fac36fb79fe36cc3f68e:src/startup_stubs/graphics_pipeline_cache.h:OpenLibraryretainsblob_for the lifetime ofID3D12PipelineLibraryandDropLibraryreleaseslibrary_before freeingblob_, respecting theCreatePipelineLibrarypointer-lifetime contract. Header validation checks magic ("XSP1"), version, header size, adapter/driver identity (vendor, device, subsys, revision, UMD version), bounded payload size (<= 256 MiB), and FNV-1a checksum; any mismatch orD3D12_ERROR_DRIVER_VERSION_MISMATCH/D3D12_ERROR_ADAPTER_NOT_FOUNDdrops the file and falls back cleanly toCreateGraphicsPipelineState.src/startup_stubs/d3d12_draw.inl:pipeline_forfoldstr.key(including translator revision),target_count,target_formats[],dsv_format,has_blend/blend, andhas_depth_stencil/depth_stencilinto the lookup key, and resetspipeline_cache_forif theID3D12Device*changes.tests/startup_pso_cache_check.cpp: covers cold store + file creation, warm hit in a freshGraphicsPipelineCacheinstance, truncated/corrupt blob recovery, disabled-library fallback, and 4-thread concurrent creation/lookup on WARP.pipeline_cache_forinsrc/startup_stubs/d3d12_draw.inluses unsynchronized function-localstaticvariables (cache,owner), thoughpipeline_foritself already accessesbound.pipelineswithout locking (single-threaded draw path);GraphicsPipelineCacheitself isSRWLOCK-synchronized.python3 tests/docs_links_check.py— passed (Checked 16 Markdown files and 348 links.)python3 tests/bidi_controls_check.py— passed (Checked 1267 tracked source, script and build/CI files: no bidirectional controls.)cmake --build --preset dev --target startup_pso_cache_check d3d12_xs_shim -- -j 6+ctest --preset dev -R '^startup_pso_cache$' --parallel 4 --no-tests=error --output-on-failure): 1/1 passed./O2(cmake --build --preset release --target startup_pso_cache_check d3d12_xs_shim -- -j 6+ctest --preset release -R '^startup_pso_cache$' --parallel 4 --no-tests=error --output-on-failure): 1/1 passed.AI-assisted; commands listed were executed locally.
@tedin7 on GitHub · 2026-11-24 17:18 UTC · original · reviewed
Re-review at
head_sha:9998541ce47e192cab5fda6862ebc9f309147ca2(previously reviewed at46a0816d).Findings
P2 (test gap): the new key-hash control cannot detect a field being left out of the key (
tests/startup_pso_cache_check.cpp,hash_padding_ignored)D3D12_BLEND_DESC/D3D12_DEPTH_STENCIL_DESCbytes (ABI padding could be uninitialized and give different cache names across runs).hash_blend_keyandhash_depth_stencil_keynow hash the semantic fields one by one, the key schema goes from 1 to 2, and a padding control was added. That design is right, and today the functions do cover every field of both structs (I counted againstd3d12.h: 2 + 10 x 8 blend fields, and 6 + 4 + 4 depth/stencil fields).RenderTarget[0].SrcBlendandFrontFace.StencilFunc. Hand-written hashing like this is exactly where a field gets dropped later, and then two different blend or depth states map to the same cached pipeline, i.e. a wrong pipeline is reused silently.hash_padding_ignoredand the twostatic_asserts into a small program that includes the unchangedgraphics_pipeline_cache.h. Unmodified: PASS. Withreturn hash_stencil_ops_key(depth.BackFace, key);replaced byreturn key;: still PASS. With theRenderTargetWriteMaskline removed fromhash_blend_key: still PASS. Expected: FAIL for both.Other changes in the new commit, no issue
hash_blend_key/hash_depth_stencil_key(usingdeclarations ind3d12_draw.inl), thehas_blend/has_depth_stencilbits are still folded in, and the schema byte is bumped so old key names are not reused.static_asserts document the padding the control relies on. They hold for the MinGW-w64 layout I built with; I did not check the MSVC layout, but the same ABI padding is what the PR text describes.git merge-treeagainst currentmain(bc65bb1b) reports no conflicts (treea0fc9b67).Verified
Limits: Linux x86-64 only.
startup_pso_cache_checkneeds a D3D12 device (WARP), so I did not run the whole test or the pipeline-library parts (cold store, warm hit, corrupt blob, concurrency). I only ran the device-free hash control, cross-built withx86_64-w64-mingw32-g++ -std=c++17 -O1 -staticand run under Wine, not MSVC.hash_padding_ignored: PASS.hash_blend_key, the per-field hashing ofBlendEnablereplaced by hashing the wholetargetstruct (padding included):hash_padding_ignored: FAIL. So the padding half of the control works.RenderTargetWriteMaskdropped, as above.git checkout -- .;git status --shortclean.AI-assisted; commands listed were executed locally.
@tedin7 on GitHub · 2026-11-24 19:22 UTC · original · reviewed
Review at
a71f8fc5f6a8aa83d6d3faf618d3a451a7579878(comment only, not an approval).What I checked
origin/main(d3d12_draw.inl,graphics_pipeline_cache.h, the test, CMake, docs).Commands run on this branch (Linux)
x86_64-w64-mingw32-g++ -std=c++17 -fsyntax-onlyongraphics_pipeline_cache.h: compiles.hash_blend_keyandhash_depth_stencil_key: 12 checks pass. Padding bytes set to 0xAA versus 0 give the same key. Flipping AlphaToCoverage, IndependentBlend, RT7 LogicOp, RT3 write mask, RT0 BlendOpAlpha, RT1 DestBlendAlpha, DepthFunc, StencilWriteMask, BackFace func or FrontFace depth-fail op each changes it.LogicOpfrom the blend hash, and droppingBackFacefrom the depth hash.startup_pso_cache_checkand anything D3D12. The Windows runner (x2w_pipe.py win2025) was blocked by a local command guard in this session, so there is no Windows result from me. I did not run the WARP test.P2: the key does not cover the translated bytecode
d3d12_draw.inl:436-446.tr.keyis a hash of the title's shader words and root signature plus the stringx2w-startup-shader-4(d3d12_draw.inl:201). The desktop VS and PS (tr.vs,tr.ps, line 451) come fromgfx2hlsl.pyand DXC, and are not in the key. If the translator output changes and nobody bumps that string, the library can hold a pipeline built from the old bytecode under the same name. I could not confirm whetherLoadGraphicsPipelinerejects a description whose shaders differ; the documentation I know does not promise it. Hashingtr.vsandtr.psbytes into the key is cheap and removes the dependency on a manual bump.P2: the library is persisted only at process shutdown
Flush()(graphics_pipeline_cache.h:208) is called only from the test. In the product the only write isPersistLibrary()fromShutdown(), reached by the destructor of the function-staticunique_ptr(d3d12_draw.inl:415). That runs at process or DLL teardown, where D3D12 may already be unloaded, and not at all if the title ends the process abruptly. In both cases the cache file never appears and the feature does nothing, while the doc says stores are coalesced and flushed. Suggest an explicit flush at a safe point (device release or a frame or time threshold).Related: the cache holds a device reference from a static (
graphics_pipeline_cache.h:178), so the device outlives the title's own release until teardown.P2: adapter and driver identity is probably the constant seed
graphics_pipeline_cache.h:85.adapter_identityqueriesIDXGIDeviceon anID3D12Device. As far as I know a D3D12 device does not implementIDXGIDevice, so the query fails and the hash stays at the seedx2w-pso-cache-v1for every GPU and driver. Safety still holds, becauseCreatePipelineLibraryrejects a foreign blob and the code deletes it and starts empty. But the docs and comments promise vendor, device, revision and UMD identity in the file name and header. I could not run this here; please confirm on the Windows node, for example by printing the identity for WARP and a hardware adapter. If it is constant, useGetAdapterLuidplusEnumAdapterByLuid, or theDXGI_ADAPTER_DESCof the adapter the device was made on.P3
graphics_pipeline_cache.h:279:StorePipelinereturningE_INVALIDARG(name already stored) is counted as a successful store and marks the library dirty. It should be counted separately; a same-name duplicate with a different pipeline would otherwise be silent.d3d12_draw.inl:413-427:pipeline_cache_forresets the static cache when the device pointer changes, with no lock. This is fine if draws are single-threaded, asbound.pipelinesalready assumes, but the cache has its own SRW lock, which suggests concurrent use is expected.d3d12_draw.inl:438-441: the key mixeskey * 131 + formatwith FNV; a 64-bit hash with no desc comparison of its own relies on the library's own validation on a collision.Verdict
No functional break found in the paths I could read or run, and the field-by-field hashing is right. I would fix the two P2 points (bytecode in the key, and when the library is written) before merge, and confirm the third on Windows.
AI-assisted; commands listed were executed locally.
@tedin7 on GitHub · 2026-11-24 21:31 UTC · original · reviewed
Re-review at head
f9a88f54759e100fd6ec056cd7cf323011f3b183(previous reviews at46a0816d,9998541c,a71f8fc5).Verdict: no P1. The P2 about the shader bytecode missing from the key is fixed. One new P2 (thread safety of the cache pointer), one P3.
What changed since
a71f8fc5(PR-only diff compared)d3d12_draw.inl:Translation::code_key=tr.key+ FNV of the translated VS and PS bytes, used inpipeline_for(schema 3); target formats are hashed withfnv_bytesinstead ofkey * 131 +. This closes the old gap where changed translator output kept the same cache name.graphics_pipeline_cache.h: adapter located throughGetAdapterLuid+IDXGIFactory4::EnumAdapterByLuid(LUID only as fallback hash, version stringx2w-pso-cache-v2);E_INVALIDARGfromStorePipelineis now counted asduplicatesinstead of a store.flush_pipeline_cache()is called fromqueue_present(d3d12_xs_device.cpp:3318), so a cold batch is written once per presented frame.tests/startup_pso_cache_check.cpp~280-335, single-field changes on blend, depth and both stencil faces).P2: unsynchronized
cache/ownerstatics are now read from a second lock domaind3d12_draw.inl:461-471(pipeline_cache_for) and the newflush_pipeline_cache()right below it. The draw path reachespipeline_cache_forunderdraw_lock;flush_pipeline_cache()is called fromqueue_presentoutsidedraw_lock(by design, per the comment). If theID3D12Device*changes (owner != device), the draw thread doescache.reset(new ...)while the present thread may be insidecache->Flush()on the old object, which is a use-after-free window. The earlier review called the unlocked statics a minor note while only one lock domain touched them; adding a second caller outside the lock makes it a real, if narrow, race. Fix: takedraw_lock(or a small dedicated lock) around the pointer read and swap, or keep the old cache alive until both paths are done with it.P3
code_keywiring inpipeline_forhas no test:startup_pso_cache_checkexercises the cache helper only, so dropping thecode_keyline leaves every test green. A small control that two translations with different VS/PS bytes and the sametr.keygive different pipeline names would pin the fix.Commands run locally
git diff --check origin/main...HEAD: exit 0.docs_links_check.py: 18 files, 376 links.bidi_controls_check.py: 1337 files, clean.x86_64-w64-mingw32-g++ -std=c++17 -fsyntax-onlyongraphics_pipeline_cache.h: compiles (only the#pragma once in main filewarning).^startup_pso_cache$: Debug 1/1 and Release /O2 1/1 passed.Mutations (mingw build run under wine, reverted with
git checkout -- .)A small harness built against the unchanged
graphics_pipeline_cache.hchanges one blend or depth field at a time and requires a different key: unmodified, 0 unchanged out of 12 cases.LogicOpfromhash_blend_keyRenderTargetWriteMaskfromhash_blend_keyhash_depth_stencil_keyreturns beforeBackFaceAI-assisted; commands listed were executed locally.
@tedin7 on GitHub · 2026-11-25 02:16 UTC · original · reviewed
Review of head
591f556e221baa64938f3221afde3ec46dd28e69(comment only).Scope: PSO library cache for translated pipelines (
graphics_pipeline_cache.h,d3d12_draw.inl, present hook, newstartup_pso_cache_check, docs, CMake).Commands executed locally (Linux worktree of the PR head):
git diff --stat origin/main...HEAD-> 6 files, +1112/-7python3 tests/docs_links_check.py-> Self-test passed; Checked 18 Markdown files and 393 linkspython3 tests/bidi_controls_check.py-> no bidirectional controls in 1414 filesgit diff --check origin/main...HEAD-> cleangh pr checks 1641-> Windows build+test pass (ctest: 100% tests passed out of 30), Linux Python checks pass, gfx1013 fixtures pass; /O2 job skippedThe new test and the cache code are Windows/D3D12 only, so the Linux tests touched are none. I did not run a Win2025 job and I did not run a mutation of the new logic. I read the code only. The Windows CI result above is the runtime evidence.
Findings: no P1, no P2.
What I checked and found sound:
pipeline_keyhashes code key (translation key + VS/PS bytes), target count and formats, DSV, blend/depth presence and the fields of both blocks one by one, so padding cannot change the name. Schema byte and adapter identity are mixed in. The old key ignored blend state and shader bytes; the new one fixes that.ID3D12Device1ends in a directCreateGraphicsPipelineState. A cache failure never fails a draw.CreatePipelineLibrary; the blob stays alive as long as the library; the write is atomic through a temp file.shared_ptrkeeps the old cache alive across a device change, and the cache holds its own device reference, so theownerpointer cannot be reused while it is set.Nits (non blocking):
graphics_pipeline_cache.h(GetOrCreateGraphicsPipeline): ifLoadGraphicsPipelinereturnsE_INVALIDARGbecause the desc differs from the stored one (rasterizer, topology or input layout are not in the key), the laterStorePipelinealso returnsE_INVALIDARGand is counted as a duplicate. The stale entry then stays forever and that PSO is rebuilt on every run. A comment, or a key that includes those fields, would make this explicit.Flush()serializes and writes the file while holding the cache lock, so a draw thread that creates a new PSO at that moment waits for the disk write. It is once per presented frame with new stores, so it is small, but worth knowing.DeleteFileW/OpenEmptyLibraryafter a driver mismatch is not logged; only the counter changes.AI-assisted; commands listed were executed locally.
@Leyukaka on GitHub · 2026-12-01 21:54 UTC · original
@lambirou, the pipeline library cache in this PR still looks useful: as your description notes, cold runs still pay the driver pipeline compile again, and
X2W_SHADER_CACHEonly covers the translated bytecode.Do you plan to reopen it after a rebase? If not, would you be fine with me carrying it forward on current
main? I would keep your commits and authorship, resolve thed3d12_draw.inlconflict, rerun the WARP cold, warm, corrupt, disabled and concurrent cases, and link the new PR here.@Leyukaka on GitHub · 2026-12-02 08:12 UTC · original
@lambirou, thank you for this work. I carried it forward on current
mainin #3839, with your three commits and authorship kept and one commit on top for the rewrittenpipeline_for. If you prefer to continue it yourself, tell me and I will close mine.Pull request closed