Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion docs/d3d12_vulkan.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <dir of .dxbc compute programs> <out file>` (`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
(`<work>/shaders/bvh`): 63 s cold, then 5.7 s with the result seeded, the 28 s program included.
- `LEONIDA_PIPELINE_CACHE_OUT=<file>` 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
Expand Down
7 changes: 7 additions & 0 deletions runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2269,6 +2269,13 @@ if(TARGET Vulkan::Headers)
add_test(NAME pipeline_cache_seed COMMAND pipeline_cache_seed_test $<TARGET_FILE:vk_pipeline_check>)
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)
Expand Down
5 changes: 5 additions & 0 deletions runtime/shims/d3d12_com.h
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
64 changes: 61 additions & 3 deletions runtime/shims/d3d12_vulkan_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<char> 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<std::streamsize>(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=<file>: 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}
Expand Down Expand Up @@ -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::milliseconds>(
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<long long>(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).
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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>(device);
return d && path && d->mutable_state().save_pipeline_cache(path);
}

void set_device_outer(ID3D12Device* device, IUnknown* outer) {
Device* d = Device::from<Device>(device);
if (!d) return;
Expand Down
2 changes: 1 addition & 1 deletion runtime/src/vulkan_backend.h
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
79 changes: 79 additions & 0 deletions runtime/test/pso_warmup.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// pso_warmup <dir of .dxbc compute programs> <pipeline_cache.bin to write>
//
// 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 <work>/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 <windows.h>
#include <d3d12.h>

#include <chrono>
#include <cstdlib>
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <iterator>
#include <string>
#include <vector>

#include "../shims/d3d12_com.h"

int wmain(int argc, wchar_t** argv) {
if (argc != 3) {
std::fprintf(stderr, "usage: pso_warmup <dir of .dxbc compute programs> <pipeline_cache.bin to write>\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 (<work>/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<char> bytes((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
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<double>(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<unsigned long>(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;
}