From 8fb2bdea47beada1098407dd08e5ffff6c3098f3 Mon Sep 17 00:00:00 2001 From: Logan <100187341+Daolyap@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:38:49 +0000 Subject: [PATCH] runtime: a pipeline cache from the runtime's own device (RT-RUNTIME-PIPELINE-CACHE) A driver keys its pipeline cache on the device's enabled extensions and features. vk_pipeline_check enables a different set from the runtime (17 device extensions the runtime has and it doesn't), so the pipelines stage's pipeline_cache.bin, though accepted by its header, misses for the runtime's pipelines. Measured on an RTX 3070 (driver 32.0.16.1692) with the retail 1.0.2.1 BVH builder: the checker's own re-run of its largest program hits in 0.01 s, while the runtime with that seed loaded still compiles it cold in about 28 s. The title compiles it on its graphics-init thread, and its own watchdog ends the process after about 26 s. - DeviceState::save_pipeline_cache writes the device's vkGetPipelineCacheData through a temporary file; rt::d3d12::save_pipeline_cache exposes it for a device from create_vulkan_device*. - pso_warmup (runtime/test/pso_warmup.cpp) builds a folder of compute programs through create_vulkan_device_standalone and writes that device's cache. For the BVH builder's 52 programs: 63 s cold, 5.7 s with the result seeded. - LEONIDA_PIPELINE_CACHE_OUT= saves after every compute compile of 250 ms or more, so a run that ends without a teardown keeps what it compiled. - A compute compile of 1 s or more is logged with the shader's name. - docs/d3d12_vulkan.md: the checker's device differs, with the measurement. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 16 +++++- runtime/CMakeLists.txt | 7 +++ runtime/shims/d3d12_com.h | 5 ++ runtime/shims/d3d12_vulkan_device.cpp | 64 +++++++++++++++++++++- runtime/src/vulkan_backend.h | 2 +- runtime/test/pso_warmup.cpp | 79 +++++++++++++++++++++++++++ 6 files changed, 168 insertions(+), 5 deletions(-) create mode 100644 runtime/test/pso_warmup.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 90828d409c..73655e93f5 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2071,7 +2071,21 @@ Pipeline creation: the `pipelines` build stage's `pipeline_cache.bin` beside the executable if its Vulkan header matches the device and pipeline-cache UUID. When the file is absent or incompatible, the runtime starts with an empty cache. The offline checker matches the runtime's layout and subgroup request for compute shaders with no descriptor - bindings and the standard 144-byte push-constant range. + bindings and the standard 144-byte push-constant range, but **its device does not match the runtime's**: the + runtime enables 17 device extensions the checker does not (mesh shader, maintenance5/8, shader FMA and clock, + fragment barycentrics and interlock among them) and a different feature set, and a driver keys its cache on that. + Measured on an RTX 3070 (driver 32.0.16.1692): the checker's own re-run of the retail BVH builder's largest + program is a cache hit in 0.01 s, while the runtime with that `pipeline_cache.bin` loaded still compiles it cold + (about 28 s). A cache that seeds the runtime has to come from the runtime's device: + - `pso_warmup ` (`runtime/test/pso_warmup.cpp`) builds each program + through `create_vulkan_device_standalone`, the device `gta6rt --run` uses with `LEONIDA_D3D12=vulkan`, and writes + that device's cache (`LEONIDA_SHADERS` must name the translated SPIR-V). For the BVH builder's 52 programs + (`/shaders/bvh`): 63 s cold, then 5.7 s with the result seeded, the 28 s program included. + - `LEONIDA_PIPELINE_CACHE_OUT=` makes the runtime write its cache after every compute compile of 250 ms or + more, so a run that ends without a device teardown (the title's watchdog, a crash) keeps what it compiled. + A compute compile of 1 s or more is logged with the shader's name. Why it matters: the retail title compiles its + BVH builder on its graphics-init thread, and a cold 28 s compile there outlasts the title's own watchdog + (about 26 s), which then ends the process with nothing in the log. `GetCachedBlob` records the vendor, device, driver version, `pipelineCacheUUID` and a SHA-256 of the description without `Flags`, sealed by a checksum (`runtime/src/cached_pso.h`). The answers are the host's, measured on an RTX 3060 and WARP: the same description is accepted; another diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index d81708e6c7..fe69b713c7 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2269,6 +2269,13 @@ if(TARGET Vulkan::Headers) add_test(NAME pipeline_cache_seed COMMAND pipeline_cache_seed_test $) set_tests_properties(pipeline_cache_seed PROPERTIES SKIP_RETURN_CODE 77) + # Builds a folder of compute programs on the runtime's own Vulkan device and writes that device's pipeline cache + # (a tool, not a test: it needs the user's carved programs and translated shaders). + add_executable(pso_warmup test/pso_warmup.cpp) + target_link_libraries(pso_warmup PRIVATE gta6rt_d3d12_com d3d12 dxgi version) + target_compile_definitions(pso_warmup PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) + target_compile_options(pso_warmup PRIVATE /W4 /permissive- /utf-8) + # What Close returns after one recorded call, against WARP; today's differences are listed in the test. add_executable(d3d12_close_parity_test test/d3d12_close_parity_test.cpp) target_link_libraries(d3d12_close_parity_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 07233494bf..6075494c0b 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -226,6 +226,11 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, // proxy it also makes the proxy's IDXGIDevice1::GetAdapter return this layer's adapter (d3d12_xs_device.h). void set_device_outer(ID3D12Device* device, IUnknown* outer); +// Writes the pipeline cache of a device from create_vulkan_device* to `path`. Its data is keyed on that device's +// extensions and features, so it seeds the game's device where a vk_pipeline_check cache (a different device) does not. +// False for any other device, or when the driver returns no data. +bool save_pipeline_cache(ID3D12Device* device, const wchar_t* path); + // Console Xbox CreateDescriptorHeap takes a 16-byte PC D3D12_DESCRIPTOR_HEAP_DESC followed by address/size at // +0x10/+0x18 (issue #313 comment 7107265058). This helper creates a heap with that console ABI contract on a // device from create_vulkan_device*; it is intended for the Xbox device-proxy slot 14 path, not normal PC callers. diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index f8a5f656dc..9cd541fb70 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -613,6 +613,47 @@ struct DeviceState { return pipeline_cache_handle; } + // Writes this device's pipeline cache to `path` (through a temporary file, so a reader never sees half of it). + // The data is the driver's own, keyed on this device's extensions and features: unlike a cache from + // vk_pipeline_check, whose device enables a different set, it hits for the pipelines this runtime creates + // (measured on an RTX 3070, docs/d3d12_vulkan.md section 4). + std::mutex pipeline_cache_save_mutex; + bool save_pipeline_cache(const std::filesystem::path& path) { + const auto& vk = context->vk; + const VkPipelineCache cache = pipeline_cache(); + if (!cache || !vk.vkGetPipelineCacheData || path.empty()) return false; + const std::lock_guard lock(pipeline_cache_save_mutex); + std::size_t size = 0; + if (vk.vkGetPipelineCacheData(info.device, cache, &size, nullptr) != VK_SUCCESS || !size) return false; + std::vector data(size); + if (vk.vkGetPipelineCacheData(info.device, cache, &size, data.data()) != VK_SUCCESS) return false; + std::filesystem::path temp = path; + temp += L".partial"; + { + std::ofstream out(temp, std::ios::binary | std::ios::trunc); + if (!out.write(data.data(), static_cast(size))) return false; + } + std::error_code error; + std::filesystem::rename(temp, path, error); + if (error) return false; + std::fprintf(stderr, "[rt] d3d12: wrote %zu bytes of pipeline cache to %ls\n", size, path.c_str()); + return true; + } + + // LEONIDA_PIPELINE_CACHE_OUT=: save after every slow compile, so a run the title (or its watchdog) ends + // without a device teardown still keeps what it compiled. Read once. + const std::filesystem::path& pipeline_cache_out() { + static const std::filesystem::path out = [] { + wchar_t* value = nullptr; + std::size_t length = 0; + std::filesystem::path path; + if (_wdupenv_s(&value, &length, L"LEONIDA_PIPELINE_CACHE_OUT") == 0 && value && *value) path = value; + std::free(value); + return path; + }(); + return out; + } + QueueClock clock; // what every queue's GetClockCalibration uses PFN_vkGetPhysicalDeviceFormatProperties2 format_properties2 = nullptr; // True when VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 lacks native STORAGE_IMAGE but mutable R32_UINT+{R32_UINT,E5B9G9R9} @@ -4097,9 +4138,20 @@ class PipelineState final VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{}; subgroup_size_for(*entry, required_size, pipeline_info.stage); pipeline_info.layout = pipeline_.layout; - if (vk.vkCreateComputePipelines(dev, device_.pipeline_cache(), 1, &pipeline_info, nullptr, &pipeline_.pipeline) != - VK_SUCCESS) - return E_FAIL; + // The console never makes the title wait for a compile here; a long one on its own thread can outlast the + // title's watchdog (measured: the retail 1.0.2.1 BVH builder's largest program, ~28 s cold on an RTX 3070). + // Name the slow ones, so a stall points at a shader. + const auto compile_start = std::chrono::steady_clock::now(); + const VkResult compiled = + vk.vkCreateComputePipelines(dev, device_.pipeline_cache(), 1, &pipeline_info, nullptr, &pipeline_.pipeline); + const auto compile_ms = std::chrono::duration_cast( + std::chrono::steady_clock::now() - compile_start).count(); + if (compile_ms >= 1000) + std::fprintf(stderr, "[rt] d3d12: compute pipeline %s took %lld ms to compile\n", entry->name.c_str(), + static_cast(compile_ms)); + if (compiled != VK_SUCCESS) return E_FAIL; + if (compile_ms >= 250 && !device_.pipeline_cache_out().empty()) + device_.save_pipeline_cache(device_.pipeline_cache_out()); // The code base: shaders read constant tables embedded in their own program through s_getpc_b64. The // translator's code offsets are into the bytes the key hashes (the FSSM blob, or the kind-6 program). @@ -5549,6 +5601,7 @@ class Device final leonida::VulkanContext& context() { return *state_.context; } const leonida::BindlessSet* bindless() const { return state_.bindless.get(); } const DeviceState& state() const { return state_; } + DeviceState& mutable_state() { return state_; } IUnknown* holder() { return identity(); } // Console-extended CreateDescriptorHeap (Xbox slot 14): a heap at the title's console address. The proxy's // handler (set_console_descriptor_heap_handler) calls this; a normal PC create never does. @@ -8876,6 +8929,11 @@ bool is_sparse_image(ID3D12Resource* resource) { return object && object->sparse_image(); } +bool save_pipeline_cache(ID3D12Device* device, const wchar_t* path) { + Device* d = Device::from(device); + return d && path && d->mutable_state().save_pipeline_cache(path); +} + void set_device_outer(ID3D12Device* device, IUnknown* outer) { Device* d = Device::from(device); if (!d) return; diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index ab6786a518..89f792d95c 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -105,7 +105,7 @@ struct VulkanDeviceFunctions { X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ X(vkCmdSetBlendConstants) X(vkCmdDraw) \ X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ - X(vkCreatePipelineCache) X(vkDestroyPipelineCache) \ + X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) \ X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) \ X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \ X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) diff --git a/runtime/test/pso_warmup.cpp b/runtime/test/pso_warmup.cpp new file mode 100644 index 0000000000..051e34fce6 --- /dev/null +++ b/runtime/test/pso_warmup.cpp @@ -0,0 +1,79 @@ +// pso_warmup +// +// Builds every compute program in a folder through the runtime's own Vulkan-backed ID3D12Device +// (create_vulkan_device_standalone, the device gta6rt --run uses with LEONIDA_D3D12=vulkan), then writes that device's +// pipeline cache. Driver caches are keyed on the device's enabled extensions and features; vk_pipeline_check enables a +// different set, so its cache misses for the runtime's pipelines (measured on an RTX 3070: a 28 s compile stays a 28 s +// compile with that seed loaded). A cache written here is the runtime's own, and placed beside gta6rt.exe as +// pipeline_cache.bin it seeds the game's device. +// +// The programs are the user's carved files (for example /shaders/bvh/*.dxbc); LEONIDA_SHADERS must point at the +// translated SPIR-V the runtime looks them up in. Nothing of the game is in this file. Exit 0 when every program built, +// 1 when some did not (the cache is still written), 2 for usage or setup errors. +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../shims/d3d12_com.h" + +int wmain(int argc, wchar_t** argv) { + if (argc != 3) { + std::fprintf(stderr, "usage: pso_warmup \n"); + return 2; + } + wchar_t* shaders = nullptr; + std::size_t shaders_length = 0; + const bool have_shaders = _wdupenv_s(&shaders, &shaders_length, L"LEONIDA_SHADERS") == 0 && shaders && *shaders; + std::free(shaders); + if (!have_shaders) { + std::fprintf(stderr, "pso_warmup: set LEONIDA_SHADERS to the translated SPIR-V (/shaders/spirv)\n"); + return 2; + } + const std::filesystem::path dir = argv[1]; + std::error_code error; + if (!std::filesystem::is_directory(dir, error)) { + std::fprintf(stderr, "pso_warmup: %ls is not a folder\n", dir.c_str()); + return 2; + } + + ID3D12Device* device = nullptr; + if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device))) || !device) { + std::fprintf(stderr, "pso_warmup: no Vulkan-backed device\n"); + return 2; + } + + int built = 0, failed = 0; + for (const auto& item : std::filesystem::directory_iterator(dir, error)) { + if (!item.is_regular_file() || item.path().extension() != L".dxbc") continue; + std::ifstream file(item.path(), std::ios::binary); + const std::vector bytes((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + if (bytes.empty()) continue; + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.CS = {bytes.data(), bytes.size()}; + const auto start = std::chrono::steady_clock::now(); + ID3D12PipelineState* pso = nullptr; + const HRESULT hr = device->CreateComputePipelineState(&desc, IID_PPV_ARGS(&pso)); + const double seconds = std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + if (SUCCEEDED(hr) && pso) { + ++built; + pso->Release(); + if (seconds >= 1.0) std::printf("%ls: %.1f s\n", item.path().filename().c_str(), seconds); + } else { + ++failed; + std::printf("%ls: failed (hr=0x%08lx)\n", item.path().filename().c_str(), static_cast(hr)); + } + } + const bool saved = rt::d3d12::save_pipeline_cache(device, argv[2]); + std::printf("%d built, %d failed; cache %s\n", built, failed, saved ? "written" : "NOT written"); + device->Release(); + if (!saved) return 2; + return failed ? 1 : 0; +}