diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 9281559e27..95a9823f87 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1507,11 +1507,14 @@ Pipeline creation: buffer device address, storage image without format, maintenance8. - Request the subgroup size each shader was translated for (`requiredSubgroupSize` 64 or 32) where the device lists the stage in `requiredSubgroupSizeStages`, and say so in the log where it cannot (section 3.2, "Subgroup size"). -- Pipeline caches: use a `VkPipelineCache` keyed by driver/pipeline-cache UUID; the `pipelines` build stage already - produces one. The PSO is always rebuilt from its descriptors: `GetCachedBlob` returns a small blob that holds no - pipeline, only what the PC runtime checks before it accepts one in `CachedPSO` (`runtime/src/cached_pso.h`: - vendor, device, driver version, `pipelineCacheUUID` and a SHA-256 of the description without `Flags`, sealed by a - checksum). The answers are the host's, measured on an RTX 3060 and WARP: the same description is accepted; another +- Pipeline caches: graphics and compute PSOs use one `VkPipelineCache` per device. On first use the runtime reads + 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. + `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 shader, root signature content or state, a changed byte, a truncated blob or a pointer with size 0 give `E_INVALIDARG`; a null pointer with a size is ignored; another adapter gives `D3D12_ERROR_ADAPTER_NOT_FOUND` and another driver `D3D12_ERROR_DRIVER_VERSION_MISMATCH`. `ID3D12PipelineLibrary` is an in-memory map plus the Vulkan diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 3fb36bd4a7..2f3af9792a 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -77,6 +77,81 @@ void log_once(const char* what, int value) { if (seen.insert({what, value}).second) std::fprintf(stderr, "[rt] d3d12: %s %d\n", what, value); } +// The pipelines build stage writes its cache beside gta6rt.exe, independently of the working directory. +std::filesystem::path pipeline_cache_path() { + std::wstring path(32768, L'\0'); + const DWORD length = GetModuleFileNameW(nullptr, path.data(), static_cast(path.size())); + if (!length || length >= path.size()) return {}; + path.resize(length); + return std::filesystem::path(path).parent_path() / L"pipeline_cache.bin"; +} + +// A corpus cache may be several GiB. Keep the read-only view alive through vkCreatePipelineCache +// and deny writers while the view is in use. +class PipelineCacheSeed { +public: + explicit PipelineCacheSeed(const std::filesystem::path& path) { + if (path.empty()) return; + file_ = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file_ == INVALID_HANDLE_VALUE) return; + LARGE_INTEGER length{}; + constexpr auto header_size = static_cast(sizeof(VkPipelineCacheHeaderVersionOne)); + if (!GetFileSizeEx(file_, &length) || length.QuadPart < header_size) + return; + const HANDLE mapping = CreateFileMappingW(file_, nullptr, PAGE_READONLY, 0, 0, nullptr); + if (!mapping) return; + data_ = MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0); + CloseHandle(mapping); + if (data_) size_ = static_cast(length.QuadPart); + } + + ~PipelineCacheSeed() { + if (data_) UnmapViewOfFile(data_); + if (file_ != INVALID_HANDLE_VALUE) CloseHandle(file_); + } + + PipelineCacheSeed(const PipelineCacheSeed&) = delete; + PipelineCacheSeed& operator=(const PipelineCacheSeed&) = delete; + + const void* data() const { return data_; } + std::size_t size() const { return size_; } + + bool compatible(const leonida::cached_pso::Identity& identity) const { + static_assert(sizeof(VkPipelineCacheHeaderVersionOne) == 32); + VkPipelineCacheHeaderVersionOne header{}; + // The header is little-endian, like the host. The driver interprets the opaque payload. + std::memcpy(&header, data_, sizeof(header)); + return header.headerSize == sizeof(header) && header.headerVersion == VK_PIPELINE_CACHE_HEADER_VERSION_ONE && + header.vendorID == identity.vendor && header.deviceID == identity.device && + std::memcmp(header.pipelineCacheUUID, identity.cache_uuid, VK_UUID_SIZE) == 0; + } + +private: + HANDLE file_ = INVALID_HANDLE_VALUE; + const void* data_ = nullptr; + std::size_t size_ = 0; +}; + +VkPipelineCache create_seeded_pipeline_cache(PFN_vkCreatePipelineCache create_cache, VkDevice device, + const leonida::cached_pso::Identity& identity) { + const PipelineCacheSeed seed(pipeline_cache_path()); + if (!seed.data()) return VK_NULL_HANDLE; + if (!seed.compatible(identity)) { + std::fprintf(stderr, "[rt] d3d12: pipeline_cache.bin does not match this Vulkan device\n"); + return VK_NULL_HANDLE; + } + const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, + nullptr, 0, seed.size(), seed.data()}; + VkPipelineCache cache = VK_NULL_HANDLE; + if (create_cache(device, &create, nullptr, &cache) != VK_SUCCESS) { + std::fprintf(stderr, "[rt] d3d12: Vulkan declined the pipeline cache seed\n"); + return VK_NULL_HANDLE; + } + std::fprintf(stderr, "[rt] d3d12: loaded %zu bytes from pipeline_cache.bin\n", seed.size()); + return cache; +} + // A shader whose subgroup size cannot be had runs at the device's: inexact if it crosses the halves of a wave64 (or, // for a wave32 shader on a 64-wide default, reads lanes that are not its own). Logged once per stage with the first // shader's name, then again at 10, 100, 1000... of that stage so a whole corpus stays readable. @@ -420,6 +495,23 @@ struct DeviceState { PFN_vkGetDeviceImageMemoryRequirements image_requirements = nullptr; // Vulkan 1.3 or VK_KHR_maintenance4 LUID luid{}; // VkPhysicalDeviceIDProperties::deviceLUID; zero when the driver reports none leonida::cached_pso::Identity pso_identity; // what GetCachedBlob records and CachedPSO is checked against + std::once_flag pipeline_cache_once; + VkPipelineCache pipeline_cache_handle = VK_NULL_HANDLE; + + VkPipelineCache pipeline_cache() { + std::call_once(pipeline_cache_once, [this] { + const auto& vk = context->vk; + if (!vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache) return; + pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity); + if (pipeline_cache_handle) return; + const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; + if (vk.vkCreatePipelineCache(info.device, &create, nullptr, &pipeline_cache_handle) != VK_SUCCESS) + pipeline_cache_handle = VK_NULL_HANDLE; + }); + // Without EXTERNALLY_SYNCHRONIZED_BIT the driver synchronizes concurrent pipeline creation using this cache. + return pipeline_cache_handle; + } + 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} @@ -2987,7 +3079,7 @@ class PipelineState final VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{}; subgroup_size_for(*entry, required_size, pipeline_info.stage); pipeline_info.layout = pipeline_.layout; - if (vk.vkCreateComputePipelines(dev, VK_NULL_HANDLE, 1, &pipeline_info, nullptr, &pipeline_.pipeline) != + if (vk.vkCreateComputePipelines(dev, device_.pipeline_cache(), 1, &pipeline_info, nullptr, &pipeline_.pipeline) != VK_SUCCESS) return E_FAIL; @@ -3075,8 +3167,8 @@ class PipelineState final info.pDynamicState = &dynamic; info.layout = graphics_.layout; VkPipeline pipeline = VK_NULL_HANDLE; - if (device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, VK_NULL_HANDLE, 1, &info, nullptr, - &pipeline) != VK_SUCCESS) + if (device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, device_.pipeline_cache(), 1, + &info, nullptr, &pipeline) != VK_SUCCESS) return VK_NULL_HANDLE; return pipeline; } @@ -4188,6 +4280,8 @@ class Device final vk.vkDestroyBuffer(state_.info.device, state_.arena.buffer, nullptr); if (state_.arena.memory) vk.vkFreeMemory(state_.info.device, state_.arena.memory, nullptr); } + if (state_.pipeline_cache_handle) + state_.context->vk.vkDestroyPipelineCache(state_.info.device, state_.pipeline_cache_handle, nullptr); state_.context.reset(); if (owned_.device) owned_.destroy_device(owned_.device, nullptr); if (owned_.instance) owned_.destroy_instance(owned_.instance, nullptr); diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 1be77a0ca4..5fd030d393 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -82,6 +82,7 @@ struct VulkanDeviceFunctions { X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ X(vkCmdSetBlendConstants) X(vkCmdDraw) \ X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) \ + X(vkCreatePipelineCache) X(vkDestroyPipelineCache) \ X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) #define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp index 65a53a5f3f..c915c706f2 100644 --- a/runtime/test/vk_pipeline_check.cpp +++ b/runtime/test/vk_pipeline_check.cpp @@ -3,7 +3,8 @@ // pipeline with the translator's resource contract (set 0: sampled images 0, 3, 5, 6; samplers 1; descriptor hash // table 2; storage images 4, 7 and 8..19; set 1 binding 0 dynamic UBO for --pc-tail-ubo shaders; push constants // sized from push_constant_bytes, default 144 or 128 with pc_tail): -// - cs: compute pipeline via vkCreateComputePipelines +// - cs: compute pipeline via vkCreateComputePipelines, using the runtime layout and subgroup request for +// descriptor-free shaders with the standard push-constant range // - ps/vs/ms/gs: graphics pipeline via vkCreateGraphicsPipelines (Vulkan 1.3 dynamic rendering, no render pass) // paired with minimal partner stubs from /stubs/ (generated by tools/spirv_stubs.py) // Only optional device extensions needed by the selected shaders (and supported by the GPU) are enabled. Shaders @@ -43,8 +44,10 @@ #include "pipeline_cache_file.h" #include "pipeline_cache_snapshot.h" #include "../src/spirv_words.h" +#include "../src/subgroup_size.h" #include +#include #include #include #include @@ -88,6 +91,10 @@ struct ShaderMeta { uint32_t lds_bytes = 0; uint32_t push_constant_bytes = 0; // 0 = absent in index (128 with pc_tail, else 144) uint32_t pc_tail_bytes = 0; // >0 = --pc-tail-ubo uniform block at set 1, binding 0 + bool no_set0_bindings = false; + bool wave64 = false; + std::array local_size{1, 1, 1}; + std::string wave64_exchange; bool writes_depth = false; bool needs_maintenance8 = false; std::vector features; @@ -220,6 +227,22 @@ struct JsonParser { if (!error) fail("unterminated u32 array"); return out; } + void parse_local_size(std::array& out) { + if (!consume('[')) { skip_value(); return; } + for (size_t dim = 0; !error && i < s.size(); ++dim) { + if (consume(']')) return; + const char* start = s.data() + i; + skip_value(); + if (dim < out.size()) { + char* end = nullptr; + const double size = std::strtod(start, &end); + out[dim] = end == s.data() + i && size >= 0 && size <= UINT32_MAX ? uint32_t(size) : 0; + } + if (consume(']')) return; + if (!consume(',')) { fail("expected ',' or ']' in local size"); return; } + } + if (!error) fail("unterminated local size"); + } std::vector parse_str_array() { std::vector out; if (!consume('[')) { skip_value(); return out; } @@ -316,6 +339,25 @@ struct JsonParser { else if (k == "push_constant_bytes") m.push_constant_bytes = parse_strict_u32("expected unsigned 32-bit push_constant_bytes"); else if (k == "pc_tail") m.pc_tail_bytes = parse_pc_tail_bytes(); + else if (k == "bindings") { + const size_t start = i; + m.no_set0_bindings = consume('[') && consume(']'); + if (!m.no_set0_bindings) { + i = start; + skip_value(); + } + } + else if (k == "wave64") { + ws(); + if (s.compare(i, 4, "true") == 0 || s.compare(i, 5, "false") == 0) m.wave64 = parse_bool(); + else skip_value(); + } + else if (k == "wave64_exchange") { + ws(); + if (i < s.size() && s[i] == '"') m.wave64_exchange = parse_string(); + else skip_value(); + } + else if (k == "local_size") parse_local_size(m.local_size); else if (k == "writes_depth") m.writes_depth = parse_bool(); else if (k == "needs_maintenance8") m.needs_maintenance8 = parse_bool(); else if (k == "features") m.features = parse_str_array(); @@ -450,6 +492,13 @@ constexpr uint32_t required_push_bytes(uint32_t push_constant_bytes, uint32_t pc return raw > (std::numeric_limits::max() - 3u) ? raw : ((raw + 3u) & ~3u); } +constexpr uint32_t runtime_compute_push_bytes = 144; // sizeof(leonida::ShaderUserData) + +bool uses_runtime_compute_layout(const ShaderMeta& meta) { + return meta.stage == "cs" && meta.no_set0_bindings && !meta.pc_tail_bytes && + required_push_bytes(meta.push_constant_bytes, meta.pc_tail_bytes) == runtime_compute_push_bytes; +} + static_assert(required_push_bytes(0, 0) == 144); static_assert(required_push_bytes(0, 16) == 128); static_assert(required_push_bytes(128, 0) == 128); @@ -941,15 +990,33 @@ int main(int argc, char** argv) { dci.enabledExtensionCount = uint32_t(enable.size()); dci.ppEnabledExtensionNames = enable.data(); VkDevice dev; if (VkResult r = vkCreateDevice(pd, &dci, nullptr, &dev)) { std::fprintf(stderr, "vkCreateDevice %d\n", r); return 1; } + leonida::SubgroupSizeCaps runtime_subgroups; + leonida::query_subgroup_size_caps(vkGetPhysicalDeviceProperties2, pd, f13.subgroupSizeControl, + f13.computeFullSubgroups, runtime_subgroups); auto can_require_sg = [&](uint32_t sg, VkShaderStageFlagBits bit) -> bool { return f13.subgroupSizeControl && sg >= sgProps.minSubgroupSize && sg <= sgProps.maxSubgroupSize && (sgProps.requiredSubgroupSizeStages & bit); }; + auto runtime_compute_subgroup = [&](const ShaderMeta& meta) { + leonida::ShaderEntry entry; + entry.stage = meta.stage; + entry.subgroup_size = meta.subgroup_size; + entry.wave64 = meta.wave64; + entry.wave64_exchange = meta.wave64_exchange; + entry.local_size = meta.local_size; + return leonida::decide_subgroup_size(entry, runtime_subgroups); + }; { std::map> unforced_by_sg; for (const auto& [_, meta] : work) { + if (uses_runtime_compute_layout(*meta)) { + const auto request = runtime_compute_subgroup(*meta); + if (request.outcome == leonida::SubgroupOutcome::unavailable) + unforced_by_sg[request.wanted].insert(meta->stage); + continue; + } const VkShaderStageFlagBits bit = stage_bit(meta->stage); if (bit && meta->subgroup_size > 0 && !can_require_sg(meta->subgroup_size, bit)) { unforced_by_sg[meta->subgroup_size].insert(meta->stage); @@ -1075,6 +1142,20 @@ int main(int argc, char** argv) { const uint32_t need_pc = required_push_bytes(meta.push_constant_bytes, meta.pc_tail_bytes); return layouts.at({need_pc, meta.pc_tail_bytes != 0}); }; + VkPipelineLayout runtime_compute_layout = VK_NULL_HANDLE; + if (runtime_compute_push_bytes <= props.limits.maxPushConstantsSize && + std::any_of(work.begin(), work.end(), [](const Item& item) { + return uses_runtime_compute_layout(*item.second); + })) { + const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, runtime_compute_push_bytes}; + VkPipelineLayoutCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + info.pushConstantRangeCount = 1; + info.pPushConstantRanges = &push; + if (VkResult r = vkCreatePipelineLayout(dev, &info, nullptr, &runtime_compute_layout)) { + std::fprintf(stderr, "runtime compute pipeline layout %d\n", r); + return 1; + } + } VkPipelineCacheCreateInfo pci{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; std::vector seed; if (!cache_path.empty()) { // resume: pipelines already in the cache compile instantly @@ -1309,15 +1390,23 @@ int main(int argc, char** argv) { if (!miss.empty()) { record_skip(name, stage, miss); } else { - VkPipelineShaderStageRequiredSubgroupSizeCreateInfo reqSg{ - VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO}; - reqSg.requiredSubgroupSize = meta.subgroup_size; + VkPipelineShaderStageRequiredSubgroupSizeCreateInfo reqSg{}; VkComputePipelineCreateInfo cpi{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; cpi.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; cpi.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; cpi.stage.module = sm; cpi.stage.pName = "main"; - const bool sg_forced = can_require_sg(meta.subgroup_size, VK_SHADER_STAGE_COMPUTE_BIT); - if (sg_forced) cpi.stage.pNext = &reqSg; - cpi.layout = layout_for(meta); + bool sg_forced = false; + if (uses_runtime_compute_layout(meta)) { + const auto request = runtime_compute_subgroup(meta); + leonida::apply_subgroup_request(request, reqSg, cpi.stage); + sg_forced = request.size != 0; + cpi.layout = runtime_compute_layout; + } else { + reqSg.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO; + reqSg.requiredSubgroupSize = meta.subgroup_size; + sg_forced = can_require_sg(meta.subgroup_size, VK_SHADER_STAGE_COMPUTE_BIT); + if (sg_forced) cpi.stage.pNext = &reqSg; + cpi.layout = layout_for(meta); + } cpi.flags = capture; // Only whole-pipeline feedback is reported. VkPipelineCreationFeedback fb{};