diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 97d737c8e..0abc54aca 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2326,6 +2326,26 @@ Pipeline creation: serialized size and bytes are each device's own (the host's empty library is 900 bytes, the layer's 16). - Not compared: the calls the host runtime faults on (`Serialize(nullptr, n)`, `StorePipeline` with a null PSO, `Load*` with a null name or description); the layer answers `E_INVALIDARG` for each. +- Compiles at draw time: the first draw of a graphics pipeline, the first dispatch of a compute pipeline the warm-up + has not built, and each variant are compiled for the submission that needs them. `prepare()` leaves each one that is + not built yet to `PipelineCompiles`, once per pipeline and variant; `VulkanQueue::execute_now` then compiles them + side by side on the device's workers (`runtime/src/pipeline_workers.h`), the submitting thread among them, and writes + the command buffer when all are built. Every draw and dispatch has its own pipeline: none is left to a later frame. A + pipeline the driver refuses has the result it had when `prepare()` built it: a draw or an indirect dispatch fails the + submission, a dispatch is dropped (strict replay: fails it too). The resource lock is held while they compile, as it + is when each is compiled alone, so a PSO released meanwhile waits for the submission. The workers have ended before + the session cache is read at device teardown. `LEONIDA_PIPELINE_THREADS=` sets the workers: unset, half the + logical processors and at most 8; `0` compiles each pipeline on the submitting thread where `prepare()` meets it. + Graphics pipelines of 1 MiB of SPIR-V or more, and compute pipelines over 128 KiB (`LEONIDA_SERIAL_BIG_COMPILES`), + are compiled one after another beside the smaller ones, because a compile takes the driver some hundred bytes of + memory for each byte of SPIR-V ([pipeline_check.md](pipeline_check.md)); so are the variants of one PSO. + `LEONIDA_ASYNC_PIPELINES=1` is not changed: its builds stay on the compile worker. Measured with synthetic programs + never compiled before and the warm-up off (RTX 3080, NVIDIA 621.24, Windows 11, 16 logical processors, 8 workers, + three runs each): the first submission of 192 graphics pipelines takes 126 to 143 ms instead of 861 to 882, of 192 + variants 124 to 130 instead of 856 to 863, of 96 compute pipelines 74 to 81 instead of 486 to 519, and the process + holds about 50 MiB more (the driver keeps memory for each thread that compiles). One `VkPipelineCache` is enough: one + cache per thread, merged, was about as fast. Tested by `pipeline_workers`, `replay_pipeline_compiles` and + `d3d12_pipeline_workers`. **Open:** whether the game uses `D3D12_PIPELINE_STATE_STREAM_DESC` for mesh/RT and which subobject types appear. The trace will enumerate them. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 48c8af360..b09f28838 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -728,6 +728,12 @@ if(BUILD_TESTING) add_executable(pipeline_cache_file_test test/pipeline_cache_file_test.cpp) add_test(NAME pipeline_cache_file COMMAND pipeline_cache_file_test) + # The pool that compiles a submission's pipelines (runtime/src/pipeline_workers.h): pure stdlib. + add_executable(pipeline_workers_test test/pipeline_workers_test.cpp) + find_package(Threads REQUIRED) + target_link_libraries(pipeline_workers_test PRIVATE Threads::Threads) + add_test(NAME pipeline_workers COMMAND pipeline_workers_test) + set_tests_properties(pipeline_workers PROPERTIES TIMEOUT 120) # D3D-704's session-cache limit and header check: pure stdlib, no Vulkan headers. add_executable(pipeline_cache_store_test test/pipeline_cache_store_test.cpp) @@ -2193,6 +2199,18 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_texture_memory COMMAND d3d12_texture_memory_test) set_tests_properties(d3d12_texture_memory PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + # The pipelines a submission needs, compiled on the device's workers: the same image as without them. The second + # time with the pipelines compiled when they are created, which leaves the variants. + add_executable(d3d12_pipeline_workers_test test/d3d12_pipeline_workers_test.cpp) + target_link_libraries(d3d12_pipeline_workers_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_pipeline_workers_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_pipeline_workers_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_pipeline_workers COMMAND d3d12_pipeline_workers_test) + add_test(NAME d3d12_pipeline_workers_eager COMMAND d3d12_pipeline_workers_test) + set_tests_properties(d3d12_pipeline_workers d3d12_pipeline_workers_eager PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 180 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + set_tests_properties(d3d12_pipeline_workers_eager PROPERTIES + ENVIRONMENT "LEONIDA_LAZY_PIPELINES=0;LEONIDA_LAZY_COMPUTE=0") # ExecuteCommandLists refuses a list whose type isn't the queue's (debug-layer message 836). add_executable(d3d12_queue_list_type_test test/d3d12_queue_list_type_test.cpp) target_link_libraries(d3d12_queue_list_type_test PRIVATE gta6rt_d3d12_com) @@ -3984,6 +4002,15 @@ if(TARGET Vulkan::Headers) target_compile_definitions(replay_readback_stages_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) endif() add_test(NAME replay_readback_stages COMMAND replay_readback_stages_test) + # Pipelines not built yet, left to the pool of pipeline_workers.h: what prepare() alone would give (no GPU). + add_executable(replay_pipeline_compiles_test test/replay_pipeline_compiles_test.cpp) + target_link_libraries(replay_pipeline_compiles_test PRIVATE Vulkan::Headers Threads::Threads) + if(WIN32) + target_compile_definitions(replay_pipeline_compiles_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME replay_pipeline_compiles COMMAND replay_pipeline_compiles_test) + add_test(NAME replay_pipeline_compiles_strict COMMAND replay_pipeline_compiles_test) + set_tests_properties(replay_pipeline_compiles_strict PROPERTIES ENVIRONMENT "LEONIDA_STRICT_REPLAY=1") add_executable(replay_quad_list_test test/replay_quad_list_test.cpp) target_link_libraries(replay_quad_list_test PRIVATE Vulkan::Headers) if(WIN32) diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 0d76ae44a..de20462da 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -272,6 +272,8 @@ leonida::ResourceId uav_image_resource(ID3D12Resource* resource, std::uint64_t a VkBuffer vulkan_buffer(ID3D12Resource* resource); // What a device from create_vulkan_device* was created with (enabled features included), or null. For tests. const VulkanDeviceInfo* vulkan_device_info(ID3D12Device* device); +// The device's pipeline workers (src/pipeline_workers.h) and what they have compiled; zeros without any. For tests. +leonida::PipelineWorkers::Stats pipeline_worker_stats(ID3D12Device* device); // True when a slot-133 buffer is a shadow copied from the title's pages, false when they were imported. For tests. bool title_shadow_buffer(ID3D12Resource* resource); // VirtualQuery calls made by the title-buffer shadows in their latest refresh. For tests. diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 12494d201..bdae55341 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -1309,6 +1309,16 @@ bool console_format_stand_ins() { return on; } +// A driver's compiler needs hundreds of MiB for a very large module; several at once exhausted host memory. Compute modules +// over 128 KiB compile one at a time (LEONIDA_SERIAL_BIG_COMPILES=0: as many as are asked for). +bool serial_big_compile(std::size_t spirv_bytes) { + static const bool serial = [] { + wchar_t v[2]{}; + return !(GetEnvironmentVariableW(L"LEONIDA_SERIAL_BIG_COMPILES", v, 2) == 1 && v[0] == L'0'); + }(); + return serial && spirv_bytes > 128 * 1024; +} + bool startup_cache_checkpoints_enabled() { static const bool enabled = [] { wchar_t value[2]{}; @@ -7394,6 +7404,7 @@ class PipelineState final if (!mesh && topology_bits != leonida::topology_type_rect_list) graphics_.rectangle_variant_topology = leonida::topology_rect_list; + std::uint64_t spirv_bytes = 0; for (Stage& stage : stages) { if (!stage.entry) continue; // After the f16 link above, which can also edit the pixel shader's words. @@ -7408,6 +7419,7 @@ class PipelineState final stage.words = std::move(patched); } } + spirv_bytes += stage.words.size() * sizeof(std::uint32_t); if (trace_pipeline_compile()) { if (!profile_shaders_.empty()) profile_shaders_ += ','; profile_shaders_ += stage.entry->name; @@ -7793,6 +7805,13 @@ class PipelineState final return graphics_.async_build ? queue_build(false, unbound) : variant(unbound, "draw"); }); }; + graphics_.built = [this](std::uint32_t unbound) { + std::unique_lock lock(variants_mutex_, std::try_to_lock); // held: another thread is compiling one + if (!lock.owns_lock()) return VkPipeline(VK_NULL_HANDLE); + const auto it = variants_.find(unbound); + return it == variants_.end() ? VkPipeline(VK_NULL_HANDLE) : it->second; + }; + graphics_.large = spirv_bytes >= leonida::PipelineCompiles::large_spirv_bytes; if (code_stage) { VkDeviceSize offset = 0; @@ -7952,6 +7971,12 @@ class PipelineState final }); }; pipeline_.build_context = this; + pipeline_.built = [](void* self) { + auto* pso = static_cast(self); + std::unique_lock lock(pso->variants_mutex_, std::try_to_lock); // held: another thread is compiling it + return lock.owns_lock() ? pso->pipeline_.pipeline : VkPipeline(VK_NULL_HANDLE); + }; + pipeline_.large = serial_big_compile(spirv_bytes); } else if (!build_compute("compute-create")) { return E_FAIL; } @@ -7985,15 +8010,9 @@ class PipelineState final const leonida::ShaderLibrary* library = device_.library(); const leonida::ShaderEntry* entry = compute_entry_; if (!library || !entry) return VK_NULL_HANDLE; - // The driver's compiler needs hundreds of MiB per very large module; several at once exhausted host memory. - // Modules over 128 KiB compile one at a time (LEONIDA_SERIAL_BIG_COMPILES=0: as many as are asked for). - static const bool serial_big = [] { - wchar_t v[2]{}; - return !(GetEnvironmentVariableW(L"LEONIDA_SERIAL_BIG_COMPILES", v, 2) == 1 && v[0] == L'0'); - }(); static std::mutex big_compile; std::unique_lock big_lock(big_compile, std::defer_lock); - if (serial_big && stage_bytes_ > 128 * 1024) big_lock.lock(); + if (serial_big_compile(stage_bytes_)) big_lock.lock(); auto 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()); @@ -9696,6 +9715,17 @@ class Device final leonida::title_va_aliases().set_buffer_maker(this, [](void* device, std::uint64_t va, std::uint64_t bytes) { static_cast*>(device)->make_title_buffer(va, bytes); }); + { + char text[32] = {}; + size_t length = 0; + const bool present = getenv_s(&length, text, "LEONIDA_PIPELINE_THREADS") == 0 && length > 1; + const auto threads = leonida::pipeline_threads(present ? text : "", std::thread::hardware_concurrency()); + if (!threads.valid) + std::fprintf(stderr, "[rt] d3d12: LEONIDA_PIPELINE_THREADS=%s is not a number; using %u\n", text, + threads.count); + if (threads.count) + state_.context->set_pipeline_workers(std::make_unique(threads.count)); + } leonida::title_va_aliases().set_hooks( &state_, [](void* device, std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { @@ -10274,6 +10304,7 @@ class Device final "vkDeviceWaitIdle"); } state_.context->drain_deleted_resources(UINT64_MAX); + state_.context->set_pipeline_workers(nullptr); // before the pipeline cache is written and destroyed state_.context->set_bindless_release(nullptr, nullptr); state_.context->set_bindless_current(nullptr); // the retired generations go with state_.bindless below } @@ -15354,6 +15385,13 @@ VkBuffer vulkan_buffer(ID3D12Resource* resource) { return r ? r->buffer() : VK_NULL_HANDLE; } +leonida::PipelineWorkers::Stats pipeline_worker_stats(ID3D12Device* device) { + if (!device) return {}; + ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); + if (auto* d = Device::from(real ? real : device)) return d->context().pipeline_worker_stats(); + return {}; +} + const VulkanDeviceInfo* vulkan_device_info(ID3D12Device* device) { if (!device) return nullptr; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); diff --git a/runtime/src/pipeline_workers.h b/runtime/src/pipeline_workers.h new file mode 100644 index 000000000..664bfe0b8 --- /dev/null +++ b/runtime/src/pipeline_workers.h @@ -0,0 +1,173 @@ +// A bounded pool that compiles the pipelines of one submission side by side (docs/d3d12_vulkan.md, "Pipeline creation"). +// +// run() is a blocking parallel loop: the calling thread works on its own batch beside the workers, so a batch completes +// even with no worker left (no thread could be started, or stop() was called), and nothing outlives the call. Several +// threads may call run() at once; they share the workers. The workers are started by the first batch that can use them, +// so a device that never compiles at draw time has none. They are plain std::threads: a driver's compiler needs the 8 MB +// of stack the loader's header gives those (docs/pipeline_check.md, "Stack reserve"). +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +class PipelineWorkers { +public: + static constexpr unsigned kMaxThreads = 64; + + // What the pool has done: batches handed to the workers, the jobs in them, and the jobs running now. + struct Stats { + unsigned threads = 0; // the most workers the pool starts + std::size_t started = 0; // the workers it has started + std::uint64_t batches = 0; + std::uint64_t jobs = 0; + std::size_t running = 0; + }; + + explicit PipelineWorkers(unsigned threads) : limit_(std::min(threads, kMaxThreads)) {} + ~PipelineWorkers() { stop(); } + PipelineWorkers(const PipelineWorkers&) = delete; + PipelineWorkers& operator=(const PipelineWorkers&) = delete; + + unsigned threads() const { return limit_; } + + // Calls job(0) .. job(count - 1) and returns when every call has returned. When calls threw, rethrows what the + // lowest of them threw, after the last has returned. With no workers or a single job the calls are made in order on + // this thread, and the first exception ends them. + void run(std::size_t count, const std::function& job) { + if (!limit_ || count < 2) { + for (std::size_t i = 0; i < count; ++i) job(i); + return; + } + Batch batch{&job, count}; + std::unique_lock lock(mutex_); + queue_.push_back(&batch); + ++batches_; + jobs_ += count; + start(count - 1); + work_.notify_all(); + while (batch.next < batch.count) step(batch, lock); + batch.done.wait(lock, [&] { return !batch.running; }); + lock.unlock(); + if (batch.error) std::rethrow_exception(batch.error); + } + + // Ends the workers once each has finished the job it is in. A run() in progress on another thread finishes its + // remaining jobs itself, and so does every later one. + void stop() { + std::vector threads; + { + std::lock_guard lock(mutex_); + stopping_ = true; + threads.swap(threads_); + } + work_.notify_all(); + for (std::thread& thread : threads) thread.join(); + } + + Stats stats() { + std::lock_guard lock(mutex_); + return {limit_, started_, batches_, jobs_, running_}; + } + +private: + struct Batch { // on the stack of the run() that made it; guarded by mutex_ + const std::function* job; + std::size_t count; + std::size_t next = 0; + std::size_t running = 0; + std::exception_ptr error{}; + std::size_t error_index = 0; + std::condition_variable done{}; + }; + + // With mutex_ held: enough workers for `wanted` more jobs, within the limit. + void start(std::size_t wanted) { + wanted = std::min(wanted, limit_); + while (!stopping_ && !exhausted_ && threads_.size() < wanted) { + try { + threads_.emplace_back([this] { work(); }); + ++started_; + } catch (const std::system_error&) { + exhausted_ = true; // the workers there are, and the callers, do it all + } + } + } + + void work() { + std::unique_lock lock(mutex_); + for (;;) { + work_.wait(lock, [this] { return stopping_ || !queue_.empty(); }); + if (stopping_) return; + step(*queue_.front(), lock); + } + } + + // Takes the next job of `batch` (there is one), runs it unlocked, and returns locked. The batch leaves the queue + // with its last job, so no worker can reach it once run() has seen nothing left and nothing running. + void step(Batch& batch, std::unique_lock& lock) { + const std::size_t index = batch.next++; + if (batch.next == batch.count) std::erase(queue_, &batch); + ++batch.running; + ++running_; + lock.unlock(); + std::exception_ptr error; + try { + (*batch.job)(index); + } catch (...) { + error = std::current_exception(); + } + lock.lock(); + --running_; + if (error && (!batch.error || index < batch.error_index)) { + batch.error = std::move(error); + batch.error_index = index; + } + // Notified with the mutex held: run() cannot return, and end the batch, before this has. + if (!--batch.running && batch.next == batch.count) batch.done.notify_all(); + } + + const unsigned limit_; + std::mutex mutex_; + std::condition_variable work_; + std::deque queue_; // batches with jobs nobody has taken yet + std::vector threads_; + bool stopping_ = false; + bool exhausted_ = false; + std::size_t started_ = 0; + std::uint64_t batches_ = 0; + std::uint64_t jobs_ = 0; + std::size_t running_ = 0; +}; + +// LEONIDA_PIPELINE_THREADS: how many workers, 0 for none (pipelines compile on the thread that submits, as before). +// Unset or empty: half the logical processors and at most 8, past which the compiles of one submission gained little +// (docs/d3d12_vulkan.md). `valid` is false for text that is not a number, which counts as unset. +struct PipelineThreads { + unsigned count = 0; + bool valid = true; +}; + +inline PipelineThreads pipeline_threads(const char* text, unsigned logical_processors) { + const unsigned automatic = std::min(8u, logical_processors / 2); + if (!text || !*text) return {automatic, true}; + unsigned value = 0; + for (const char* c = text; *c; ++c) { + if (*c < '0' || *c > '9') return {automatic, false}; + value = std::min(PipelineWorkers::kMaxThreads, value * 10 + unsigned(*c - '0')); + } + return {value, true}; +} + +} // namespace leonida diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 5c3e884ba..9946331f9 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -14,6 +14,7 @@ #include "buffer_va_index.h" #include "image_memory.h" #include "occlusion_sum_spirv.h" +#include "pipeline_workers.h" #include "queue_holds.h" #include "retire_tickets.h" #include "statistics_sum_spirv.h" @@ -1428,6 +1429,17 @@ class VulkanContext { graphics_pipelines_[id] = pipeline; if (shaders && device_fault_) device_fault_->pipeline_names[id] = *shaders; } + // Workers for the pipelines a submission needs and that are not built yet. Null (the default): each is built where + // prepare() meets it, on the submitting thread. Replacing it waits for submissions that are compiling, and ends the + // workers it had. + void set_pipeline_workers(std::unique_ptr workers) { + std::unique_lock lock(resource_mutex_); + pipeline_workers_.swap(workers); + } + PipelineWorkers::Stats pipeline_worker_stats() { + std::shared_lock lock(resource_mutex_); + return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{}; + } // Configure before queue creation, when the selected queue family supports compute. void set_occlusion_resolve_memory(const VkPhysicalDeviceMemoryProperties& memory) { occlusion_resolve_memory_ = memory; @@ -2003,6 +2015,7 @@ class VulkanContext { std::unordered_map> sparse_resources_; std::unordered_map pipelines_; std::unordered_map graphics_pipelines_; + std::unique_ptr pipeline_workers_; std::unordered_map acceleration_structures_; LayoutTracker tracker_; std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only @@ -2803,9 +2816,18 @@ class VulkanQueue : private QueueHolds::Holder { const auto resolve = [this](ResourceId id) { return context_.resolve(id); }; std::uint32_t segments = 0, statistics_segments = 0; bool has_queries = false; + // With workers, the pipelines the lists need and that are not built yet are compiled together below instead of + // one after another in prepare(). resource_lock is held until they are all built, which keeps the pipeline + // states that own them alive (remove_pipeline takes it uniquely). + PipelineCompiles compiles; + if (context_.pipeline_workers_) replay.compiles = &compiles; + ReplayResult prepare_result = ReplayResult::success; for (std::size_t i = 0; i < lists.size(); ++i) { const auto result = prepare(*lists[i], resolve, replay, prepared[i], can_resolve_occlusion); - if (result != ReplayResult::success) return result; + if (result != ReplayResult::success) { + prepare_result = result; + break; + } if (prepared[i].segment_count > UINT32_MAX - segments || prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments) return queue_unsupported(__LINE__); @@ -2813,6 +2835,12 @@ class VulkanQueue : private QueueHolds::Holder { statistics_segments += prepared[i].statistics_segment_count; has_queries = has_queries || !prepared[i].queries.empty(); } + prepare_result = build_pipelines( + compiles, std::span(prepared).first(lists.size()), prepare_result, + [this](std::size_t count, const std::function& job) { + context_.pipeline_workers_->run(count, job); + }); + if (prepare_result != ReplayResult::success) return prepare_result; const auto segment_pool = [this](VkQueryType type, std::uint32_t count, std::shared_ptr& out) { const auto& vk = context_.vk; diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 2fef87194..6d1d60f03 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -803,6 +803,10 @@ struct ComputePipeline { VkPipeline (*build)(void*) = nullptr; void* build_context = nullptr; bool async_build = false; // a null handle may be waiting for the compile worker + // What `build` would return when it is built already and nobody is building it, else null; builds nothing. Null: a + // first use is always built where prepare() meets it. Not used with async_build. See PipelineCompiles. + VkPipeline (*built)(void*) = nullptr; + bool large = false; // compiled one after another with the other large ones (PipelineCompiles) bool skipped = false; // never built on request (LEONIDA_SKIP_COMPUTE): its dispatches are dropped }; @@ -830,6 +834,10 @@ struct GraphicsPipeline { // IA topology requiring a fourth-corner geometry stage. Zero when the PSO already contains the stage. std::uint32_t rectangle_variant_topology = 0; std::function variant; + // What `variant` would return when it is built already and nobody is building one, else null; builds nothing. See + // ComputePipeline::built. + std::function built; + bool large = false; // as ComputePipeline::large std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count bool async_build = false; }; @@ -915,7 +923,75 @@ inline ReplayResult unsupported_at(int line) { } +// The pipelines of a submission that are not built yet. prepare() adds each of them once and goes on; build_pipelines() +// then compiles them all and puts them where prepare() left them out. Holds pointers to registered pipelines: valid +// while the context's resource lock is held. +class PipelineCompiles { +public: + // Where a prepared command finds its pipeline: an index for `built`, plus one; 0 when it needs none. + using Ticket = std::uint32_t; + // Which command needs a pipeline: it decides what a pipeline that cannot be built means (build_pipelines). + enum class User : std::uint8_t { draw, dispatch, indirect_dispatch }; + struct Use { + Ticket ticket; + User user; + }; + // A compile takes the driver some hundred bytes of memory for each byte of SPIR-V (docs/pipeline_check.md): graphics + // pipelines of this much or more are `large`. + static constexpr std::uint64_t large_spirv_bytes = 1u << 20; + + Ticket add(const GraphicsPipeline& pipeline, std::uint32_t flags) { + return add({&pipeline, nullptr, flags}, User::draw); + } + Ticket add(const ComputePipeline& pipeline, User user) { return add({nullptr, &pipeline, 0}, user); } + + bool empty() const { return jobs_.empty(); } + std::size_t size() const { return jobs_.size(); } + VkPipeline built(Ticket ticket) const { return jobs_[ticket - 1].built; } + const std::vector& uses() const { return uses_; } // in the order of the commands + + // Compiles all of them through run(count, job) (PipelineWorkers::run): the large ones one after another, as without + // workers, beside the others. + template + void build(Run&& run) { + std::vector single, large; + for (std::size_t i = 0; i < jobs_.size(); ++i) (is_large(jobs_[i]) ? large : single).push_back(i); + const auto compile = [this](std::size_t i) { + Job& job = jobs_[i]; + job.built = job.graphics ? job.graphics->variant(job.flags) : job.compute->build(job.compute->build_context); + }; + const std::size_t chain = large.empty() ? 0 : 1; // the large ones are one unit, the first + run(chain + single.size(), [&](std::size_t i) { + if (i >= chain) + compile(single[i - chain]); + else + for (const std::size_t each : large) compile(each); + }); + } + +private: + struct Job { + const GraphicsPipeline* graphics; // one of the two + const ComputePipeline* compute; + std::uint32_t flags; + VkPipeline built = VK_NULL_HANDLE; + }; + static bool is_large(const Job& job) { return job.graphics ? job.graphics->large : job.compute->large; } + Ticket add(const Job& job, User user) { + const void* const pipeline = job.graphics ? static_cast(job.graphics) : job.compute; + const auto [it, added] = tickets_.try_emplace({pipeline, job.flags}, Ticket(jobs_.size() + 1)); + if (added) jobs_.push_back(job); + uses_.push_back({it->second, user}); + return it->second; + } + std::vector jobs_; + std::vector uses_; + std::map, Ticket> tickets_; +}; + struct ReplayFunctions { + // Set: prepare() leaves pipelines that are not built to it instead of building each on the spot. + PipelineCompiles* compiles = nullptr; std::function gpu_label; // Set 0 for the pipelines that declare one (their own `bindless_set` is only the marker): the device's current // generation of it, which a flush may have replaced since the pipeline was made. Null: the pipeline's. @@ -1179,6 +1255,7 @@ struct Prepared { VkDeviceSize fill_scratch_offset = 0; QueryPool* queries = nullptr; // query commands: the heap ComputePipeline pipeline; // dispatches + PipelineCompiles::Ticket compile = 0; // dispatches: where the pipeline comes from when it was not built yet std::uint32_t draw = 0; // draws: its PreparedDraw in PreparedList::draws std::uint32_t depth_uav_copy = UINT32_MAX; bool order_depth_uav = false; @@ -1224,6 +1301,7 @@ struct PreparedDraw { // lock across both), so it is not copied. const GraphicsPipeline* graphics = nullptr; VkPipeline pipeline = VK_NULL_HANDLE; // graphics->pipeline, or its variant for the slots the draw leaves unbound + PipelineCompiles::Ticket compile = 0; // where `pipeline` comes from when it was not built yet std::vector colors; // by slot; id 0 = unbound Attachment depth; std::vector vertex_buffers; @@ -1244,6 +1322,7 @@ struct PreparedDraw { skipped = false; graphics = nullptr; pipeline = VK_NULL_HANDLE; + compile = 0; colors.clear(); depth = {}; vertex_buffers.clear(); @@ -2462,12 +2541,17 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED && !p.colors[slot].id) unbound |= 1u << slot; if (pipeline->depth_format != VK_FORMAT_UNDEFINED && !p.depth.id) unbound |= GraphicsPipeline::unbound_depth; if (unbound || !p.pipeline) { - p.pipeline = pipeline->variant ? pipeline->variant(unbound) : VK_NULL_HANDLE; - if (!p.pipeline && pipeline->async_build && !strict_replay()) { - p.skipped = true; - return ReplayResult::success; + if (vk.compiles && pipeline->variant && pipeline->built && !pipeline->async_build) { + p.pipeline = pipeline->built(unbound); + if (!p.pipeline) p.compile = vk.compiles->add(*pipeline, unbound); + } else { + p.pipeline = pipeline->variant ? pipeline->variant(unbound) : VK_NULL_HANDLE; + if (!p.pipeline && pipeline->async_build && !strict_replay()) { + p.skipped = true; + return ReplayResult::success; + } + if (!p.pipeline) return unsupported_at(__LINE__); } - if (!p.pipeline) return unsupported_at(__LINE__); } // An unbound vertex-buffer slot reads zeros, as in D3D12: the zero page with stride 0. Per-instance slots with @@ -2534,6 +2618,20 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct return ReplayResult::success; } +// A compute pipeline that is built on first use: the one built already, the one vk.compiles will build with the +// submission's others (true, with p.compile set and no pipeline yet), or the one built here. +inline bool first_use(const ComputePipeline& pipeline, PipelineCompiles::User user, const ReplayFunctions& vk, Prepared& p) { + if (p.pipeline.pipeline || !pipeline.build) return p.pipeline.pipeline != VK_NULL_HANDLE; + if (vk.compiles && pipeline.built && !pipeline.async_build && !pipeline.skipped && + (!pipeline.bindless_set || vk.bind_descriptor_sets)) { + p.pipeline.pipeline = pipeline.built(pipeline.build_context); + if (!p.pipeline.pipeline) p.compile = vk.compiles->add(pipeline, user); + return true; + } + p.pipeline.pipeline = pipeline.build(pipeline.build_context); + return p.pipeline.pipeline != VK_NULL_HANDLE; +} + // An indexed quad list (D3D_PRIMITIVE_TOPOLOGY 19): the scratch and the compute job that turn the application's // indices into triangle-list indices (quad_index_expand.h). `p` is the draw as prepare_draw left it. A draw of // fewer than four indices has no quad and needs nothing. @@ -2665,6 +2763,32 @@ class PreparedList { std::vector khr_postbuilds; }; +// Ends the preparation of a submission whose prepare() calls used `compiles` and returned `result` (the first that +// failed, if any): builds the pipelines through run(count, job), puts them into `lists`, and returns what the calls would +// have returned had they built each pipeline themselves. Every use in `compiles` comes from a command before the one that +// failed, so a pipeline that cannot be built counts first, at the earliest command that uses it: it fails the list of a +// draw or an indirect dispatch, and a dispatch is dropped as prepare() drops one. +template +ReplayResult build_pipelines(PipelineCompiles& compiles, std::span lists, ReplayResult result, + Run&& run) { + if (compiles.empty()) return result; + compiles.build(run); + for (const PipelineCompiles::Use& use : compiles.uses()) { + if (compiles.built(use.ticket)) continue; + if (use.user == PipelineCompiles::User::draw) return unsupported_at(__LINE__); + if (use.user == PipelineCompiles::User::indirect_dispatch || strict_replay()) return unresolved_at(__LINE__); + unresolved_at(__LINE__); + } + if (result != ReplayResult::success) return result; + for (PreparedList& list : lists) { + for (detail::Prepared& command : list.commands) + if (command.compile) command.pipeline.pipeline = compiles.built(command.compile); + for (std::size_t i = 0; i < list.draw_count; ++i) + if (list.draws[i].compile) list.draws[i].pipeline = compiles.built(list.draws[i].compile); + } + return result; +} + inline ReplayResult plan_occlusion_segments(PreparedList& out) { // Active logical queries cover a contiguous range of physical slots. A Begin or End closes the old // slot and opens a new one if any query remains active. Each shared interval is recorded only once. @@ -3568,10 +3692,10 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun const ComputePipeline* pipeline = vk.compute_pipeline(ind->pipeline); if (!pipeline) return unresolved_at(__LINE__); p.pipeline = *pipeline; - if (!p.pipeline.pipeline && p.pipeline.build) p.pipeline.pipeline = p.pipeline.build(p.pipeline.build_context); - if (!p.pipeline.pipeline && p.pipeline.skipped) continue; // dropped on request, strict or not - if (!p.pipeline.pipeline && p.pipeline.async_build && !strict_replay()) continue; - if (!p.pipeline.pipeline) return unresolved_at(__LINE__); + const bool found = detail::first_use(*pipeline, PipelineCompiles::User::indirect_dispatch, vk, p); + if (!found && p.pipeline.skipped) continue; // dropped on request, strict or not + if (!found && p.pipeline.async_build && !strict_replay()) continue; + if (!found) return unresolved_at(__LINE__); if (pipeline->bindless_set && !vk.bind_descriptor_sets) return unsupported_at(__LINE__); } } else if (const auto* build = std::get_if(&command)) { @@ -3676,9 +3800,9 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun continue; } p.pipeline = *pipeline; - if (!p.pipeline.pipeline && p.pipeline.build) p.pipeline.pipeline = p.pipeline.build(p.pipeline.build_context); - if (!p.pipeline.pipeline && p.pipeline.skipped) continue; // dropped on request, strict or not - if (!p.pipeline.pipeline) { + const bool found = detail::first_use(*pipeline, PipelineCompiles::User::dispatch, vk, p); + if (!found && p.pipeline.skipped) continue; // dropped on request, strict or not + if (!found) { if (strict) return unresolved_at(__LINE__); if (!p.pipeline.async_build) unresolved_at(__LINE__); continue; diff --git a/runtime/test/d3d12_pipeline_workers_test.cpp b/runtime/test/d3d12_pipeline_workers_test.cpp new file mode 100644 index 000000000..8d567e226 --- /dev/null +++ b/runtime/test/d3d12_pipeline_workers_test.cpp @@ -0,0 +1,851 @@ +// Pipelines compiled by a submission on the device's workers (LEONIDA_PIPELINE_THREADS, src/pipeline_workers.h), through +// the D3D12 layer on a GPU. One submission draws 48 graphics pipeline states (16 of them with a render target left +// unbound, so through a variant) and dispatches 16 compute ones, each into its own pixels or buffer element; the image +// and the buffer are read back. +// - workers off (0) and on: the same bytes, the same number of compiles, and several at a time only with workers; +// - a compile the driver refuses: the same result, the same dropped dispatch and the same retry with and without workers; +// - two queues that need the same pipelines at once compile each once; +// - pipeline states released while a submission compiles: the ones it uses live on, and the release of any other waits +// until the submission has its pipelines; +// - a device whose last references go while its workers compile: the workers have ended before the pipeline cache is +// read for pipeline_cache.session.bin. +// With LEONIDA_LAZY_PIPELINES=0 and LEONIDA_LAZY_COMPUTE=0 the pipelines are compiled when they are created and only the +// variants are left to the submission; the cases that need more than that are then left out. +// The calls that create pipelines and read the cache are watched, and held back, through the device's vkGetDeviceProcAddr. +// Self-contained: builds its SPIR-V in memory. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "test_temp_dir.h" +#include "../shims/d3d12_com.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace std::chrono_literals; +using d3d12test::Ref; +using leonida::ReplayResult; +using Words = std::vector; + +constexpr unsigned kGraphics = 48, kVariants = 16, kCompute = 16, kPipelines = kGraphics + kCompute; +// Programs padded past PipelineCompiles::large_spirv_bytes: compiled one after another, as one job of the pool. The first +// of the graphics ones is drawn through a variant. +bool large_graphics(unsigned n) { return n % 16 == 5; } +bool large_compute(unsigned n) { return n % 8 == 3; } +constexpr unsigned kLargeGraphics = 3, kLargeVariants = 1, kLargeCompute = 2; +constexpr unsigned kExtent = 16; // the render target; each graphics pipeline draws one 2x2 cell + +#define CHECK(expr) \ + do { \ + if (!(expr)) { \ + std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #expr); \ + return false; \ + } \ + } while (0) + +// ---- The driver's pipeline calls, watched. ---- + +struct Hooks { + std::mutex mutex; + std::condition_variable changed; + bool closed = false; // creations wait while it is + int meet = 0; // creations wait (at most 10 s) until this many are in progress, the first time + int in_flight = 0; + int most_in_flight = 0; + int creates = 0; + int graphics = 0, compute = 0; // of those + int fail_graphics = -1; // the graphics or compute create (counted from 0) the driver refuses + int fail_compute = -1; + std::set threads; + // Threads that have created a pipeline while `track` was set and have not ended. + bool track = false; + int live = 0; + int cache_reads = 0; + bool cache_read_during_create = false; + bool cache_read_with_workers = false; + + void reset() { + std::lock_guard lock(mutex); + closed = track = cache_read_during_create = cache_read_with_workers = false; + meet = most_in_flight = creates = graphics = compute = cache_reads = 0; + fail_graphics = fail_compute = -1; + threads.clear(); + } + void open() { + std::lock_guard lock(mutex); + closed = false; + changed.notify_all(); + } + bool wait_in_flight(int count) { + std::unique_lock lock(mutex); + return changed.wait_for(lock, 10s, [&] { return in_flight >= count; }); + } +} hooks; + +struct Tracked { + bool on = false; + ~Tracked() { + if (!on) return; + std::lock_guard lock(hooks.mutex); + --hooks.live; + } +}; +thread_local Tracked tracked; + +PFN_vkGetInstanceProcAddr real_instance_proc = nullptr; +PFN_vkGetDeviceProcAddr real_device_proc = nullptr; +PFN_vkCreateGraphicsPipelines real_create_graphics = nullptr; +PFN_vkCreateComputePipelines real_create_compute = nullptr; +PFN_vkGetPipelineCacheData real_cache_data = nullptr; + +// False: the driver is to refuse this one. +bool enter_create(bool compute) { + std::unique_lock lock(hooks.mutex); + ++hooks.creates; + const int index = compute ? hooks.compute++ : hooks.graphics++; + hooks.most_in_flight = std::max(hooks.most_in_flight, ++hooks.in_flight); + hooks.threads.insert(std::this_thread::get_id()); + if (hooks.track && !tracked.on) { + tracked.on = true; + ++hooks.live; + } + hooks.changed.notify_all(); + if (hooks.meet) { + hooks.changed.wait_for(lock, 10s, [] { return !hooks.meet || hooks.in_flight >= hooks.meet; }); + hooks.meet = 0; + hooks.changed.notify_all(); + } + hooks.changed.wait(lock, [] { return !hooks.closed; }); + return index != (compute ? hooks.fail_compute : hooks.fail_graphics); +} + +void leave_create() { + std::lock_guard lock(hooks.mutex); + --hooks.in_flight; + hooks.changed.notify_all(); +} + +VKAPI_ATTR VkResult VKAPI_CALL create_graphics(VkDevice device, VkPipelineCache cache, std::uint32_t count, + const VkGraphicsPipelineCreateInfo* infos, + const VkAllocationCallbacks* allocator, VkPipeline* out) { + VkResult result = VK_ERROR_UNKNOWN; + if (enter_create(false)) result = real_create_graphics(device, cache, count, infos, allocator, out); + leave_create(); + return result; +} + +VKAPI_ATTR VkResult VKAPI_CALL create_compute(VkDevice device, VkPipelineCache cache, std::uint32_t count, + const VkComputePipelineCreateInfo* infos, + const VkAllocationCallbacks* allocator, VkPipeline* out) { + VkResult result = VK_ERROR_UNKNOWN; + if (enter_create(true)) result = real_create_compute(device, cache, count, infos, allocator, out); + leave_create(); + return result; +} + +VKAPI_ATTR VkResult VKAPI_CALL cache_data(VkDevice device, VkPipelineCache cache, std::size_t* size, void* data) { + { + std::lock_guard lock(hooks.mutex); + ++hooks.cache_reads; + if (hooks.in_flight) hooks.cache_read_during_create = true; + if (hooks.live > (tracked.on ? 1 : 0)) hooks.cache_read_with_workers = true; + } + return real_cache_data(device, cache, size, data); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL device_proc(VkDevice device, const char* name) { + const PFN_vkVoidFunction real = real_device_proc(device, name); + if (!real) return nullptr; + if (!std::strcmp(name, "vkCreateGraphicsPipelines")) { + real_create_graphics = reinterpret_cast(real); + return reinterpret_cast(create_graphics); + } + if (!std::strcmp(name, "vkCreateComputePipelines")) { + real_create_compute = reinterpret_cast(real); + return reinterpret_cast(create_compute); + } + if (!std::strcmp(name, "vkGetPipelineCacheData")) { + real_cache_data = reinterpret_cast(real); + return reinterpret_cast(cache_data); + } + return real; +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL instance_proc(VkInstance instance, const char* name) { + if (!std::strcmp(name, "vkGetDeviceProcAddr")) { + real_device_proc = reinterpret_cast(real_instance_proc(instance, name)); + return reinterpret_cast(device_proc); + } + return real_instance_proc(instance, name); +} + +// ---- The shaders. ---- + +void op(Words& out, std::uint16_t code, std::initializer_list operands) { + out.push_back((std::uint32_t(operands.size() + 1) << 16) | code); + out.insert(out.end(), operands.begin(), operands.end()); +} + +std::uint32_t bits(float f) { return std::bit_cast(f); } + +// 1.25 MiB of OpString, which compile to nothing, where the module's layout has them: before the decorations. +void pad(Words& w, std::uint32_t first_id) { + for (std::uint32_t i = 0; i < 5; ++i) { + const std::size_t at = w.size(); + w.resize(at + 65535, 0x20202020u); + w[at] = 65535u << 16 | 7; // OpString + w[at + 1] = first_id + i; + w.back() = 0; + } +} + +// A full-screen triangle from VertexIndex. +Words vertex_words() { + Words w = {0x07230203u, 0x00010500u, 0u, 42u, 0u}; + op(w, 17, {1}); // OpCapability Shader + op(w, 14, {0, 1}); // OpMemoryModel Logical GLSL450 + op(w, 15, {0, 4, 0x6e69616du, 0u, 10, 11}); // OpEntryPoint Vertex %4 "main" %10 %11 + op(w, 71, {10, 11, 0}); // OpDecorate %10 BuiltIn Position + op(w, 71, {11, 11, 42}); // OpDecorate %11 BuiltIn VertexIndex + op(w, 19, {1}); // %1 = OpTypeVoid + op(w, 33, {2, 1}); // %2 = OpTypeFunction %1 + op(w, 22, {3, 32}); // %3 = OpTypeFloat 32 + op(w, 23, {6, 3, 4}); // %6 = OpTypeVector %3 4 + op(w, 21, {15, 32, 1}); // %15 = OpTypeInt 32 1 + op(w, 32, {7, 3, 6}); // %7 = OpTypePointer Output %6 + op(w, 32, {8, 1, 15}); // %8 = OpTypePointer Input %15 + op(w, 59, {7, 10, 3}); // %10 = OpVariable (Position) + op(w, 59, {8, 11, 1}); // %11 = OpVariable (VertexIndex) + op(w, 43, {15, 24, 1}); // %24 = OpConstant 1 + op(w, 43, {15, 25, 2}); // %25 = OpConstant 2 + op(w, 43, {3, 26, bits(2.0f)}); + op(w, 43, {3, 27, bits(-1.0f)}); + op(w, 43, {3, 28, bits(0.0f)}); + op(w, 43, {3, 29, bits(1.0f)}); + op(w, 54, {1, 4, 0, 2}); // OpFunction + op(w, 248, {30}); // OpLabel + op(w, 61, {15, 31, 11}); // %31 = VertexIndex + op(w, 196, {15, 32, 31, 24}); // %32 = %31 << 1 + op(w, 199, {15, 33, 32, 25}); // %33 = %32 & 2 + op(w, 199, {15, 34, 31, 25}); // %34 = %31 & 2 + op(w, 111, {3, 35, 33}); + op(w, 111, {3, 36, 34}); + op(w, 133, {3, 37, 35, 26}); + op(w, 133, {3, 38, 36, 26}); + op(w, 129, {3, 39, 37, 27}); // x = 2 * %35 - 1 + op(w, 129, {3, 40, 38, 27}); // y = 2 * %36 - 1 + op(w, 80, {6, 41, 39, 40, 28, 29}); + op(w, 62, {10, 41}); // Position = (x, y, 0, 1) + op(w, 253, {}); + op(w, 56, {}); + return w; +} + +// The colour (n/255, (255 - 2n)/255, 0.25 * FragCoord.x / 16 + 0.5, 1) of pipeline n: a constant of its own, and one that +// depends on the pixel. +Words fragment_words(unsigned n) { + Words w = {0x07230203u, 0x00010500u, 0u, 40u, 0u}; + op(w, 17, {1}); + op(w, 14, {0, 1}); + op(w, 15, {4, 4, 0x6e69616du, 0u, 8, 9}); // OpEntryPoint Fragment %4 "main" %8 %9 + op(w, 16, {4, 7}); // OpExecutionMode OriginUpperLeft + if (large_graphics(n)) pad(w, 30); + op(w, 71, {8, 11, 15}); // OpDecorate %8 BuiltIn FragCoord + op(w, 71, {9, 30, 0}); // OpDecorate %9 Location 0 + op(w, 19, {1}); + op(w, 33, {2, 1}); + op(w, 22, {3, 32}); + op(w, 23, {6, 3, 4}); + op(w, 32, {7, 1, 6}); + op(w, 32, {10, 3, 6}); + op(w, 59, {7, 8, 1}); + op(w, 59, {10, 9, 3}); + op(w, 43, {3, 20, bits(float(n) / 255.0f)}); + op(w, 43, {3, 21, bits(float(255 - 2 * n) / 255.0f)}); + op(w, 43, {3, 22, bits(0.25f / float(kExtent))}); + op(w, 43, {3, 23, bits(0.5f)}); + op(w, 43, {3, 24, bits(1.0f)}); + op(w, 54, {1, 4, 0, 2}); + op(w, 248, {11}); + op(w, 61, {6, 12, 8}); + op(w, 81, {3, 13, 12, 0}); // FragCoord.x + op(w, 133, {3, 14, 13, 22}); + op(w, 129, {3, 15, 14, 23}); + op(w, 80, {6, 16, 20, 21, 15, 24}); + op(w, 62, {9, 16}); + op(w, 253, {}); + op(w, 56, {}); + return w; +} + +// Stores 1000 + n at the root UAV's element s[6] (the translator's push-constant block; the console's compute arguments +// start at s[4]: s[4]:s[5] is the root UAV's console VA, s[6] the root constant). +Words compute_words(unsigned n) { + Words w = {0x07230203u, 0x00010500u, 0u, 80u, 0u}; + op(w, 17, {1}); + op(w, 17, {11}); // Int64 + op(w, 17, {5347}); // PhysicalStorageBufferAddresses + op(w, 14, {5348, 1}); // OpMemoryModel PhysicalStorageBuffer64 GLSL450 + op(w, 15, {5, 4, 0x6e69616du, 0u, 20}); // OpEntryPoint GLCompute %4 "main" %20 + op(w, 16, {4, 17, 1, 1, 1}); // OpExecutionMode LocalSize 1 1 1 + if (large_compute(n)) pad(w, 70); + op(w, 71, {17, 6, 4}); // ArrayStride 4 + op(w, 71, {18, 2}); // Block + op(w, 72, {18, 0, 35, 0}); // s[32], heap base, code base + op(w, 72, {18, 1, 35, 128}); + op(w, 72, {18, 2, 35, 136}); + op(w, 71, {23, 2}); + op(w, 72, {23, 0, 35, 0}); + op(w, 19, {1}); + op(w, 33, {2, 1}); + op(w, 21, {6, 32, 0}); // %6 = uint + op(w, 21, {11, 64, 0}); // %11 = ulong + op(w, 43, {6, 16, 32}); + op(w, 28, {17, 6, 16}); + op(w, 30, {18, 17, 11, 11}); + op(w, 32, {19, 9, 18}); + op(w, 59, {19, 20, 9}); // %20 = the push-constant block + op(w, 32, {21, 9, 6}); + op(w, 32, {22, 9, 11}); + op(w, 30, {23, 6}); + op(w, 32, {24, 5349, 23}); + op(w, 32, {25, 5349, 6}); + op(w, 43, {6, 26, 0}); + op(w, 43, {6, 27, 1}); + op(w, 43, {6, 28, 4}); + op(w, 43, {6, 32, 5}); + op(w, 43, {6, 33, 6}); + op(w, 43, {11, 29, 32, 0}); + op(w, 43, {11, 30, 2, 0}); + op(w, 43, {6, 31, 1000 + n}); + op(w, 54, {1, 4, 0, 2}); + op(w, 248, {40}); + op(w, 65, {21, 41, 20, 26, 28}); + op(w, 65, {21, 42, 20, 26, 32}); + op(w, 65, {21, 43, 20, 26, 33}); + op(w, 65, {22, 44, 20, 27}); + op(w, 61, {6, 45, 41}); + op(w, 61, {6, 46, 42}); + op(w, 61, {6, 47, 43}); + op(w, 61, {11, 48, 44}); + op(w, 113, {11, 49, 45}); + op(w, 113, {11, 50, 46}); + op(w, 113, {11, 51, 47}); + op(w, 196, {11, 52, 50, 29}); // s[5] << 32 + op(w, 196, {11, 53, 51, 30}); // s[6] << 2 + op(w, 197, {11, 54, 52, 49}); + op(w, 128, {11, 55, 54, 53}); + op(w, 128, {11, 56, 55, 48}); // + heap base + op(w, 120, {24, 57, 56}); // OpConvertUToPtr + op(w, 65, {25, 58, 57, 26}); + op(w, 62, {58, 31, 2, 4}); // OpStore Aligned 4 + op(w, 253, {}); + op(w, 56, {}); + return w; +} + +std::vector program(unsigned stage, unsigned n) { + return d3d12test::fssm_program({0x50574b00u + stage, n, 0xbf810000u}); +} + +bool write_library(const std::filesystem::path& dir) { + const auto write = [&](const std::string& name, const Words& words) { + std::ofstream f(dir / (name + ".spv"), std::ios::binary | std::ios::trunc); + f.write(reinterpret_cast(words.data()), std::streamsize(words.size() * 4)); + return bool(f); + }; + CHECK(write("vs", vertex_words())); + std::ofstream index(dir / "index.json", std::ios::binary | std::ios::trunc); + index << "{\"vs\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(program(0, 0)) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": []}"; + for (unsigned n = 0; n <= kGraphics; ++n) { // one more than is drawn: the pipeline state released on its own + const std::string name = "ps" + std::to_string(n); + CHECK(write(name, fragment_words(n))); + index << ",\n\"" << name << "\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(program(1, n)) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"inputs\": [], \"outputs\": [0]}"; + } + for (unsigned n = 0; n < kCompute; ++n) { + const std::string name = "cs" + std::to_string(n); + CHECK(write(name, compute_words(n))); + index << ",\n\"" << name << "\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(program(2, n)) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"local_size\": [1, 1, 1], \"wave64\": false}"; + } + index << "}"; + return bool(index); +} + +// ---- The device and what it draws. ---- + +// The settings the runtime reads once: with both off, pipelines are compiled when they are created. +bool off(const char* name) { + char value[8]{}; + std::size_t length = 0; + return getenv_s(&length, value, name) == 0 && length == 2 && value[0] == '0'; +} +const bool first_use = !off("LEONIDA_LAZY_PIPELINES"); + +struct Setup { + vktest::Device* vk; + std::string library; + + bool device(const char* threads, Ref& out) const { + _putenv_s("LEONIDA_PIPELINE_THREADS", threads); + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = instance_proc; + info.instance = vk->instance; + info.physical = vk->physical; + info.device = vk->device; + info.queue = vk->queue; + info.queue_family = vk->family; + info.buffer_device_address = true; + info.subgroup = vk->subgroup; + info.features = vk->enabled; + info.shader_dir = library; + CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&out.p)))); + return true; + } +}; + +struct Pipelines { + Ref root; + std::vector states; // kGraphics, then kCompute + ~Pipelines() { release(); } + void release() { + for (auto* s : states) s->Release(); + states.clear(); + } + + static ID3D12PipelineState* graphics(ID3D12Device* dev, ID3D12RootSignature* root, unsigned n) { + const auto vs = d3d12test::shader_container(program(0, 0)), ps = d3d12test::shader_container(program(1, n)); + D3D12_GRAPHICS_PIPELINE_STATE_DESC pd{}; + pd.pRootSignature = root; + pd.VS = {vs.data(), vs.size()}; + pd.PS = {ps.data(), ps.size()}; + for (auto& rt : pd.BlendState.RenderTarget) { + rt.SrcBlend = rt.SrcBlendAlpha = D3D12_BLEND_ONE; + rt.DestBlend = rt.DestBlendAlpha = D3D12_BLEND_ZERO; + rt.BlendOp = rt.BlendOpAlpha = D3D12_BLEND_OP_ADD; + rt.LogicOp = D3D12_LOGIC_OP_NOOP; + rt.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + } + pd.SampleMask = UINT_MAX; + pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pd.RasterizerState.DepthClipEnable = TRUE; + pd.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + pd.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + pd.NumRenderTargets = n < kVariants ? 2 : 1; // the second is never bound: those draws take a variant + for (UINT i = 0; i < pd.NumRenderTargets; ++i) pd.RTVFormats[i] = DXGI_FORMAT_R8G8B8A8_UNORM; + pd.SampleDesc = {1, 0}; + ID3D12PipelineState* out = nullptr; + return SUCCEEDED(dev->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&out))) ? out : nullptr; + } + + bool create(ID3D12Device* dev) { + D3D12_ROOT_PARAMETER params[2]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[1].Constants.Num32BitValues = 1; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc{}; + desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto blob = d3d12test::serialize_root_signature(desc); + CHECK(SUCCEEDED(dev->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root.p)))); + for (unsigned n = 0; n < kGraphics; ++n) { + auto* state = graphics(dev, root.p, n); + CHECK(state); + states.push_back(state); + } + for (unsigned n = 0; n < kCompute; ++n) { + const auto cs = d3d12test::shader_container(program(2, n)); + D3D12_COMPUTE_PIPELINE_STATE_DESC pd{}; + pd.pRootSignature = root.p; + pd.CS = {cs.data(), cs.size()}; + ID3D12PipelineState* state = nullptr; + CHECK(SUCCEEDED(dev->CreateComputePipelineState(&pd, IID_PPV_ARGS(&state)))); + states.push_back(state); + } + return true; + } +}; + +// A queue, and two lists that use every pipeline once and copy what they wrote to a readback buffer. +struct Frame { + Ref target, buffer, readback; + Ref rtvs; + Ref queue; + Ref allocator; + Ref lists[2]; + Ref fence; + UINT64 fence_value = 0; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT foot{}; + + bool create(ID3D12Device* dev, const Pipelines& p) { + const D3D12_HEAP_PROPERTIES def{D3D12_HEAP_TYPE_DEFAULT}, back{D3D12_HEAP_TYPE_READBACK}; + D3D12_RESOURCE_DESC td{}; + td.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + td.Width = td.Height = kExtent; + td.DepthOrArraySize = td.MipLevels = 1; + td.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + td.SampleDesc = {1, 0}; + td.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + CHECK(SUCCEEDED(dev->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &td, D3D12_RESOURCE_STATE_RENDER_TARGET, + nullptr, IID_PPV_ARGS(&target.p)))); + const auto bd = d3d12test::buffer_desc(4 * kCompute, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + CHECK(SUCCEEDED(dev->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &bd, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&buffer.p)))); + UINT64 image_bytes = 0; + dev->GetCopyableFootprints(&td, 0, 1, 0, &foot, nullptr, nullptr, &image_bytes); + const auto rd = d3d12test::buffer_desc(4096 + 4 * kCompute); + CHECK(image_bytes <= 4096); + CHECK(SUCCEEDED(dev->CreateCommittedResource(&back, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&readback.p)))); + const D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; + CHECK(SUCCEEDED(dev->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&rtvs.p)))); + const auto rtv = rtvs->GetCPUDescriptorHandleForHeapStart(); + dev->CreateRenderTargetView(target.p, nullptr, rtv); + const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT}; + CHECK(SUCCEEDED(dev->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p)))); + CHECK(SUCCEEDED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + CHECK(SUCCEEDED(dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + for (int l = 0; l < 2; ++l) { + auto& list = lists[l]; + CHECK(SUCCEEDED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + if (l == 0) { + const FLOAT clear[4] = {0, 0, 0, 0}; + list->ClearRenderTargetView(rtv, clear, 0, nullptr); + } + list->SetGraphicsRootSignature(p.root.p); + list->SetComputeRootSignature(p.root.p); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + const D3D12_VIEWPORT vp{0, 0, float(kExtent), float(kExtent), 0, 1}; + list->RSSetViewports(1, &vp); + list->SetComputeRootUnorderedAccessView(0, buffer->GetGPUVirtualAddress()); + for (unsigned n = unsigned(l); n < kPipelines; n += 2) { // the even ones in one list, the odd in the other + list->SetPipelineState(p.states[n]); + if (n < kGraphics) { + const LONG x = LONG(n % 8 * 2), y = LONG(n / 8 * 2); + const D3D12_RECT cell{x, y, x + 2, y + 2}; + list->RSSetScissorRects(1, &cell); + list->DrawInstanced(3, 1, 0, 0); + list->DrawInstanced(3, 1, 0, 0); // again: the same pipeline, once compiled + } else { + list->SetComputeRoot32BitConstant(1, n - kGraphics, 0); + list->Dispatch(1, 1, 1); + } + } + CHECK(l == 0 || copy_back(list.p)); + CHECK(SUCCEEDED(list->Close())); + } + return true; + } + + bool copy_back(ID3D12GraphicsCommandList* list) { + const D3D12_RESOURCE_BARRIER to_source[2] = { + d3d12test::transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE), + d3d12test::transition(buffer.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)}; + list->ResourceBarrier(2, to_source); + D3D12_TEXTURE_COPY_LOCATION src{target.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + src.SubresourceIndex = 0; + D3D12_TEXTURE_COPY_LOCATION dst{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + dst.PlacedFootprint = foot; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + list->CopyBufferRegion(readback.p, 4096, buffer.p, 0, 4 * kCompute); + const D3D12_RESOURCE_BARRIER back[2] = { + d3d12test::transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET), + d3d12test::transition(buffer.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)}; + list->ResourceBarrier(2, back); + return true; + } + + ReplayResult submit() { + ID3D12CommandList* both[] = {lists[0].p, lists[1].p}; + queue->ExecuteCommandLists(2, both); + const ReplayResult result = rt::d3d12::last_execute_result(queue.p); + queue->Signal(fence.p, ++fence_value); + fence->SetEventOnCompletion(fence_value, nullptr); + return result; + } + + // The image's rows, then the buffer; the readback buffer is cleared, so stale bytes cannot pass. + std::vector read() { + std::vector out; + void* mapped = nullptr; + if (FAILED(readback->Map(0, nullptr, &mapped)) || !mapped) return out; + auto* bytes = static_cast(mapped); + for (unsigned y = 0; y < kExtent; ++y) + out.insert(out.end(), bytes + foot.Offset + y * foot.Footprint.RowPitch, + bytes + foot.Offset + y * foot.Footprint.RowPitch + 4 * kExtent); + out.insert(out.end(), bytes + 4096, bytes + 4096 + 4 * kCompute); + std::memset(bytes, 0xee, 4096 + 4 * kCompute); + readback->Unmap(0, nullptr); + return out; + } +}; + +// What the shaders say, for the exact channels: red is the pipeline's number, green 255 - 2n, and the buffer 1000 + n. +bool expected(const std::vector& bytes) { + CHECK(bytes.size() == 4 * kExtent * kExtent + 4 * kCompute); + for (unsigned n = 0; n < kGraphics; ++n) + for (unsigned dy = 0; dy < 2; ++dy) + for (unsigned dx = 0; dx < 2; ++dx) { + const auto* pixel = &bytes[4 * ((n / 8 * 2 + dy) * kExtent + n % 8 * 2 + dx)]; + CHECK(pixel[0] == n && pixel[1] == 255 - 2 * n && pixel[3] == 255 && pixel[2] >= 127 && pixel[2] <= 192); + } + for (unsigned n = 0; n < kCompute; ++n) { + std::uint32_t value = 0; + std::memcpy(&value, &bytes[4 * kExtent * kExtent + 4 * n], 4); + CHECK(value == 1000 + n); + } + return true; +} + +std::vector reference; // what the device without workers drew + +// One device: creates, submits twice, and leaves the bytes of both submissions (equal) in `out`. +bool draw_all(const Setup& setup, const char* threads, int meet, std::vector& out) { + Ref dev; + CHECK(setup.device(threads, dev)); + Pipelines pipelines; + Frame frame; + hooks.reset(); + CHECK(pipelines.create(dev.p)); + const int at_creation = hooks.creates; + CHECK(frame.create(dev.p, pipelines)); + { + std::lock_guard lock(hooks.mutex); + hooks.meet = meet; + hooks.most_in_flight = 0; + } + CHECK(frame.submit() == ReplayResult::success); + out = frame.read(); + CHECK(expected(out)); + // First use: each base pipeline the draws need (none of the variants'), each variant, each compute pipeline, once. + // Otherwise the base and compute pipelines were built at creation and only the variants are left. + CHECK(at_creation == (first_use ? 0 : int(kPipelines))); + const int drawn = hooks.creates - at_creation; + CHECK(drawn == int(first_use ? kPipelines : kVariants)); + const auto stats = rt::d3d12::pipeline_worker_stats(dev.p); + const bool workers = std::strcmp(threads, "0") != 0; + CHECK(stats.threads == unsigned(std::atoi(threads))); + const unsigned large = first_use ? kLargeGraphics + kLargeCompute : kLargeVariants; + CHECK(stats.batches == (workers ? 1u : 0u) && !stats.running); + CHECK(stats.jobs == (workers ? unsigned(drawn) - large + 1 : 0u)); + CHECK(workers ? hooks.most_in_flight >= 2 && hooks.most_in_flight <= std::atoi(threads) + 1 + : hooks.most_in_flight == 1); + CHECK(workers || hooks.threads.size() == 1); + CHECK(hooks.threads.size() <= std::size_t(std::atoi(threads)) + 1); + CHECK(frame.submit() == ReplayResult::success); + CHECK(frame.read() == out); + CHECK(hooks.creates == at_creation + drawn); + CHECK(rt::d3d12::pipeline_worker_stats(dev.p).batches == stats.batches); + return true; +} + +bool same_image(const Setup& setup) { + std::vector out; + CHECK(draw_all(setup, "0", 0, reference)); + for (const char* threads : {"1", "4", "16"}) { + CHECK(draw_all(setup, threads, 2, out)); + CHECK(out == reference); + } + return true; +} + +// The driver refuses one graphics compile: the submission is unsupported and nothing of it is drawn; the next one succeeds. +bool refused_graphics(const Setup& setup) { + for (const char* threads : {"0", "4"}) { + Ref dev; + CHECK(setup.device(threads, dev)); + Pipelines pipelines; + Frame frame; + CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines)); + hooks.reset(); + hooks.fail_graphics = 4; + CHECK(frame.submit() == ReplayResult::unsupported); + // Serially the fifth draw's is the last one tried; with workers the others were asked for too. + const bool workers = std::strcmp(threads, "0") != 0; + CHECK(hooks.creates == (workers ? int(kPipelines) : 5)); + hooks.reset(); + CHECK(frame.submit() == ReplayResult::success); + CHECK(frame.read() == reference); + CHECK(hooks.creates == (workers ? 1 : int(kPipelines) - 4)); + } + return true; +} + +// The driver refuses one compute compile: its dispatch is dropped, the rest of the submission runs, and it is not tried +// again, with and without workers. +bool refused_compute(const Setup& setup) { + for (const char* threads : {"0", "4"}) { + Ref dev; + CHECK(setup.device(threads, dev)); + Pipelines pipelines; + Frame frame; + CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines)); + hooks.reset(); + hooks.fail_compute = 4; + for (int round = 0; round < 2; ++round) { + CHECK(frame.submit() == ReplayResult::success); + const auto bytes = frame.read(); + CHECK(std::equal(bytes.begin(), bytes.begin() + 4 * kExtent * kExtent, reference.begin())); + unsigned missing = 0; + for (unsigned n = 0; n < kCompute; ++n) { + std::uint32_t value = 0; + std::memcpy(&value, &bytes[4 * kExtent * kExtent + 4 * n], 4); + CHECK(value == 1000 + n || value == 0); // a committed buffer reads zero where nothing wrote it + missing += value == 0; + } + CHECK(missing == 1); + CHECK(hooks.creates == int(kPipelines)); + } + } + return true; +} + +// Two queues submit the same pipelines at once: each is compiled once and both images are right. +bool two_queues(const Setup& setup) { + for (int round = 0; round < 3; ++round) { + Ref dev; + CHECK(setup.device("4", dev)); + Pipelines pipelines; + Frame frames[2]; + CHECK(pipelines.create(dev.p) && frames[0].create(dev.p, pipelines) && frames[1].create(dev.p, pipelines)); + hooks.reset(); + hooks.meet = 2; + ReplayResult results[2]{}; + std::vector bytes[2]; + std::thread threads[2]; + for (int i = 0; i < 2; ++i) + threads[i] = std::thread([&, i] { + results[i] = frames[i].submit(); + bytes[i] = frames[i].read(); + }); + for (auto& t : threads) t.join(); + for (int i = 0; i < 2; ++i) CHECK(results[i] == ReplayResult::success && bytes[i] == reference); + CHECK(hooks.creates == int(kPipelines)); + } + return true; +} + +// Pipeline states released while a submission compiles them, and one it does not use. +bool released_while_compiling(const Setup& setup) { + Ref dev; + CHECK(setup.device("4", dev)); + Pipelines pipelines; + Frame frame; + CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines)); + auto* other = Pipelines::graphics(dev.p, pipelines.root.p, kGraphics); + CHECK(other); + hooks.reset(); + hooks.closed = true; + ReplayResult result = ReplayResult::unsupported; + std::thread submitting([&] { result = frame.submit(); }); + const bool compiling = hooks.wait_in_flight(2); + pipelines.release(); // the application's references; the lists keep theirs + std::atomic released = false; + std::thread releasing([&] { + other->Release(); + released = true; + }); + std::this_thread::sleep_for(200ms); + const bool early = released; + hooks.open(); + submitting.join(); + releasing.join(); + CHECK(compiling); + CHECK(!early); // its destructor waits for the submission that looks pipelines up + CHECK(result == ReplayResult::success && frame.read() == reference); + return true; +} + +// The device's last references are released by the thread whose submission is compiling. +bool device_destroyed(const Setup& setup) { + _putenv_s("LEONIDA_PIPELINE_CACHE_BYTES", "1"); // read the cache at teardown, write no file + Ref dev; + CHECK(setup.device("4", dev)); + auto pipelines = std::make_unique(); + auto frame = std::make_unique(); + CHECK(pipelines->create(dev.p) && frame->create(dev.p, *pipelines)); + hooks.reset(); + hooks.track = true; + hooks.closed = true; + ReplayResult result = ReplayResult::unsupported; + std::vector bytes; + std::thread submitting([&] { + result = frame->submit(); + bytes = frame->read(); + frame.reset(); + pipelines.reset(); + }); + const bool compiling = hooks.wait_in_flight(2); + dev.reset(); + hooks.open(); + submitting.join(); + _putenv_s("LEONIDA_PIPELINE_CACHE_BYTES", "0"); + CHECK(compiling); + CHECK(result == ReplayResult::success && bytes == reference); + CHECK(hooks.cache_reads > 0); + CHECK(!hooks.cache_read_during_create); + CHECK(!hooks.cache_read_with_workers); + CHECK(hooks.live == 0); + return true; +} + +bool run(const Setup& setup) { + if (!same_image(setup)) return false; + return !first_use || (refused_graphics(setup) && refused_compute(setup) && two_queues(setup) && + released_while_compiling(setup) && device_destroyed(setup)); +} + +} // namespace + +int main() { + vktest::Device vk; + vk.request_buffer_device_address = true; + const auto status = vk.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + if (status != vktest::DeviceStatus::ready) return 1; + VkPhysicalDeviceProperties properties{}; + vk.instance_fn("vkGetPhysicalDeviceProperties")(vk.physical, &properties); + if (!vk.buffer_device_address || !vk.enabled.shaderInt64) { + std::printf("SKIP: the GPU lacks bufferDeviceAddress or shaderInt64\n"); + return 77; + } + if (properties.limits.maxPushConstantsSize < 144) { + std::printf("SKIP: maxPushConstantsSize %u, below the 144-byte block\n", properties.limits.maxPushConstantsSize); + return 77; + } + real_instance_proc = vk.instance_proc; + _putenv_s("LEONIDA_PIPELINE_CACHE_BYTES", "0"); // no session file in or out + _putenv_s("LEONIDA_COMPUTE_WARMUP", "0"); // every compile is a submission's + const testfiles::ScratchDir library("leonida_pipeline_workers_test"); + if (!write_library(library.path())) return 1; + if (!run({&vk, library.path().string()})) return 1; + if (vk.validation_errors()) { + std::fprintf(stderr, "FAIL: %u validation errors\n", vk.validation_errors()); + return 1; + } + std::printf("d3d12_pipeline_workers_test: passed on %s\n", properties.deviceName); + return 0; +} diff --git a/runtime/test/pipeline_workers_test.cpp b/runtime/test/pipeline_workers_test.cpp new file mode 100644 index 000000000..22aa4e768 --- /dev/null +++ b/runtime/test/pipeline_workers_test.cpp @@ -0,0 +1,292 @@ +// PipelineWorkers (runtime/src/pipeline_workers.h): every job runs once and before run() returns, on the workers and on +// the caller; with no workers, after stop(), with several callers at once and when jobs throw. CPU only, no Vulkan. + +#include "../src/pipeline_workers.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using leonida::PipelineWorkers; +using namespace std::chrono_literals; + +std::atomic failures = 0; +void check(bool ok, const char* what) { + if (ok) return; + std::printf("FAIL: %s\n", what); + ++failures; +} + +// Waits until `ready`, at most 10 s: a job that never comes fails the test instead of hanging it. +template +bool wait_for(Ready ready) { + const auto end = std::chrono::steady_clock::now() + 10s; + while (!ready()) { + if (std::chrono::steady_clock::now() > end) return false; + std::this_thread::sleep_for(1ms); + } + return true; +} + +// Time spent in a job. Not a sleep: those end on the system's timer tick, up to 16 ms later. +void spend(std::chrono::microseconds time) { + const auto end = std::chrono::steady_clock::now() + time; + while (std::chrono::steady_clock::now() < end) std::this_thread::yield(); +} + +// No workers, or one job: on the calling thread, in order, and no thread is started. +void inline_runs() { + for (const unsigned threads : {0u, 4u}) { + PipelineWorkers pool(threads); + std::vector order; + std::set ids; + const auto job = [&](std::size_t i) { + order.push_back(i); + ids.insert(std::this_thread::get_id()); + }; + pool.run(0, job); + check(order.empty(), "run(0) called the job"); + pool.run(1, job); + if (!threads) pool.run(5, job); + check(order == (threads ? std::vector{0} : std::vector{0, 0, 1, 2, 3, 4}), + "inline jobs out of order, missing or repeated"); + check(ids == std::set{std::this_thread::get_id()}, "an inline job ran on another thread"); + check(pool.stats().batches == 0 && pool.stats().started == 0, "an inline run was a batch or started a worker"); + check(pool.threads() == threads, "threads()"); + } + PipelineWorkers pool(0); + int ran = 0; + try { + pool.run(3, [&](std::size_t i) { + ++ran; + if (i == 1) throw std::runtime_error("inline"); + }); + check(false, "an inline exception was lost"); + } catch (const std::runtime_error&) { + check(ran == 2, "inline jobs went on after an exception"); + } +} + +// Each job once, all of them done when run() returns. Run often: a lost job or an early return shows up as a race. +void each_once() { + PipelineWorkers pool(4); + for (int round = 0; round < 500; ++round) { + const std::size_t count = 2 + std::size_t(round % 37); + std::vector> calls(count); + pool.run(count, [&](std::size_t i) { + if (round % 8 == 0) spend(50us); + calls[i].fetch_add(1); + }); + for (auto& c : calls) check(c == 1, "a job ran zero or several times, or after run() returned"); + } + const auto stats = pool.stats(); + check(stats.batches == 500 && stats.threads == 4 && stats.started == 4 && stats.running == 0, "stats after the runs"); + PipelineWorkers small(4); + small.run(3, [](std::size_t) {}); + check(small.stats().started == 2, "a batch of three starts two workers beside its caller"); +} + +// The last job is still running when all the others are done: run() has to wait for it. +void waits_for_the_last() { + PipelineWorkers pool(3); + for (int round = 0; round < 20; ++round) { + std::atomic finished = 0; + std::atomic worker_has_one = false; + const auto caller = std::this_thread::get_id(); + pool.run(8, [&](std::size_t) { + if (std::this_thread::get_id() != caller) { + worker_has_one = true; + std::this_thread::sleep_for(20ms); + } else { + wait_for([&] { return worker_has_one.load(); }); + } + ++finished; + }); + check(finished == 8, "run() returned while a worker was in a job"); + } +} + +// The jobs do run at the same time, on the workers and the caller together, and never on more threads than that. +void in_parallel() { + PipelineWorkers pool(3); + std::atomic inside = 0, most = 0; + std::mutex mutex; + std::set ids; + pool.run(4, [&](std::size_t) { + most = std::max(most.load(), ++inside); + check(wait_for([&] { return inside.load() == 4; }), "four jobs, three workers and the caller did not meet"); + most = std::max(most.load(), inside.load()); + std::lock_guard lock(mutex); + ids.insert(std::this_thread::get_id()); + }); + check(ids.size() == 4 && ids.count(std::this_thread::get_id()) == 1, "the caller and each worker took one job"); + ids.clear(); + inside = most = 0; + pool.run(64, [&](std::size_t) { + const int now = ++inside; + int seen = most; + while (now > seen && !most.compare_exchange_weak(seen, now)) {} + spend(1ms); + --inside; + }); + check(most >= 2 && most <= 4, "more jobs at once than workers and caller, or no two at once"); +} + +void exceptions() { + PipelineWorkers pool(4); + std::atomic ran = 0; + for (int round = 0; round < 50; ++round) { + ran = 0; + std::string what; + try { + pool.run(16, [&](std::size_t i) { + ++ran; + if (i == 3 || i == 11) { + // the later one first: the lowest is still the one rethrown + if (i == 3) spend(2ms); + throw std::runtime_error(std::to_string(i)); + } + }); + } catch (const std::runtime_error& error) { + what = error.what(); + } + check(what == "3", "run() rethrew no exception, or not the lowest job's"); + check(ran == 16, "an exception kept other jobs from running"); + } + int after = 0; + pool.run(1, [&](std::size_t) { ++after; }); + std::atomic more = 0; + pool.run(8, [&](std::size_t) { ++more; }); + check(after == 1 && more == 8, "the pool does not work after an exception"); +} + +// Several threads submit at once (several queues): each gets its own batch done, and no batch waits for another to end. +void several_callers() { + PipelineWorkers pool(2); + std::atomic wrong = 0; + std::vector callers; + for (int c = 0; c < 6; ++c) + callers.emplace_back([&] { + for (int round = 0; round < 100; ++round) { + std::vector> calls(5); + pool.run(calls.size(), [&](std::size_t i) { ++calls[i]; }); + for (auto& n : calls) wrong += n != 1; + } + }); + for (auto& c : callers) c.join(); + check(wrong == 0, "a concurrent run() lost or repeated a job"); + check(pool.stats().running == 0, "jobs still counted as running"); + + // One batch whose jobs hold every worker; another caller still gets its batch done. + std::atomic release = false; + std::atomic held = 0; + std::thread blocked([&] { + pool.run(3, [&](std::size_t) { + ++held; + wait_for([&] { return release.load(); }); + }); + }); + check(wait_for([&] { return held == 3; }), "the first batch did not take both workers and its caller"); + std::atomic done = 0; + pool.run(4, [&](std::size_t) { ++done; }); + check(done == 4, "a batch did not complete while the workers were busy"); + release = true; + blocked.join(); +} + +// A job that itself submits a batch (a pipeline that needs another): the caller's own work keeps it from waiting forever. +void nested() { + PipelineWorkers pool(2); + std::atomic inner = 0; + pool.run(6, [&](std::size_t) { pool.run(6, [&](std::size_t) { ++inner; }); }); + check(inner == 36, "nested runs"); +} + +// stop() during a run(): the jobs nobody took yet are the caller's, none is lost, and stop() waits for the workers. +void stopped_while_queued() { + for (int round = 0; round < 30; ++round) { + PipelineWorkers pool(3); + std::vector> calls(40); + std::atomic started = false, stopped = false; + std::atomic in_job = 0; + std::thread runner([&] { + const auto self = std::this_thread::get_id(); + pool.run(calls.size(), [&](std::size_t i) { + started = true; + if (std::this_thread::get_id() != self) ++in_job; + spend(500us); + ++calls[i]; + if (std::this_thread::get_id() != self) --in_job; + }); + }); + wait_for([&] { return started.load(); }); + pool.stop(); + stopped = true; + check(in_job == 0, "stop() returned while a worker was in a job"); + runner.join(); + for (auto& c : calls) check(c == 1, "a queued job was lost or repeated by stop()"); + // And later batches still complete, on this thread alone, with no worker started for them. + const std::size_t workers = pool.stats().started; + std::set ids; + int count = 0; + pool.run(5, [&](std::size_t) { + ++count; + ids.insert(std::this_thread::get_id()); + }); + check(count == 5 && ids == std::set{std::this_thread::get_id()} && pool.stats().started == workers, + "a run() after stop()"); + pool.stop(); // twice is fine + } +} + +// The destructor stops too, with the workers idle or never started. +void destroyed() { + for (int i = 0; i < 50; ++i) { + PipelineWorkers pool(4); + std::atomic n = 0; + if (i & 1) pool.run(6, [&](std::size_t) { ++n; }); + check(n == (i & 1 ? 6 : 0), "jobs before the destructor"); + } +} + +void setting() { + using leonida::pipeline_threads; + check(pipeline_threads(nullptr, 16).count == 8 && pipeline_threads(nullptr, 16).valid, "unset on 16 processors"); + check(pipeline_threads("", 32).count == 8, "empty on 32 processors"); + check(pipeline_threads(nullptr, 6).count == 3 && pipeline_threads(nullptr, 1).count == 0 && + pipeline_threads(nullptr, 0).count == 0, + "unset on few processors"); + check(pipeline_threads("0", 16).count == 0 && pipeline_threads("0", 16).valid, "0 turns it off"); + check(pipeline_threads("3", 16).count == 3, "a number"); + check(pipeline_threads("64", 16).count == 64 && pipeline_threads("65", 16).count == 64 && + pipeline_threads("99999999999999999999", 16).count == 64, + "at most kMaxThreads, without wrapping"); + for (const char* text : {"-1", "two", "4x", " 4", "0x4"}) + check(!pipeline_threads(text, 16).valid && pipeline_threads(text, 16).count == 8, "not a number counts as unset"); +} + +} // namespace + +int main() { + inline_runs(); + each_once(); + waits_for_the_last(); + in_parallel(); + exceptions(); + several_callers(); + nested(); + stopped_while_queued(); + destroyed(); + setting(); + if (failures) return 1; + std::printf("pipeline_workers_test: passed\n"); + return 0; +} diff --git a/runtime/test/replay_pipeline_compiles_test.cpp b/runtime/test/replay_pipeline_compiles_test.cpp new file mode 100644 index 000000000..35b6057ed --- /dev/null +++ b/runtime/test/replay_pipeline_compiles_test.cpp @@ -0,0 +1,564 @@ +// Pipelines that are not built when a submission is prepared (PipelineCompiles, build_pipelines): the same commands are +// prepared twice, once with every pipeline built where prepare() meets it and once with them left to PipelineCompiles +// and built on PipelineWorkers. Both have to give the same result, the same pipeline to every draw and dispatch, the same +// commands dropped, and the same pipelines built, each once. Fixed cases, then random ones. Run a second time with +// LEONIDA_STRICT_REPLAY=1, where a dispatch without a pipeline fails its list. No GPU: pipelines and resources are fakes. +#include "../src/pipeline_workers.h" +#include "../src/vulkan_replay.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace leonida; + +int failures = 0; +void check(bool ok, const std::string& what) { + if (ok) return; + std::fprintf(stderr, "FAIL: %s\n", what.c_str()); + ++failures; +} + +template +T handle(std::uintptr_t n) { + return reinterpret_cast(n); +} + +constexpr ResourceId color_id = 1, depth_id = 2, arguments_id = 3; +constexpr std::uint64_t bad_va = 0xbad0000; + +// The large pipelines being built now, and how often there were two. +std::atomic large_now = 0; +std::atomic large_together = 0; + +// What a pipeline state owns: its variants, built on demand under its own lock, and what was asked of it. +struct Owner { + std::uintptr_t id = 0; + bool fails = false; + bool large = false; + bool compute = false; + bool failed = false; + std::mutex mutex; + std::map variants; + std::vector attempts; // the flags of every build, also the failed ones + + VkPipeline build(std::uint32_t flags) { + std::lock_guard lock(mutex); + if (const auto it = variants.find(flags); it != variants.end()) return it->second; + if (failed && compute) return VK_NULL_HANDLE; // a refused compute pipeline is not tried again + attempts.push_back(flags); + if (large) { + if (++large_now > 1) ++large_together; + const auto end = std::chrono::steady_clock::now() + std::chrono::microseconds(20); + while (std::chrono::steady_clock::now() < end) std::this_thread::yield(); + --large_now; + } + if (fails) { + failed = true; + return VK_NULL_HANDLE; + } + return variants[flags] = handle(id * 0x1000 + flags + 1); + } + VkPipeline find(std::uint32_t flags) { + std::lock_guard lock(mutex); + const auto it = variants.find(flags); + return it == variants.end() ? VK_NULL_HANDLE : it->second; + } +}; + +struct PipelineSpec { + bool compute = false; + bool pending = true; // no pipeline yet: built on first use + bool fails = false; + bool with_built = true; + bool large = false; + bool skipped = false; // compute: never built, its dispatches are dropped + bool bindless = false; // compute: needs a set 0, which these functions cannot bind + bool async = false; // its null handle may be waiting for another worker: never left to PipelineCompiles + bool mesh = false; + bool rectangle = false; + bool vertices = false; + int colors = 1; + bool depth = false; + std::set ready; // built before +}; + +// One run's registered pipelines, made from the same specs for both runs. +struct Registry { + std::vector> owners; + std::map graphics; + std::map compute; + + explicit Registry(const std::vector& specs) { + for (std::size_t i = 0; i < specs.size(); ++i) { + const PipelineSpec& spec = specs[i]; + auto& owner = *owners.emplace_back(std::make_unique()); + owner.id = i + 1; + owner.fails = spec.fails; + owner.large = spec.large; + owner.compute = spec.compute; + for (const auto flags : spec.ready) owner.variants[flags] = handle(owner.id * 0x1000 + flags + 1); + if (spec.compute) { + ComputePipeline p{}; + p.layout = handle(7); + p.large = spec.large; + p.async_build = spec.async; + p.skipped = spec.skipped; + if (spec.bindless) p.bindless_set = handle(6); + if (spec.pending) { + p.build = [](void* context) { return static_cast(context)->build(0); }; + if (spec.with_built) p.built = [](void* context) { return static_cast(context)->find(0); }; + p.build_context = &owner; + } else { + p.pipeline = handle(owner.id * 0x1000); + } + compute[owner.id] = p; + continue; + } + GraphicsPipeline p{}; + p.layout = handle(7); + p.async_build = spec.async; + if (!spec.pending) p.pipeline = handle(owner.id * 0x1000); + p.color_formats.assign(std::size_t(spec.colors), VK_FORMAT_R8G8B8A8_UNORM); + if (spec.depth) { + p.depth_format = VK_FORMAT_D32_SFLOAT; + p.depth_aspects = VK_IMAGE_ASPECT_DEPTH_BIT; + } + p.mesh = spec.mesh; + p.large = spec.large; + p.vertex_slots = spec.vertices ? 1 : 0; + if (spec.rectangle) p.rectangle_variant_topology = 17; + p.variant = [&owner](std::uint32_t flags) { return owner.build(flags); }; + if (spec.with_built) p.built = [&owner](std::uint32_t flags) { return owner.find(flags); }; + graphics[owner.id] = p; + } + } + std::multiset> built() const { + std::multiset> out; + for (const auto& o : owners) + for (const auto flags : o->attempts) out.insert({o->id, flags}); + return out; + } +}; + +struct CommandSpec { + enum Kind { draw, dispatch, indirect_dispatch } kind = draw; + std::uintptr_t pipeline = 1; + int colors = 1; // how many render targets are bound + bool depth = false; + bool rectangle = false; // the topology of PipelineSpec::rectangle + bool bad_vertices = false; // a vertex buffer that resolves to nothing + bool mesh = false; +}; + +std::vector record(const std::vector>& specs) { + std::vector lists; + for (const auto& commands : specs) { + CommandList list; + for (const CommandSpec& c : commands) { + if (c.kind == CommandSpec::dispatch) { + list.dispatch({c.pipeline, {}, 1, 1, 1}); + } else if (c.kind == CommandSpec::indirect_dispatch) { + ExecuteIndirect e{}; + e.kind = IndirectKind::dispatch; + e.stride = 12; + e.max_count = 1; + e.argument_buffer = arguments_id; + e.pipeline = c.pipeline; + list.execute_indirect(e); + } else { + Draw d{}; + d.pipeline = c.pipeline; + d.topology = c.rectangle ? 17 : 4; + d.count = 3; + d.instances = 1; + d.first = 1; + d.mesh = c.mesh; + auto views = std::make_shared(); + for (int i = 0; i < c.colors; ++i) views->render_targets[std::size_t(i)] = {color_id, 0, 0, 1}; + views->vertex_buffers[0].va = c.bad_vertices ? bad_va : 0x1000; + views->vertex_buffers[0].size = 64; + d.views = views; + if (c.depth) d.depth = {depth_id, 0, 0, 1}; + list.draw(d); + } + } + list.close(); + lists.push_back(std::move(list)); + } + return lists; +} + +ReplayFunctions functions(const Registry& registry) { + ReplayFunctions vk{}; + vk.begin_rendering = +[](VkCommandBuffer, const VkRenderingInfo*) {}; + vk.end_rendering = +[](VkCommandBuffer) {}; + vk.bind_pipeline = +[](VkCommandBuffer, VkPipelineBindPoint, VkPipeline) {}; + vk.push_constants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, std::uint32_t, std::uint32_t, + const void*) {}; + vk.dispatch = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t) {}; + vk.dispatch_indirect = +[](VkCommandBuffer, VkBuffer, VkDeviceSize) {}; + vk.set_viewport = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkViewport*) {}; + vk.set_scissor = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkRect2D*) {}; + vk.set_primitive_topology = +[](VkCommandBuffer, VkPrimitiveTopology) {}; + vk.set_primitive_restart_enable = +[](VkCommandBuffer, VkBool32) {}; + vk.set_stencil_reference = +[](VkCommandBuffer, VkStencilFaceFlags, std::uint32_t) {}; + vk.set_blend_constants = +[](VkCommandBuffer, const float*) {}; + vk.bind_index_buffer = +[](VkCommandBuffer, VkBuffer, VkDeviceSize, VkIndexType) {}; + vk.bind_vertex_buffers2 = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkBuffer*, const VkDeviceSize*, + const VkDeviceSize*, const VkDeviceSize*) {}; + vk.draw = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t, std::uint32_t) {}; + vk.draw_indexed = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t, std::int32_t, std::uint32_t) {}; + vk.draw_mesh_tasks = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t) {}; + vk.image_view = [](const ResourceBinding&, const VkImageSubresourceRange&) { return handle(8); }; + vk.buffer_at = [](std::uint64_t va, std::uint64_t&, VkBuffer& buffer, VkDeviceSize& offset) { + if (va == bad_va) return false; + buffer = handle(9); + offset = 0; + return true; + }; + vk.graphics_pipeline = [®istry](std::uintptr_t id) -> const GraphicsPipeline* { + const auto it = registry.graphics.find(id); + return it == registry.graphics.end() ? nullptr : &it->second; + }; + vk.compute_pipeline = [®istry](std::uintptr_t id) -> const ComputePipeline* { + const auto it = registry.compute.find(id); + return it == registry.compute.end() ? nullptr : &it->second; + }; + return vk; +} + +const ResourceBinding* resolve(ResourceId id) { + static const auto binding = [](VkImageAspectFlags aspects, VkFormat format) { + ResourceBinding b{}; + b.aspects = aspects; + b.format = format; + b.width = b.height = 16; + return b; + }; + static const ResourceBinding color = [] { + auto b = binding(VK_IMAGE_ASPECT_COLOR_BIT, VK_FORMAT_R8G8B8A8_UNORM); + b.image = handle(10); + return b; + }(); + static const ResourceBinding depth = [] { + auto b = binding(VK_IMAGE_ASPECT_DEPTH_BIT, VK_FORMAT_D32_SFLOAT); + b.image = handle(11); + return b; + }(); + static const ResourceBinding arguments = [] { + auto b = binding(0, VK_FORMAT_UNDEFINED); + b.buffer = handle(12); + b.size = 4096; + return b; + }(); + return id == color_id ? &color : id == depth_id ? &depth : id == arguments_id ? &arguments : nullptr; +} + +struct Outcome { + ReplayResult result = ReplayResult::success; + std::vector pipelines; // of every draw and dispatch, when the lists were prepared; null: dropped + std::multiset> built; + std::size_t jobs = 0; + std::size_t runs = 0; + std::size_t units = 0; // what run() was given: the large pipelines together are one +}; + +// `workers` null: prepare() builds each pipeline itself, as without workers. +Outcome prepare_all(const std::vector& lists, const std::vector& specs, + PipelineWorkers* workers) { + Registry registry(specs); + ReplayFunctions vk = functions(registry); + PipelineCompiles compiles; + if (workers) vk.compiles = &compiles; + Outcome out; + std::vector prepared(lists.size()); + for (std::size_t i = 0; i < lists.size() && out.result == ReplayResult::success; ++i) + out.result = prepare(lists[i], resolve, vk, prepared[i]); + out.jobs = compiles.size(); + if (workers) + out.result = build_pipelines(compiles, std::span(prepared), out.result, + [&](std::size_t count, const std::function& job) { + ++out.runs; + out.units = count; + workers->run(count, job); + }); + if (out.result == ReplayResult::success) + for (std::size_t i = 0; i < lists.size(); ++i) { + for (std::size_t c = 0; c < prepared[i].commands.size(); ++c) { + const auto& command = lists[i].commands()[c]; + if (std::holds_alternative(command)) { + const auto& draw = prepared[i].draws[prepared[i].commands[c].draw]; + out.pipelines.push_back(draw.skipped ? VkPipeline(VK_NULL_HANDLE) : draw.pipeline); + check(draw.skipped || draw.pipeline, "a draw neither dropped nor with a pipeline"); + } else + out.pipelines.push_back(prepared[i].commands[c].pipeline.pipeline); + } + } + out.built = registry.built(); + return out; +} + +Outcome compare(const std::string& name, const std::vector& specs, + const std::vector>& commands, PipelineWorkers& workers) { + const auto lists = record(commands); + const Outcome serial = prepare_all(lists, specs, nullptr); + const Outcome together = prepare_all(lists, specs, &workers); + check(serial.result == together.result, name + ": another result"); + check(serial.pipelines == together.pipelines, name + ": another pipeline for a draw or dispatch"); + if (serial.result == ReplayResult::success) + check(serial.built == together.built, name + ": other pipelines built"); + else // serial stops at the first pipeline that fails; the others were already wanted by commands before + check(std::includes(together.built.begin(), together.built.end(), serial.built.begin(), serial.built.end()), + name + ": a pipeline built serially was not built"); + for (const auto& one : together.built) // one another worker builds is asked for again while it is refused + check(together.built.count(one) == 1 || (specs[one.first - 1].async && specs[one.first - 1].fails), + name + ": a pipeline built twice"); + return together; +} + +using Commands = std::vector>; + +void cases(PipelineWorkers& workers) { + const bool strict = strict_replay(); + const PipelineSpec pending{}, eager{.pending = false}; + const CommandSpec draw{}; + const auto use = [](std::uintptr_t id) { CommandSpec c{}; c.pipeline = id; return c; }; + + auto out = compare("one pending pipeline in many draws", {pending}, {{draw, draw, draw}, {draw}}, workers); + check(out.jobs == 1 && out.built.size() == 1, "one pipeline is one job"); + out = compare("several pending pipelines", {pending, pending, pending}, + {{use(1), use(2), use(1)}, {use(3), use(2)}}, workers); + check(out.jobs == 3 && out.pipelines.size() == 5 && out.runs == 1, "three pipelines, all in one batch"); + out = compare("an eager pipeline", {eager}, {{draw, draw}}, workers); + check(out.jobs == 0 && out.runs == 0, "an eager pipeline with everything bound needs no job"); + out = compare("a built variant", {{.ready = {0}}}, {{draw, draw}}, workers); + check(out.jobs == 0 && out.runs == 0 && out.built.empty(), "a built pipeline is found, not built again"); + + // The variant flags: colour slots left unbound, depth left unbound, the rectangle topology. + PipelineSpec targets{.pending = false, .rectangle = true, .colors = 3, .depth = true}; + CommandSpec full{.colors = 3, .depth = true}, two = full, no_depth = full, rectangle = full, all = full; + two.colors = 1; + no_depth.depth = false; + rectangle.rectangle = true; + all.colors = 0; + all.depth = false; + all.rectangle = true; + out = compare("variants", {targets}, {{full, two, no_depth, rectangle, all, two, all}}, workers); + const std::multiset> flags{ + {1, 0b110}, {1, GraphicsPipeline::unbound_depth}, {1, GraphicsPipeline::rectangle_stage}, + {1, 0b111 | GraphicsPipeline::unbound_depth | GraphicsPipeline::rectangle_stage}}; + check(out.built == flags && out.jobs == 4, "the variants a draw needs, each once"); + targets.pending = true; + out = compare("base and variants pending", {targets}, {{full, two, full}}, workers); + check(out.jobs == 2, "the base pipeline and one variant"); + + // Pipelines that cannot say whether they are built are built on the spot, as before. + out = compare("without built", {{.with_built = false}, pending}, {{use(1), use(2)}}, workers); + check(out.jobs == 1, "only the pipeline with `built` is left to PipelineCompiles"); + + // Compute, directly and through ExecuteIndirect. + const PipelineSpec compute{.compute = true}, ready_compute{.compute = true, .ready = {0}}, + eager_compute{.compute = true, .pending = false}; + CommandSpec dispatch{.kind = CommandSpec::dispatch}, indirect{.kind = CommandSpec::indirect_dispatch}; + const auto with = [](CommandSpec c, std::uintptr_t id) { c.pipeline = id; return c; }; + out = compare("first-use dispatches", {compute, compute, eager_compute, ready_compute}, + {{with(dispatch, 1), with(indirect, 2), with(dispatch, 1), with(dispatch, 3), with(dispatch, 4), + with(indirect, 1)}}, + workers); + check(out.jobs == 2 && out.pipelines.size() == 6, "a compute pipeline is compiled once for both kinds of dispatch"); + out = compare("draws and dispatches", {pending, compute}, {{use(1), with(dispatch, 2)}, {with(indirect, 2), use(1)}}, + workers); + check(out.jobs == 2 && out.runs == 1, "graphics and compute share one batch"); + + // Failures: the one a list would have stopped at. + const PipelineSpec failing{.fails = true}, failing_compute{.compute = true, .fails = true}; + out = compare("a pipeline that cannot be built", {failing}, {{draw}}, workers); + check(out.result == ReplayResult::unsupported, "it is unsupported"); + out = compare("a compute pipeline that cannot be built", {failing_compute, compute}, + {{with(dispatch, 1), with(dispatch, 2)}}, workers); + check(out.result == (strict ? ReplayResult::unresolved_resource : ReplayResult::success), "its dispatch is dropped"); + check(strict || (!out.pipelines[0] && out.pipelines[1]), "and no other"); + out = compare("an indirect dispatch of one", {failing_compute}, {{with(indirect, 1)}}, workers); + check(out.result == ReplayResult::unresolved_resource, "it fails its list"); + out = compare("a refused draw after a refused dispatch", {failing_compute, failing}, + {{with(dispatch, 1), use(2)}}, workers); + check(out.result == (strict ? ReplayResult::unresolved_resource : ReplayResult::unsupported), "the first that fails"); + out = compare("a refused indirect dispatch after a refused draw", {failing_compute, failing}, + {{use(2), with(indirect, 1)}}, workers); + check(out.result == ReplayResult::unsupported, "the draw comes first"); + out = compare("a refused draw after a refused indirect dispatch", {failing_compute, failing}, + {{with(indirect, 1), use(2)}}, workers); + check(out.result == ReplayResult::unresolved_resource, "the indirect dispatch comes first"); + const PipelineSpec skipped{.compute = true, .fails = true, .skipped = true}; + out = compare("a skipped program", {skipped, compute}, {{with(dispatch, 1), with(indirect, 1), with(dispatch, 2)}}, + workers); + check(out.result == ReplayResult::success && out.jobs == 1, "a skipped program is dropped, strictly too"); + out = compare("a set 0 that cannot be bound", {{.compute = true, .bindless = true}}, {{with(dispatch, 1)}}, workers); + check(out.result == ReplayResult::unsupported, "it is unsupported once the pipeline is there"); + out = compare("and a pipeline that cannot be built", {{.compute = true, .fails = true, .bindless = true}}, + {{with(dispatch, 1)}}, workers); + check(out.result == (strict ? ReplayResult::unresolved_resource : ReplayResult::success), "it is dropped first"); + const PipelineSpec async{.async = true}, async_compute{.compute = true, .async = true}; + out = compare("pipelines that another worker builds", {async, async_compute}, {{use(1), with(dispatch, 2)}}, workers); + check(out.jobs == 0, "async_build is never left to PipelineCompiles"); + compare("and cannot", {{.fails = true, .async = true}, {.compute = true, .fails = true, .async = true}}, + {{use(1), with(dispatch, 2)}, {with(indirect, 2)}}, workers); + out = compare("a failure among others", {pending, failing, pending}, {{use(1), use(2)}, {use(3)}}, workers); + check(out.result == ReplayResult::unsupported, "one failure fails the submission"); + out = compare("a failure before a missing pipeline", {failing}, {{use(1), use(9)}}, workers); + check(out.result == ReplayResult::unsupported, "the failed build comes first"); + out = compare("a missing pipeline before a failure", {failing}, {{use(9), use(1)}}, workers); + check(out.result == (strict ? ReplayResult::unresolved_resource : ReplayResult::unsupported) && + out.built.empty() == strict, + "a missing pipeline drops its draw; strictly it comes first"); + out = compare("a missing pipeline after one that builds", {pending}, {{use(1), use(9)}}, workers); + check(out.result == (strict ? ReplayResult::unresolved_resource : ReplayResult::success) && out.built.size() == 1, + "the pipeline is built, as before"); + out = compare("a missing pipeline in a later list", {pending, pending}, {{use(1)}, {use(2), use(9)}, {use(1)}}, workers); + check(out.result == (strict ? ReplayResult::unresolved_resource : ReplayResult::success) && out.built.size() == 2, + "lists before the failure"); + PipelineSpec vertices{.fails = true, .vertices = true}; + CommandSpec bad = draw; + bad.bad_vertices = true; + out = compare("a failure in a draw whose vertex buffer is missing too", {vertices}, {{bad}}, workers); + check(out.result == ReplayResult::unsupported, "the pipeline is looked at before the vertex buffers"); + vertices.fails = false; + out = compare("a missing vertex buffer", {vertices}, {{bad}}, workers); + check(out.result == (strict ? ReplayResult::unresolved_resource : ReplayResult::success), "the vertex buffer"); + CommandSpec mesh = draw; + mesh.mesh = true; + out = compare("a mesh draw with a vertex pipeline", {pending}, {{mesh}}, workers); + check(out.result == ReplayResult::invalid_draw && out.built.empty(), "refused before its pipeline is built"); +} + +// More than one worker's worth of pipelines, so that the batch really runs on several threads. +void many(PipelineWorkers& workers) { + std::vector specs; + Commands commands(3); + for (std::uintptr_t i = 0; i < 300; ++i) { + PipelineSpec spec{}; + spec.compute = i % 3 == 2; + spec.large = i % 7 == 0; // 43 of them, graphics and compute + specs.push_back(spec); + for (std::size_t repeat = 0; repeat < 2; ++repeat) { + CommandSpec c{}; + c.pipeline = i + 1; + if (spec.compute) c.kind = repeat ? CommandSpec::indirect_dispatch : CommandSpec::dispatch; + commands[(i + repeat) % 3].push_back(c); + } + } + const auto out = compare("300 pipelines", specs, commands, workers); + check(out.jobs == 300 && out.pipelines.size() == 600, "300 pipelines: every command has its own"); + check(out.units == 300 - 43 + 1, "the large pipelines are one unit, the others one each"); + const auto stats = workers.stats(); + check(stats.batches > 0 && stats.jobs >= out.units, "the batch went through the workers"); +} + +// A queue prepares every submission into the same PreparedLists: what one left in them is not used by the next. +void reused_lists(PipelineWorkers& workers) { + Registry registry({{}, {}, {}, {.compute = true}, {}, {.compute = true}}); + ReplayFunctions vk = functions(registry); + std::vector prepared(2); + const auto submit = [&](const Commands& commands, std::size_t jobs) { + const auto lists = record(commands); + PipelineCompiles compiles; + vk.compiles = &compiles; + ReplayResult result = ReplayResult::success; + for (std::size_t i = 0; i < lists.size(); ++i) + check(prepare(lists[i], resolve, vk, prepared[i]) == ReplayResult::success, "reused lists: prepare"); + check(compiles.size() == jobs, "reused lists: " + std::to_string(compiles.size()) + " jobs"); + result = build_pipelines(compiles, std::span(prepared).first(lists.size()), result, + [&](std::size_t count, const std::function& job) { + workers.run(count, job); + }); + check(result == ReplayResult::success, "reused lists: result"); + for (std::size_t i = 0; i < lists.size(); ++i) + for (std::size_t c = 0; c < commands[i].size(); ++c) { + const VkPipeline want = handle(commands[i][c].pipeline * 0x1000 + 1); + const auto& command = prepared[i].commands[c]; + check((commands[i][c].kind == CommandSpec::draw ? prepared[i].draws[command.draw].pipeline + : command.pipeline.pipeline) == want, + "reused lists: another pipeline"); + } + }; + const auto draw = [](std::uintptr_t id) { CommandSpec c{}; c.pipeline = id; return c; }; + const auto dispatch = [](std::uintptr_t id) { CommandSpec c{.kind = CommandSpec::dispatch}; c.pipeline = id; return c; }; + submit({{draw(1), draw(2), dispatch(4), draw(3)}, {draw(2), draw(1)}}, 4); + submit({{draw(3), draw(5), dispatch(4), draw(1), dispatch(6)}, {draw(1), draw(5), draw(2)}}, 2); + submit({{draw(5)}, {draw(1)}}, 0); + // Lists a shorter submission leaves over keep the tickets of an older one; nothing looks at them. + submit({{draw(2)}}, 0); +} + +void random_submissions(PipelineWorkers& workers) { + std::mt19937 rng(20251125); + const auto chance = [&](unsigned percent) { return rng() % 100 < percent; }; + unsigned succeeded = 0; + for (int round = 0; round < 3000; ++round) { + std::vector specs(1 + rng() % 8); + for (auto& s : specs) { + s.compute = chance(30); + s.pending = chance(75); + s.fails = chance(4); + s.with_built = chance(90); + s.async = chance(8); + s.large = chance(15); + s.bindless = chance(2); + s.skipped = s.compute && chance(4); + if (s.skipped) s.fails = s.pending = true; + s.mesh = chance(3); + s.rectangle = chance(20); + s.vertices = chance(30); + s.colors = int(rng() % 4); + s.depth = chance(40); + if (chance(30)) s.ready.insert(rng() % 4); + } + Commands commands(1 + rng() % 4); + for (auto& list : commands) + for (unsigned i = rng() % 8; i; --i) { + CommandSpec c{}; + c.pipeline = 1 + (chance(3) ? specs.size() : rng() % specs.size()); + const bool compute = c.pipeline <= specs.size() && specs[c.pipeline - 1].compute; + if (compute) c.kind = chance(50) ? CommandSpec::dispatch : CommandSpec::indirect_dispatch; + c.colors = int(rng() % 4); + c.depth = chance(50); + c.rectangle = chance(25); + c.bad_vertices = chance(2); + c.mesh = c.pipeline <= specs.size() && specs[c.pipeline - 1].mesh; + list.push_back(c); + } + succeeded += compare("random submission " + std::to_string(round), specs, commands, workers).result == + ReplayResult::success; + } + check(succeeded > 1000 && succeeded < 2900, "the random submissions both succeed and fail: " + + std::to_string(succeeded)); +} + +} // namespace + +int main() { + for (const unsigned threads : {0u, 1u, 4u}) { + PipelineWorkers workers(threads); + cases(workers); + if (threads) many(workers); + reused_lists(workers); + random_submissions(workers); + } + check(large_together == 0, "two large pipelines were built at once"); + if (failures) return 1; + std::printf("replay_pipeline_compiles_test: passed\n"); + return 0; +}