diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 3ae29163e5..89b32b1f10 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2056,6 +2056,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"). +- Deferred pipelines (`LEONIDA_LAZY_PSO=1`, off by default): `CreateGraphicsPipelineState` and the compute calls + check the description, pick and read the translated shaders and make the layout as before, but the driver pipeline + is built by the first draw (as `variant(0)`) or dispatch (`ComputePipeline::build`) that uses it, and a stage the + runtime does not edit (no f16 link, no D24 depth patch) keeps no `VkShaderModule`: one is made from the library's + words for each pipeline built and destroyed after. The retail title creates some 50,000 PSOs before its first frame + and draws with far fewer; built eagerly, their modules and pipelines ran a 16 GB machine out of commit. A pipeline + the driver refuses then fails its draw or dispatch (unresolved) instead of `CreatePipelineState`. Tested by + `d3d12_compute_lazy_pso`, `d3d12_draw_lazy_pso` and `d3d12_mesh_lazy_pso`. - 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. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 64e346f40a..5bbdd53870 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2750,6 +2750,9 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_compute_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_compute COMMAND d3d12_compute_test) set_tests_properties(d3d12_compute PROPERTIES SKIP_RETURN_CODE 77) + # The same with LEONIDA_LAZY_PSO=1: pipelines built by their first dispatch, unedited stages without kept modules. + add_test(NAME d3d12_compute_lazy_pso COMMAND d3d12_compute_test) + set_tests_properties(d3d12_compute_lazy_pso PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT LEONIDA_LAZY_PSO=1) # Compute PSOs from FSPX programs (docs/fspx.md): an ACCC container at slot 62 and a bare kind-6 program. add_executable(d3d12_fspx_compute_test test/d3d12_fspx_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_CS}) target_link_libraries(d3d12_fspx_compute_test PRIVATE gta6rt_d3d12_com) @@ -2789,6 +2792,9 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_draw_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_draw COMMAND d3d12_draw_test) set_tests_properties(d3d12_draw PROPERTIES SKIP_RETURN_CODE 77) + # The same with LEONIDA_LAZY_PSO=1: pipelines built by their first draw, unedited stages without kept modules. + add_test(NAME d3d12_draw_lazy_pso COMMAND d3d12_draw_test) + set_tests_properties(d3d12_draw_lazy_pso PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT LEONIDA_LAZY_PSO=1) # Graphics & compute PSO descriptor validation parity against live Windows D3D12 (WARP and HW). add_executable(d3d12_pso_validation_test test/d3d12_pso_validation_test.cpp ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS} ${LEONIDA_TEST_PS_UINT} ${LEONIDA_TEST_VS_FULLSCREEN} ${LEONIDA_TEST_CS}) @@ -3001,6 +3007,9 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_mesh_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_mesh COMMAND d3d12_mesh_test) set_tests_properties(d3d12_mesh PROPERTIES SKIP_RETURN_CODE 77) + # The same with LEONIDA_LAZY_PSO=1: pipelines built by their first draw, unedited stages without kept modules. + add_test(NAME d3d12_mesh_lazy_pso COMMAND d3d12_mesh_test) + set_tests_properties(d3d12_mesh_lazy_pso PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT LEONIDA_LAZY_PSO=1) else() message(STATUS "glslangValidator not found: d3d12_compute_test, d3d12_draw_test, d3d12_set0_compute_test and d3d12_mesh_test are not built") endif() diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 0273f9339b..61be7b49c5 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -3306,6 +3306,7 @@ class PipelineState final const VkDevice dev = device_.info.device; if (registered_) device_.context->remove_pipeline(id()); if (pipeline_.pipeline) vk.vkDestroyPipeline(dev, pipeline_.pipeline, nullptr); + if (lazy_compute_) vk.vkDestroyPipeline(dev, lazy_compute_, nullptr); if (pipeline_.layout) vk.vkDestroyPipelineLayout(dev, pipeline_.layout, nullptr); if (module_) vk.vkDestroyShaderModule(dev, module_, nullptr); if (graphics_.pipeline) vk.vkDestroyPipeline(dev, graphics_.pipeline, nullptr); @@ -3588,8 +3589,11 @@ class PipelineState final if (vs_stage.entry && ps_stage.entry && !ps_stage.entry->f16_halves.empty() && gs_stage.entry) { log_once("--f16-interp-fallback halves are linked VS->PS only; this PSO has a geometry shader", 0); } - if (vs_stage.entry && ps_stage.entry && !gs_stage.entry && - (!ps_stage.entry->f16_halves.empty() || !vs_stage.entry->f16_halves.empty())) { + // Whether the link below may have edited the VS's and PS's words: such stages keep their modules under + // LEONIDA_LAZY_PSO, since the library's words are not what they run. + const bool f16_linked = vs_stage.entry && ps_stage.entry && !gs_stage.entry && + (!ps_stage.entry->f16_halves.empty() || !vs_stage.entry->f16_halves.empty()); + if (f16_linked) { std::string link_error; if (!leonida::link_f16_halves(vs_stage.words, *vs_stage.entry, ps_stage.words, *ps_stage.entry, &link_error, device_.f16_half_top_location)) { @@ -3627,16 +3631,25 @@ class PipelineState final stage.words = std::move(patched); } } - VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module_info.codeSize = stage.words.size() * 4; - module_info.pCode = stage.words.data(); - VkShaderModule module = VK_NULL_HANDLE; - if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL; - modules_.push_back(module); VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; info.stage = stage.bit; - info.module = module; info.pName = "main"; + const bool edited = (f16_linked && (&stage == &vs_stage || &stage == &ps_stage)) || + (depth24_fragment && stage.bit == VK_SHADER_STAGE_FRAGMENT_BIT); + if (lazy_pso() && !edited) { + // LEONIDA_LAZY_PSO: no module is kept; build() makes one from the library's words (the same words + // read above) for each pipeline it creates, and destroys it after. + recipe_.lazy_modules.emplace_back(stage_infos.size(), *stage.entry); + } else { + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = stage.words.size() * 4; + module_info.pCode = stage.words.data(); + VkShaderModule module = VK_NULL_HANDLE; + if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL; + modules_.push_back(module); + info.module = module; + } + stage.words = {}; // a lazy stage reads its words again at build time; an eager one has its module subgroup_size_for(*stage.entry, required_sizes[stage_infos.size()], info); stage_infos.push_back(info); } @@ -3950,8 +3963,13 @@ class PipelineState final recipe_.depth = depth; recipe_.blends = std::move(blends); recipe_.blend = blend; - graphics_.pipeline = build(0); - if (!graphics_.pipeline) return E_FAIL; + // LEONIDA_LAZY_PSO=1: the driver pipeline is built by the first draw that uses it (variant(0) in replay), not + // here. The retail title creates some 50,000 graphics PSOs before its first frame and draws with far fewer, so + // building them all costs gigabytes of driver memory up front. + if (!lazy_pso()) { + graphics_.pipeline = build(0); + if (!graphics_.pipeline) return E_FAIL; + } graphics_.variant = [this](std::uint32_t unbound) { return variant(unbound); }; if (code_stage) { @@ -4033,16 +4051,20 @@ class PipelineState final } } } - const std::vector words = library->spirv(*entry); - if (words.empty()) { - std::fprintf(stderr, "[rt] d3d12: %s.spv is missing or not SPIR-V\n", entry->name.c_str()); - return E_FAIL; + { + const std::vector words = library->spirv(*entry); + if (words.empty()) { + std::fprintf(stderr, "[rt] d3d12: %s.spv is missing or not SPIR-V\n", entry->name.c_str()); + return E_FAIL; + } + // LEONIDA_LAZY_PSO: no module yet; the first dispatch makes one from these words again (lazy_compute). + if (!lazy_pso()) { + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = words.size() * 4; + module_info.pCode = words.data(); + if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module_) != VK_SUCCESS) return E_FAIL; + } } - - VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module_info.codeSize = words.size() * 4; - module_info.pCode = words.data(); - if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module_) != VK_SUCCESS) return E_FAIL; const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(leonida::ShaderUserData)}; VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; layout_info.pushConstantRangeCount = 1; @@ -4055,17 +4077,23 @@ class PipelineState final pipeline_.bindless_set = device_.bindless->set(); } if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &pipeline_.layout) != VK_SUCCESS) return E_FAIL; - VkComputePipelineCreateInfo pipeline_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; - pipeline_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; - pipeline_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; - pipeline_info.stage.module = module_; - pipeline_info.stage.pName = "main"; - 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 subgroup size is decided (and recorded, and reported if unavailable) here in both modes; the compile + // applies it. + { + VkPipelineShaderStageCreateInfo decided{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + decided.stage = VK_SHADER_STAGE_COMPUTE_BIT; + VkPipelineShaderStageRequiredSubgroupSizeCreateInfo storage{}; + subgroup_size_for(*entry, storage, decided); + compute_subgroup_ = subgroup_requests_.back(); + } + if (lazy_pso()) { + // Compiled by the first dispatch that uses it (ComputePipeline::build in replay), as graphics PSOs are. + compute_entry_ = std::make_unique(*entry); + pipeline_.build = [this] { return lazy_compute(); }; + } else { + pipeline_.pipeline = compile_compute(module_); + if (!pipeline_.pipeline) return E_FAIL; + } // 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). @@ -4099,8 +4127,70 @@ class PipelineState final VkPipelineDepthStencilStateCreateInfo depth{}; std::vector blends; VkPipelineColorBlendStateCreateInfo blend{}; + // LEONIDA_LAZY_PSO: the entries of `stages` (by index) that hold no module; build() makes each from the + // library's words for the pipeline it creates. + std::vector> lazy_modules; }; + // LEONIDA_LAZY_PSO=1: graphics pipelines are built at their first draw and compute pipelines at their first + // dispatch, and neither keeps a shader module the runtime did not edit. + static bool lazy_pso() { + static const bool lazy = [] { + const char* v = std::getenv("LEONIDA_LAZY_PSO"); + return v && *v && *v != '0'; + }(); + return lazy; + } + + // A shader module of `words`; VK_NULL_HANDLE when they are empty or the driver refuses them. + VkShaderModule make_module(const std::vector& words) const { + if (words.empty()) return VK_NULL_HANDLE; + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = words.size() * 4; + module_info.pCode = words.data(); + VkShaderModule module = VK_NULL_HANDLE; + if (device_.context->vk.vkCreateShaderModule(device_.info.device, &module_info, nullptr, &module) != VK_SUCCESS) + return VK_NULL_HANDLE; + return module; + } + + // The compute pipeline from `module`, pipeline_.layout and compute_subgroup_; VK_NULL_HANDLE when the driver + // refuses it. + VkPipeline compile_compute(VkShaderModule module) { + VkComputePipelineCreateInfo pipeline_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + pipeline_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + pipeline_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + pipeline_info.stage.module = module; + pipeline_info.stage.pName = "main"; + VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{}; + leonida::apply_subgroup_request(compute_subgroup_, required_size, pipeline_info.stage); + pipeline_info.layout = pipeline_.layout; + VkPipeline pipeline = VK_NULL_HANDLE; + if (device_.context->vk.vkCreateComputePipelines(device_.info.device, device_.pipeline_cache(), 1, + &pipeline_info, nullptr, &pipeline) != VK_SUCCESS) + return VK_NULL_HANDLE; + return pipeline; + } + + // LEONIDA_LAZY_PSO: the compute pipeline, compiled by the first dispatch (from any queue) and kept until the PSO + // is released. Its module lives only for the compile. + VkPipeline lazy_compute() { + std::lock_guard lock(variants_mutex_); + if (lazy_compute_ || lazy_compute_failed_ || !compute_entry_) return lazy_compute_; + const leonida::ShaderLibrary* library = device_.library(); + const VkShaderModule module = library ? make_module(library->spirv(*compute_entry_)) : VK_NULL_HANDLE; + if (module) { + lazy_compute_ = compile_compute(module); + device_.context->vk.vkDestroyShaderModule(device_.info.device, module, nullptr); + } + if (!lazy_compute_) { + lazy_compute_failed_ = true; + std::fprintf(stderr, "[rt] d3d12: compute pipeline %s could not be built at its first dispatch\n", + compute_entry_->name.c_str()); + } + return lazy_compute_; + } + // The graphics pipeline with the formats of the `unbound` slots (leonida::GraphicsPipeline::variant) undefined. VkPipeline build(std::uint32_t unbound) const { // The stride state is last: a pipeline without vertex bindings (a full-screen pass that builds its vertices @@ -4167,9 +4257,33 @@ class PipelineState final dynamic.pDynamicStates = dynamic_states; } + // LEONIDA_LAZY_PSO: stages without a module get one from the library's words for this pipeline only. + std::vector stages = r.stages; + struct ModuleCleanup { + const PipelineState& self; + std::vector modules; + ~ModuleCleanup() { + for (VkShaderModule m : modules) + self.device_.context->vk.vkDestroyShaderModule(self.device_.info.device, m, nullptr); + } + } cleanup{*this, {}}; + if (!r.lazy_modules.empty()) { + const leonida::ShaderLibrary* library = device_.library(); + if (!library) return VK_NULL_HANDLE; + for (const auto& [index, entry] : r.lazy_modules) { + const VkShaderModule module = make_module(library->spirv(entry)); + if (!module) { + std::fprintf(stderr, "[rt] d3d12: no shader module for %s at pipeline build\n", entry.name.c_str()); + return VK_NULL_HANDLE; + } + cleanup.modules.push_back(module); + stages[index].module = module; + } + } + VkGraphicsPipelineCreateInfo info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering}; - info.stageCount = std::uint32_t(r.stages.size()); - info.pStages = r.stages.data(); + info.stageCount = std::uint32_t(stages.size()); + info.pStages = stages.data(); info.pVertexInputState = r.mesh ? nullptr : &vertex_input; // ignored with a mesh stage; null for clarity info.pInputAssemblyState = r.mesh ? nullptr : &r.assembly; info.pViewportState = &viewport; @@ -4205,6 +4319,10 @@ class PipelineState final Recipe recipe_; std::mutex variants_mutex_; std::map variants_; + std::unique_ptr compute_entry_; // LEONIDA_LAZY_PSO: what the first dispatch compiles + VkPipeline lazy_compute_ = VK_NULL_HANDLE; + bool lazy_compute_failed_ = false; + leonida::SubgroupRequest compute_subgroup_{}; // decided at creation, applied by compile_compute VkShaderModule module_ = VK_NULL_HANDLE; std::vector modules_; VkDeviceSize code_base_ = 0; diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 889bb71f72..eda3fcff5b 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -752,6 +752,8 @@ struct ComputePipeline { VkPipelineLayout layout = VK_NULL_HANDLE; std::uint64_t code_base = 0; VkDescriptorSet bindless_set = VK_NULL_HANDLE; // set 0 of the layout, bound at every dispatch; null: none + // LEONIDA_LAZY_PSO: `pipeline` stays null and the first dispatch builds it through this (once, thread-safe). + std::function build; }; // A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it @@ -2100,13 +2102,17 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct !vk.draw_indexed || !vk.bind_pipeline || !vk.push_constants) return ReplayResult::unsupported; const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw.pipeline); - if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; + if (!pipeline) return ReplayResult::unresolved_resource; + // A pipeline created lazily (LEONIDA_LAZY_PSO) has no base pipeline until its first draw builds it as variant 0. + const VkPipeline base = pipeline->pipeline ? pipeline->pipeline + : (pipeline->variant ? pipeline->variant(0) : VK_NULL_HANDLE); + if (!base) return ReplayResult::unresolved_resource; if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw; if (draw.mesh && !vk.draw_mesh_tasks) return ReplayResult::unsupported; if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; if (pipeline->color_formats.size() > max_render_targets) return ReplayResult::unsupported; p.graphics = pipeline; - p.pipeline = pipeline->pipeline; + p.pipeline = base; p.area = {UINT32_MAX, UINT32_MAX}; std::uint32_t layers = UINT32_MAX; const auto shrink = [&](const ResourceBinding& b, const TargetView& view, const VkImageSubresourceRange& range) { @@ -3052,9 +3058,11 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (ind->kind == IndirectKind::dispatch && ind->pipeline) { // the pipeline and root arguments it was recorded if (!vk.bind_pipeline || !vk.push_constants || !vk.compute_pipeline) return ReplayResult::unsupported; const ComputePipeline* pipeline = vk.compute_pipeline(ind->pipeline); - if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; + if (!pipeline) return ReplayResult::unresolved_resource; if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; p.pipeline = *pipeline; + if (!p.pipeline.pipeline && pipeline->build) p.pipeline.pipeline = pipeline->build(); + if (!p.pipeline.pipeline) return ReplayResult::unresolved_resource; } } else if (const auto* build = std::get_if(&command)) { p.khr_instances = 0; @@ -3140,9 +3148,11 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!vk.bind_pipeline || !vk.push_constants || !vk.dispatch || !vk.compute_pipeline) return ReplayResult::unsupported; const ComputePipeline* pipeline = vk.compute_pipeline(dispatch->pipeline); - if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; + if (!pipeline) return ReplayResult::unresolved_resource; if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; p.pipeline = *pipeline; + if (!p.pipeline.pipeline && pipeline->build) p.pipeline.pipeline = pipeline->build(); + if (!p.pipeline.pipeline) return ReplayResult::unresolved_resource; } else if (const auto* draw = std::get_if(&command)) { if (out.draw_count == out.draws.size()) out.draws.emplace_back(); auto& prepared_draw = out.draws[out.draw_count];