From a83f38508f535a2de95a15f91071139de2c26fee Mon Sep 17 00:00:00 2001 From: Tyrannys <80750971+Tyrannys@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:10:28 -0600 Subject: [PATCH 1/5] d3d12: a pool of compile workers for the pipeline compiler (RT-ASYNC-COMPILE-POOL) With LEONIDA_ASYNC_PIPELINES=1 every demanded build, the compute warm-up and the cache checkpoint ran on one general worker (plus a graphics-only one), so one long driver compile held every pipeline a submission asked for behind it, and their draws and dispatches were skipped meanwhile. PipelineCompiler now runs LEONIDA_COMPILE_THREADS workers (half the logical processors, 2 to 8). A worker takes the most urgent job it may: - demanded builds first, in the order they came, then warm-ups by size, then the checkpoint, which waits until no worker compiles; - large builds (compute over 128 KiB, graphics of 1 MiB or more) and warm-ups together take at most threads-1 workers, so one stays free for a small demanded build; at most LEONIDA_COMPILE_HEAVY_MAX large builds at once (default threads-1, 1 with LEONIDA_SERIAL_BIG_COMPILES=1), compute and graphics alike, each still within the memory gate; - warm-ups run one at a time, and none starts while a demanded build runs: each holds the compile gate for its whole create, and a submission waits for every create in flight; - one build of a PSO at a time, so after_running and the teardown rules hold. LEONIDA_COMPILE_THREADS=1 keeps the layout before the pool. The design is MoonEyes' (#2077), ported onto #2098's scheduler. Tests: d3d12_compile_pool (CPU, jobs held at gates: settings, a long build does not hold up a small demanded one, heavy count, free worker, warm-ups one at a time and after demanded builds, order, one job per PSO, release/cancel/ stop_for_exit with jobs in flight), and d3d12_compile_teardown also with one worker. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 15 + runtime/CMakeLists.txt | 12 + runtime/README.md | 4 +- runtime/shims/d3d12_pipeline_compile.h | 207 ++++++++-- runtime/shims/d3d12_vulkan_device.cpp | 10 +- runtime/test/d3d12_compile_pool_test.cpp | 468 +++++++++++++++++++++++ 6 files changed, 673 insertions(+), 43 deletions(-) create mode 100644 runtime/test/d3d12_compile_pool_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 43886af30f..a14e10f36f 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2606,6 +2606,21 @@ submitting thread; at the maintainers' decision it was replaced by this one when at record time already: at `SetPipelineState` for compute and at each draw for graphics, with the variant its bound targets give (`request_pipeline_build`). A compute build the compile helper is still making (`LEONIDA_COMPILE_HELPER`) publishes nothing, so its next use asks again. +- **Compile workers** (RT-ASYNC-COMPILE-POOL, after MoonEyes' design in #2077). The jobs above, the compute warm-up + and the cache checkpoint run on `LEONIDA_COMPILE_THREADS` workers (half the logical processors, 2 to 8). With one + worker a driver compile of minutes held every pipeline a submission asked for behind it, and their draws and + dispatches were skipped meanwhile. A worker now takes the most urgent job it may: demanded builds first, in the + order they came, then warm-ups by module size, then the checkpoint, which waits until no worker compiles. Large + builds (compute over 128 KiB, graphics of 1 MiB or more) and warm-ups together take at most threads-1 workers, so + one is always free for a small demanded build; at most `LEONIDA_COMPILE_HEAVY_MAX` large builds run at once (default + threads-1, 1 with `LEONIDA_SERIAL_BIG_COMPILES=1`), each still within the memory gate; warm-ups run one at a time, + as before, and none starts while a demanded build is queued or running, since each holds the compile gate for its + whole create (MoonEyes measured in #1608 that with the gate on, submissions waited 142 s in all behind warm-ups of + about 800 KB, and that with `LEONIDA_COMPILE_GATE=0` the same boot reached game state 3); and a PSO has one build + running at a time, so + `after_running` and the teardown rules hold as they were. `LEONIDA_COMPILE_THREADS=1` is the layout before the pool: + one general worker and the graphics-only one. A submission still waits at the compile gate for every create in + flight, so more workers do not shorten that wait (`SubmitMutex::CompileTurn`; `LEONIDA_COMPILE_GATE=0` turns it off). - **Warm-ups while the title submits.** A compute warm-up holds the compile gate for its whole create, and every submission waits behind it: a native boot's submissions waited 140 s in all at the gate behind compute warm-ups, and past the story load the worker went through 694 warm-ups of modules over 128 KiB (those over 640 KiB take 4-25 s diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 10ee582b12..36a84df7ea 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2477,6 +2477,14 @@ if(TARGET Vulkan::Headers) 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. + # The compile workers of PipelineCompiler (LEONIDA_COMPILE_THREADS, LEONIDA_COMPILE_HEAVY_MAX): their rules with jobs + # that wait at gates, no device. + add_executable(d3d12_compile_pool_test test/d3d12_compile_pool_test.cpp) + target_link_libraries(d3d12_compile_pool_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_compile_pool_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_compile_pool_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_compile_pool COMMAND d3d12_compile_pool_test) + set_tests_properties(d3d12_compile_pool PROPERTIES TIMEOUT 120) 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) @@ -3807,6 +3815,10 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_compile_teardown_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_compile_teardown COMMAND d3d12_compile_teardown_test) set_tests_properties(d3d12_compile_teardown PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) + # The same with one compile worker, the layout before the pool (LEONIDA_COMPILE_THREADS=1). + add_test(NAME d3d12_compile_teardown_one_worker COMMAND d3d12_compile_teardown_test) + set_tests_properties(d3d12_compile_teardown_one_worker PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300 + ENVIRONMENT "LEONIDA_COMPILE_THREADS=1") # A buffer at the title's own VA (device slot 133) read by the same shader through a root view and a V#. add_executable(d3d12_title_va_test test/d3d12_title_va_test.cpp shims/d3d12_xs_device.cpp test/xmem_geometry_aliases_stub.cpp ${LEONIDA_TEST_CS}) diff --git a/runtime/README.md b/runtime/README.md index 23a7811abe..ffd166f7d4 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -417,7 +417,9 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES` | unset | ``: a compute warm-up of a module over n bytes of SPIR-V is not started while the title submits (a submission in the last second); the pipeline is built at its first use instead (docs/d3d12_vulkan.md, "Pipelines still being built"). Unset or `0`: every warm-up runs, ordered behind a submission's compiles by the large-compile gate. | | `LEONIDA_COMPILE_GATE` | unset | `1`: a compute pipeline build holds the device's submit lock for its driver calls, so no compute compile runs while a queue submits. Unset: the asynchronous workers compile while other queues submit. | | `LEONIDA_FAST_PIPELINES` | unset | `graphics`, `compute` or `all` (`1` = all) creates those pipelines with `VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT` (`shims/d3d12_pipeline_compile.h`): slower shaders, much shorter builds. Part of the compute journal key, so optimized and fast builds keep separate files. | -| `LEONIDA_GRAPHICS_COMPILE_WORKER` | on | A second compile worker that takes graphics pipeline builds only, so a long compute build does not hold them up (`shims/d3d12_pipeline_compile.h`). `0`: the one general worker builds everything. | +| `LEONIDA_COMPILE_THREADS` | half the logical processors, 2-8 | ``: the compile workers of the asynchronous builds (`LEONIDA_ASYNC_PIPELINES=1`), the compute warm-up and the cache checkpoint (`shims/d3d12_pipeline_compile.h`, `CompilePool`). A demanded build goes before warm-ups; large and speculative builds take at most n-1 workers, so one stays free for a small build a submission waits for; one build of a PSO at a time; warm-ups one at a time, and none while a demanded build is queued or running. `1`: one general worker plus the graphics-only one (`LEONIDA_GRAPHICS_COMPILE_WORKER`), the layout before the pool. | +| `LEONIDA_COMPILE_HEAVY_MAX` | threads-1 (`1` with `LEONIDA_SERIAL_BIG_COMPILES=1`) | ``: at most n builds of large modules (compute over 128 KiB, graphics of 1 MiB of SPIR-V or more) on the compile workers at once, 1 to threads-1. They also keep within the memory budget of `LEONIDA_BIG_COMPILE_BUDGET_MB`. | +| `LEONIDA_GRAPHICS_COMPILE_WORKER` | on | With `LEONIDA_COMPILE_THREADS=1`: a second compile worker that takes graphics pipeline builds only, so a long compute build does not hold them up (`shims/d3d12_pipeline_compile.h`). `0`: the one general worker builds everything. With more workers it is not used. | | `LEONIDA_CONSOLE_HEAP_GPU` | unset | `1`: the V#s of the console descriptor heaps are rebased by a compute pass at the start of each submission (`src/console_heap_gpu.h`) instead of on the CPU. The CPU still finds the changed slots and registers the T#s; a V# the pass cannot answer is resolved after its submission and its slot queued again. | | `LEONIDA_CONSOLE_HEAP_ARENA` | unset | With `LEONIDA_CONSOLE_HEAP_GPU=1`, `1` puts a console heap's GPU copy and its guard in the arena (device-local where the device has ReBAR) instead of an import of host memory. No room in the arena: the import. | | `LEONIDA_CONSOLE_GPU_TSHARPS` | on | With `LEONIDA_CONSOLE_HEAP_GPU=1`, the T#s of changed slots are registered by the resolver thread and the refresh only decodes them. `0` registers them on the submitting thread, under the fix budget. | diff --git a/runtime/shims/d3d12_pipeline_compile.h b/runtime/shims/d3d12_pipeline_compile.h index 2889d7fd36..05be862604 100644 --- a/runtime/shims/d3d12_pipeline_compile.h +++ b/runtime/shims/d3d12_pipeline_compile.h @@ -190,8 +190,80 @@ class DriverTurn { }; -// Demanded work has priority zero, speculative work is ordered by module size, and -// an idle checkpoint runs last. No Vulkan call runs with the queue lock held. +// How many compile workers PipelineCompiler runs, and how many of them may build a large module at once. +// LEONIDA_COMPILE_THREADS=: n workers (1..64). Unset: half the logical processors, 2 at least and 8 at most. 1: one +// worker for every job plus the graphics-only one (LEONIDA_GRAPHICS_COMPILE_WORKER), the layout before the pool. +// LEONIDA_COMPILE_HEAVY_MAX=: at most n large builds (compute modules over 128 KiB, graphics pipelines of +// PipelineCompiles::large_spirv_bytes or more) at once, 1..threads-1. Unset: threads-1, or 1 with +// LEONIDA_SERIAL_BIG_COMPILES=1. Large builds still take their place at the memory gate (big_compile_gate) too. +// With two workers or more, large and speculative builds (warm-ups) together take at most threads-1 of them, so one +// worker is always free for a small build a submission waits for. Warm-ups run one at a time, as on the single worker, +// and none starts while a demanded build is queued or running: each holds the compile gate for its whole create, and a +// submission waits there for every create in flight (MoonEyes, #1608: with the gate on, submissions waited 142 s in all +// behind warm-ups of about 800 KB, 5-13.5 s each). +struct CompilePool { + unsigned threads = 1; + unsigned heavy = 1; // large builds at once + bool threads_valid = true; // false: LEONIDA_COMPILE_THREADS was not a number (the default is used) + bool heavy_valid = true; +}; + +inline bool parse_compile_count(const wchar_t* text, unsigned& out) { + if (!text || !*text) return false; + unsigned value = 0; + for (const wchar_t* c = text; *c; ++c) { + if (*c < L'0' || *c > L'9') return false; + value = (std::min)(1000u, value * 10 + unsigned(*c - L'0')); + } + out = value; + return true; +} + +// Null or empty text: the setting is unset. +inline CompilePool compile_pool(const wchar_t* threads_text, const wchar_t* heavy_text, unsigned logical_processors, + bool serial_big) { + CompilePool pool; + pool.threads = std::clamp(logical_processors / 2, 2u, 8u); + unsigned value = 0; + if (threads_text && *threads_text) { + if (parse_compile_count(threads_text, value)) pool.threads = std::clamp(value, 1u, 64u); + else pool.threads_valid = false; + } + const unsigned most = pool.threads > 1 ? pool.threads - 1 : 1; + pool.heavy = serial_big ? 1 : most; + if (heavy_text && *heavy_text) { + if (parse_compile_count(heavy_text, value)) pool.heavy = std::clamp(value, 1u, most); + else pool.heavy_valid = false; + } + return pool; +} + +inline CompilePool compile_pool_from_environment() { + wchar_t threads[16]{}, heavy[16]{}, serial[2]{}; + const DWORD t = GetEnvironmentVariableW(L"LEONIDA_COMPILE_THREADS", threads, 16); + const DWORD h = GetEnvironmentVariableW(L"LEONIDA_COMPILE_HEAVY_MAX", heavy, 16); + const DWORD s = GetEnvironmentVariableW(L"LEONIDA_SERIAL_BIG_COMPILES", serial, 2); + if (t >= 16) threads[0] = L'x'; // too long to be a count + if (h >= 16) heavy[0] = L'x'; + const bool serial_big = s == 1 && serial[0] != L'0'; + const CompilePool pool = compile_pool(t ? threads : nullptr, h ? heavy : nullptr, + std::thread::hardware_concurrency(), serial_big); + if (!pool.threads_valid) std::fprintf(stderr, "[rt] d3d12: LEONIDA_COMPILE_THREADS is not a number; not used\n"); + if (!pool.heavy_valid) std::fprintf(stderr, "[rt] d3d12: LEONIDA_COMPILE_HEAVY_MAX is not a number; not used\n"); + return pool; +} + +// The compile workers: replay's asynchronous builds (LEONIDA_ASYNC_PIPELINES=1), the compute warm-up and the startup +// cache checkpoint. Jobs are taken most urgent first: demanded work has priority zero (in the order it came), speculative +// work is ordered by module size, and a checkpoint (SIZE_MAX) runs last. No Vulkan call runs with the queue lock held. +// With two workers or more (CompilePool), a worker takes the most urgent job that +// - is not a checkpoint while any worker is busy (it saves the cache only when nothing compiles); +// - has no other job of its owner running (one build of a PSO at a time); +// - when it is large or speculative, leaves one worker for the others (threads-1 of these at once); when it is +// large, keeps within the heavy count; when it is speculative, runs alone among speculative ones and only while +// no demanded build is queued or running. +// So a long driver compile holds up only the jobs of its own PSO, and a small build a submission asked for gets a free +// worker while large ones run. With one worker the order is the old one: the next job, whatever it is. // // Lifetime. A job names its owner (the PSO it builds, or the device for a cache checkpoint) and the device whose // Vulkan objects it uses, and holds no reference to either: a reference kept the device alive past the title's last @@ -200,46 +272,68 @@ class DriverTurn { // - A PSO's last Release does not wait for its running build, which can be a dispatch-worker build of a module the // driver takes minutes over: after_running() drops its queued jobs and hands the PSO's deletion to the worker, // to run when that build returns (PipelineState::last_release). The PSO lets its device reference go at once. -// - A device's teardown waits: cancel() drops its queued jobs (by owner or device) and waits for its running one -// and what runs after it, so an in-flight vkCreate*Pipelines finishes before the device's objects go. -// - The worker thread runs while a device is alive (retain/release): the last device's release stops and joins it. +// - A device's teardown waits: cancel() drops its queued jobs (by owner or device) and waits for its running ones +// and what runs after them, so an in-flight vkCreate*Pipelines finishes before the device's objects go. +// - The workers run while a device is alive (retain/release): the last device's release stops and joins them. // - stop_for_exit() is for a process that ends with its device alive (main.cpp: the title's exit, a console Ctrl+C // or close). After it nothing more is queued: submit() refuses, and the callers build in place or not at all. class PipelineCompiler { public: static PipelineCompiler& instance() { - static auto* pool = new PipelineCompiler; // never destroyed: static destruction must not race the worker + static auto* pool = new PipelineCompiler; // never destroyed: static destruction must not race the workers return *pool; } struct Stats { std::uint64_t submitted = 0; - std::uint64_t completed = 0; // jobs the worker ran + std::uint64_t completed = 0; // jobs the workers ran std::uint64_t dropped = 0; // queued jobs thrown away by cancel, after_running, release or stop_for_exit std::uint64_t refused = 0; // submissions after stop_for_exit std::uint64_t waited = 0; // cancel calls that waited for a running job std::uint64_t deferred = 0; // after_running calls that left something to run after a running job + unsigned threads = 0; // the pool's workers (CompilePool), 0 before the first job + unsigned heavy = 0; // its large builds at once + std::size_t most_running = 0; // the most jobs that ran at once }; - // False, with nothing queued, after stop_for_exit. A `graphics` job (a graphics pipeline build) may also run on a - // second worker that takes only graphics jobs, so a compute build the driver takes minutes over does not hold - // up later graphics pipelines. LEONIDA_GRAPHICS_COMPILE_WORKER=0 uses one shared worker. + // Sets the pool size before the first job (tests); otherwise it is read from the environment at the first submit. + // False when it was set already. + bool configure(CompilePool pool) { + std::lock_guard lock(mutex_); + if (pool_) return false; + pool_ = pool; + return true; + } + + // False, with nothing queued, after stop_for_exit. `graphics`: a graphics pipeline build; with one worker it may also + // run on a second worker that takes only graphics jobs, so a compute build the driver takes minutes over does not + // hold up later graphics pipelines (LEONIDA_GRAPHICS_COMPILE_WORKER=0: no second worker). `large`: a build of a + // large module (CompilePool's heavy count). bool submit(const void* owner, const void* device, std::size_t priority, std::function work, - bool graphics = false) { + bool graphics = false, bool large = false) { std::lock_guard lock(mutex_); if (closed_) { ++stats_.refused; return false; } - if (!worker_.joinable()) { + if (!pool_) { + pool_ = compile_pool_from_environment(); + if (pool_->threads > 1) + std::fprintf(stderr, "[rt] d3d12: %u pipeline compile workers, at most %u large builds at once " + "(LEONIDA_COMPILE_THREADS, LEONIDA_COMPILE_HEAVY_MAX)\n", + pool_->threads, pool_->heavy); + } + stats_.threads = pool_->threads; + stats_.heavy = pool_->heavy; + while (workers_.size() < pool_->threads) { const std::uint64_t generation = generation_; - worker_ = std::thread([this, generation] { run(generation, false); }); + workers_.emplace_back([this, generation] { run(generation, false); }); } - if (graphics && graphics_worker_enabled() && !graphics_worker_.joinable()) { + if (graphics && pool_->threads == 1 && graphics_worker_enabled() && !graphics_worker_.joinable()) { const std::uint64_t generation = generation_; graphics_worker_ = std::thread([this, generation] { run(generation, true); }); } - jobs_.emplace(priority, Job{owner, device, std::move(work), graphics}); + jobs_.emplace(priority, Job{owner, device, std::move(work), graphics, large}); ++stats_.submitted; wake_.notify_all(); return true; @@ -299,7 +393,7 @@ class PipelineCompiler { return false; } - // True on the worker while it runs a job whose owner or device is `key` (not what runs after it). + // True on a worker while it runs a job whose owner or device is `key` (not what runs after it). bool running_here(const void* key) { std::lock_guard lock(mutex_); const auto me = std::this_thread::get_id(); @@ -308,40 +402,40 @@ class PipelineCompiler { }); } - // A device holds the worker while it lives. The last release drops whatever is still queued, stops the worker - // and joins it; a release on the worker itself lets it return after the job it is in. + // A device holds the workers while it lives. The last release drops whatever is still queued, stops the workers + // and joins them; a release on a worker itself lets it return after the job it is in. void retain() { std::lock_guard lock(mutex_); ++users_; } void release() { std::vector dropped; - Workers worker; + Workers workers; { std::lock_guard lock(mutex_); if (users_ && --users_) return; - worker = stop_locked(dropped); + workers = stop_locked(dropped); } - finish(std::move(worker), true); + finish(std::move(workers), true); } - // Process exit with a device still alive: drops the queue, refuses new jobs and waits up to `wait` for a running - // one, so ExitProcess does not end the worker inside the driver. False when a job was still running. + // Process exit with a device still alive: drops the queue, refuses new jobs and waits up to `wait` for the running + // ones, so ExitProcess does not end a worker inside the driver. False when a job was still running. bool stop_for_exit(std::chrono::milliseconds wait) { std::vector dropped; - Workers worker; + Workers workers; bool idle = true; { std::unique_lock lock(mutex_); closed_ = true; closed_flag_.store(true, std::memory_order_release); - worker = stop_locked(dropped); + workers = stop_locked(dropped); const auto me = std::this_thread::get_id(); idle = done_.wait_for(lock, wait, [&] { return std::none_of(running_.begin(), running_.end(), [&](const Running& r) { return r.thread != me; }); }); } - finish(std::move(worker), idle); + finish(std::move(workers), idle); return idle; } @@ -351,7 +445,8 @@ class PipelineCompiler { } bool worker_running() { std::lock_guard lock(mutex_); - return worker_.joinable() || graphics_worker_.joinable(); + return graphics_worker_.joinable() || + std::any_of(workers_.begin(), workers_.end(), [](const std::thread& t) { return t.joinable(); }); } // Tests: called on the worker with each job's owner, once the job counts as running and before its work. void set_job_probe(std::function probe) { @@ -365,6 +460,7 @@ class PipelineCompiler { const void* device = nullptr; std::function work; bool graphics = false; // a graphics pipeline build: the graphics worker may take it too + bool large = false; // a large module's build (CompilePool::heavy) }; static bool graphics_worker_enabled() { static const bool on = [] { @@ -373,14 +469,18 @@ class PipelineCompiler { }(); return on; } - // Both workers: the general one, and the graphics one when it was started. + // The pool's workers, and the graphics-only one when it was started (one worker only). struct Workers { - std::thread general, graphics; + std::vector general; + std::thread graphics; }; struct Running { const void* owner; const void* device; std::thread::id thread; + bool heavy = false; // large or speculative: counts against threads-1 + bool large = false; // counts against the heavy count + bool speculative = false; // a warm-up: one at a time std::function after; // after_running bool finished = false; // the job returned; `after` may be running }; @@ -401,7 +501,9 @@ class PipelineCompiler { drop_locked(dropped, [](const Job&) { return true; }); ++generation_; // the workers return when they next look: after the job each is running, if any wake_.notify_all(); - return {std::move(worker_), std::move(graphics_worker_)}; + Workers workers{std::move(workers_), std::move(graphics_worker_)}; + workers_.clear(); + return workers; } static void finish(std::thread worker, bool join) { @@ -410,7 +512,7 @@ class PipelineCompiler { else worker.detach(); } static void finish(Workers workers, bool join) { - finish(std::move(workers.general), join); + for (std::thread& worker : workers.general) finish(std::move(worker), join); finish(std::move(workers.graphics), join); } @@ -418,11 +520,34 @@ class PipelineCompiler { return *std::find_if(running_.begin(), running_.end(), [me](const Running& r) { return r.thread == me; }); } - // The first job this worker may take, most urgent first: any job for the general worker, a graphics job for the - // graphics one. + // The first job this worker may take, most urgent first (see the class comment). With one worker: any job for the + // general worker, a graphics job for the graphics one. std::multimap::iterator next_locked(bool graphics_only) { - if (!graphics_only) return jobs_.begin(); - return std::find_if(jobs_.begin(), jobs_.end(), [](const auto& entry) { return entry.second.graphics; }); + if (!pool_ || pool_->threads < 2) { + if (!graphics_only) return jobs_.begin(); + return std::find_if(jobs_.begin(), jobs_.end(), [](const auto& entry) { return entry.second.graphics; }); + } + unsigned heavy = 0, large = 0, speculative = 0, demanded = 0; + for (const Running& r : running_) { + heavy += r.heavy; + large += r.large; + speculative += r.speculative; + demanded += !r.speculative; + } + for (auto it = jobs_.begin(); it != jobs_.end(); ++it) { + const Job& job = it->second; + if (it->first == SIZE_MAX) { + if (running_.empty()) return it; + continue; + } + if (std::any_of(running_.begin(), running_.end(), [&](const Running& r) { return r.owner == job.owner; })) + continue; + if ((job.large || it->first != 0) && heavy >= pool_->threads - 1) continue; + if (job.large && large >= pool_->heavy) continue; + if (it->first != 0 && (speculative || demanded)) continue; + return it; + } + return jobs_.end(); } void run(std::uint64_t generation, bool graphics_only) { @@ -433,9 +558,11 @@ class PipelineCompiler { wake_.wait(lock, [&] { return generation_ != generation || next_locked(graphics_only) != jobs_.end(); }); if (generation_ != generation) return; auto first = next_locked(graphics_only); + const bool speculative = first->first != 0; Job job = std::move(first->second); jobs_.erase(first); - running_.push_back({job.owner, job.device, me}); + running_.push_back({job.owner, job.device, me, job.large || speculative, job.large, speculative}); + stats_.most_running = (std::max)(stats_.most_running, running_.size()); const auto probe = probe_; lock.unlock(); try { @@ -463,6 +590,7 @@ class PipelineCompiler { return r.thread == me; })); done_.notify_all(); + wake_.notify_all(); // a job this one held back (its PSO's, a heavy one, a checkpoint) may go now } } @@ -470,9 +598,10 @@ class PipelineCompiler { std::condition_variable wake_; std::condition_variable done_; std::multimap jobs_; - std::vector running_; // one per worker; a stopped worker may still be finishing one - std::thread worker_; - std::thread graphics_worker_; // graphics jobs only (submit's `graphics`), started at the first one + std::vector running_; // one per busy worker; a stopped worker may still be finishing one + std::vector workers_; // CompilePool::threads, started at the first job + std::thread graphics_worker_; // one worker only: graphics jobs (submit's `graphics`), started at the first one + std::optional pool_; // read at the first submit unless configure() came first std::uint64_t generation_ = 0; // a worker runs while this is the value it started with unsigned users_ = 0; // live devices (retain/release) bool closed_ = false; // stop_for_exit: nothing more is queued diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 1fb36401e3..378dc44143 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -11439,8 +11439,8 @@ class PipelineState final 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 && - big_compiles() != BigCompiles::unlimited; + graphics_large_module_ = spirv_bytes >= leonida::PipelineCompiles::large_spirv_bytes; + graphics_.large = graphics_large_module_ && big_compiles() != BigCompiles::unlimited; graphics_.estimate = leonida::large_module_estimate(spirv_bytes); if (code_stage) { @@ -11794,7 +11794,8 @@ class PipelineState final } catch (const std::exception& e) { std::fprintf(stderr, "[rt] pipeline compile worker failed: %s\n", e.what()); } - }, !compute); // a graphics build may also take the graphics worker + }, !compute, // a graphics build may also take the graphics worker + compute ? big_compute(stage_bytes_) : graphics_large_module_); // the pool's heavy count } catch (...) { } // Not queued (refused by a stop that came after the check above, or out of memory): no request stays @@ -12211,6 +12212,9 @@ class PipelineState final std::atomic early_{0}; // request_early: the last mask asked for, plus one std::string profile_shaders_; // populated only with compile tracing enabled std::size_t stage_bytes_ = 0; + // A graphics pipeline of PipelineCompiles::large_spirv_bytes or more, whatever LEONIDA_SERIAL_BIG_COMPILES says: + // the compile pool's heavy count (CompilePool) caps these and large compute builds alike. + bool graphics_large_module_ = false; std::mutex variants_mutex_; std::map variants_; VkShaderModule module_ = VK_NULL_HANDLE; diff --git a/runtime/test/d3d12_compile_pool_test.cpp b/runtime/test/d3d12_compile_pool_test.cpp new file mode 100644 index 0000000000..144d26cb05 --- /dev/null +++ b/runtime/test/d3d12_compile_pool_test.cpp @@ -0,0 +1,468 @@ +// The compile workers of PipelineCompiler (shims/d3d12_pipeline_compile.h, CompilePool), without a device: the jobs are +// functions that wait at gates the test opens, so each rule is seen while the jobs it is about are still running. +// - the pool size and heavy count from LEONIDA_COMPILE_THREADS, LEONIDA_COMPILE_HEAVY_MAX and LEONIDA_SERIAL_BIG_COMPILES; +// - a long large build does not hold up a small build a submission waits for (with one worker it still does); +// - large builds keep within the heavy count, and large and speculative ones together leave one worker free; +// - demanded jobs go first, in the order they came, then warm-ups by size, and a checkpoint only when nothing runs; +// - one job of a PSO at a time; +// - the last release with jobs running and queued: the queued ones are dropped, the running ones finish, the +// workers are joined; a device's cancel waits for its running jobs; stop_for_exit does not wait past its limit. +#include "../shims/d3d12_pipeline_compile.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +int failures = 0; +#define EXPECT(cond) \ + do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + ++failures; \ + } \ + } while (0) + +using rt::d3d12::CompilePool; +using rt::d3d12::PipelineCompiler; +using namespace std::chrono_literals; + +// A gate a job waits at until the test opens it. +struct Gate { + std::mutex mutex; + std::condition_variable changed; + bool open = false; + void wait() { + std::unique_lock lock(mutex); + changed.wait(lock, [this] { return open; }); + } + void release() { + { + std::lock_guard lock(mutex); + open = true; + } + changed.notify_all(); + } +}; + +// What the jobs did: the names in the order they started and finished, and how many ran at once. +struct Log { + std::mutex mutex; + std::condition_variable changed; + std::vector started; + std::vector finished; + int running = 0, large_running = 0, most = 0, most_large = 0; + + void start(const std::string& name, bool large) { + std::lock_guard lock(mutex); + started.push_back(name); + ++running; + large_running += large; + most = (std::max)(most, running); + most_large = (std::max)(most_large, large_running); + changed.notify_all(); + } + void finish(const std::string& name, bool large) { + std::lock_guard lock(mutex); + finished.push_back(name); + --running; + large_running -= large; + changed.notify_all(); + } + bool has_started(const std::string& name) { + std::lock_guard lock(mutex); + return std::find(started.begin(), started.end(), name) != started.end(); + } + // Waits up to `limit` for `count` jobs to have started (finished); false when they have not. + bool wait_started(std::size_t count, std::chrono::milliseconds limit = 10s) { + std::unique_lock lock(mutex); + return changed.wait_for(lock, limit, [&] { return started.size() >= count; }); + } + bool wait_finished(std::size_t count, std::chrono::milliseconds limit = 10s) { + std::unique_lock lock(mutex); + return changed.wait_for(lock, limit, [&] { return finished.size() >= count; }); + } +}; + +// Owners only need distinct addresses. +struct Owners { + char slots[64]{}; + const void* operator[](std::size_t i) const { return &slots[i]; } +}; +const char device_slot = 0; +const void* const device = &device_slot; + +// A pool of `threads` workers and `heavy` large builds at once, never destroyed: a worker detached by stop_for_exit may +// still be returning from its job. +PipelineCompiler& make_pool(unsigned threads, unsigned heavy) { + auto* pool = new PipelineCompiler; + CompilePool config; + config.threads = threads; + config.heavy = heavy; + EXPECT(pool->configure(config)); + EXPECT(!pool->configure(config)); // once + pool->retain(); + return *pool; +} + +void submit(PipelineCompiler& pool, Log& log, Gate* gate, const void* owner, const std::string& name, + std::size_t priority = 0, bool large = false) { + EXPECT(pool.submit(owner, device, priority, [&log, gate, name, large] { + log.start(name, large); + if (gate) gate->wait(); + log.finish(name, large); + }, false, large)); +} + +void test_pool_settings() { + auto pool = rt::d3d12::compile_pool(nullptr, nullptr, 16, false); + EXPECT(pool.threads == 8 && pool.heavy == 7); + pool = rt::d3d12::compile_pool(nullptr, nullptr, 32, false); + EXPECT(pool.threads == 8); + pool = rt::d3d12::compile_pool(nullptr, nullptr, 6, false); + EXPECT(pool.threads == 3 && pool.heavy == 2); + pool = rt::d3d12::compile_pool(nullptr, nullptr, 2, false); + EXPECT(pool.threads == 2 && pool.heavy == 1); + pool = rt::d3d12::compile_pool(nullptr, nullptr, 0, false); // hardware_concurrency may answer 0 + EXPECT(pool.threads == 2); + pool = rt::d3d12::compile_pool(L"1", nullptr, 16, false); + EXPECT(pool.threads == 1 && pool.heavy == 1); + pool = rt::d3d12::compile_pool(L"0", nullptr, 16, false); + EXPECT(pool.threads == 1); + pool = rt::d3d12::compile_pool(L"200", nullptr, 16, false); + EXPECT(pool.threads == 64); + pool = rt::d3d12::compile_pool(L"6", L"2", 16, false); + EXPECT(pool.threads == 6 && pool.heavy == 2); + pool = rt::d3d12::compile_pool(L"6", L"9", 16, false); + EXPECT(pool.heavy == 5); // one worker stays free + pool = rt::d3d12::compile_pool(L"6", L"0", 16, false); + EXPECT(pool.heavy == 1); + pool = rt::d3d12::compile_pool(L"6", nullptr, 16, true); // LEONIDA_SERIAL_BIG_COMPILES=1 + EXPECT(pool.heavy == 1); + pool = rt::d3d12::compile_pool(L"6", L"3", 16, true); // an explicit count wins + EXPECT(pool.heavy == 3); + pool = rt::d3d12::compile_pool(L"six", L"x", 16, false); + EXPECT(!pool.threads_valid && !pool.heavy_valid && pool.threads == 8 && pool.heavy == 7); +} + +void test_long_build_does_not_hold_up_a_small_demanded_one() { + auto& pool = make_pool(2, 1); + Log log; + Gate long_build; + Owners owner; + submit(pool, log, &long_build, owner[0], "large", 0, true); + EXPECT(log.wait_started(1)); + submit(pool, log, nullptr, owner[1], "small"); + EXPECT(log.wait_finished(1)); // while the large one still runs + EXPECT(log.has_started("small")); + // A second large one waits for the first (heavy count 1); a small one after it does not. + submit(pool, log, nullptr, owner[2], "large 2", 0, true); + submit(pool, log, nullptr, owner[3], "small 2"); + EXPECT(log.wait_finished(2)); + std::this_thread::sleep_for(100ms); + EXPECT(!log.has_started("large 2")); + long_build.release(); + EXPECT(log.wait_finished(4)); + pool.wait_idle(); + EXPECT(log.most_large == 1); + EXPECT(pool.stats().threads == 2 && pool.stats().most_running == 2); + pool.release(); +} + +void test_one_worker_keeps_the_old_order() { + auto& pool = make_pool(1, 1); // LEONIDA_COMPILE_THREADS=1 + Log log; + Gate long_build; + Owners owner; + submit(pool, log, &long_build, owner[0], "large", 0, true); + EXPECT(log.wait_started(1)); + submit(pool, log, nullptr, owner[1], "small"); + std::this_thread::sleep_for(100ms); + EXPECT(!log.has_started("small")); // behind the large one, as before the pool + long_build.release(); + EXPECT(log.wait_finished(2)); + EXPECT(pool.stats().threads == 1 && pool.stats().most_running == 1); + pool.release(); +} + +void test_heavy_count_and_the_free_worker() { + auto& pool = make_pool(4, 2); + Log log; + Gate hold; + Owners owner; + for (int i = 0; i < 4; ++i) submit(pool, log, &hold, owner[i], "large " + std::to_string(i), 0, true); + EXPECT(log.wait_started(2)); + std::this_thread::sleep_for(100ms); + EXPECT(log.most_large == 2); // the heavy count + // No warm-up while demanded builds are running or held back. + submit(pool, log, &hold, owner[4], "warm a", 1000); + submit(pool, log, &hold, owner[5], "warm b", 2000); + std::this_thread::sleep_for(100ms); + { + std::lock_guard lock(log.mutex); + EXPECT(log.started.size() == 2); + EXPECT(log.running == 2); + } + // The last worker is free for a small demanded build. + Gate small; + submit(pool, log, &small, owner[6], "small"); + EXPECT(log.wait_started(3)); + EXPECT(log.has_started("small")); + small.release(); + hold.release(); + EXPECT(log.wait_finished(7)); + pool.wait_idle(); + EXPECT(log.most_large <= 2); + EXPECT(log.most <= 4); + pool.release(); +} + +// Warm-ups one at a time, as on the single worker (each holds the compile gate for its whole create), while the other +// workers take demanded builds. +void test_one_warm_up_at_a_time() { + auto& pool = make_pool(4, 3); + Log log; + Gate hold; + Owners owner; + submit(pool, log, &hold, owner[0], "warm a", 100); + submit(pool, log, &hold, owner[1], "warm b", 200); + EXPECT(log.wait_started(1)); + std::this_thread::sleep_for(100ms); + EXPECT(!log.has_started("warm b")); // four workers, nothing else to do, still one warm-up + submit(pool, log, &hold, owner[2], "demand"); + EXPECT(log.wait_started(2)); + std::this_thread::sleep_for(100ms); + EXPECT(!log.has_started("warm b")); + hold.release(); + EXPECT(log.wait_finished(3)); + pool.wait_idle(); + std::lock_guard lock(log.mutex); + EXPECT(log.started.front() == "warm a"); + pool.release(); +} + +// A warm-up already running does not keep a demanded build waiting, and the next warm-up waits for it. +void test_demanded_builds_go_before_warm_ups() { + auto& pool = make_pool(3, 2); + Log log; + Gate warm, demand; + Owners owner; + submit(pool, log, &warm, owner[0], "warm 1", 100); + EXPECT(log.wait_started(1)); + submit(pool, log, nullptr, owner[1], "warm 2", 50); // smaller, but not before the first warm-up ends + submit(pool, log, &demand, owner[2], "demand", 0, true); + EXPECT(log.wait_started(2)); + EXPECT(log.has_started("demand")); + warm.release(); + EXPECT(log.wait_finished(1)); + std::this_thread::sleep_for(100ms); + EXPECT(!log.has_started("warm 2")); // the demanded build still runs + demand.release(); + EXPECT(log.wait_finished(3)); + pool.release(); +} + +// A running warm-up takes a heavy place too: with two workers a large demanded build then waits, and the other worker +// stays free for a small one. +void test_a_warm_up_and_a_large_build_leave_a_worker_free() { + auto& pool = make_pool(2, 1); + Log log; + Gate warm, small; + Owners owner; + submit(pool, log, &warm, owner[0], "warm", 100); + EXPECT(log.wait_started(1)); + submit(pool, log, nullptr, owner[1], "large", 0, true); + std::this_thread::sleep_for(100ms); + EXPECT(!log.has_started("large")); + submit(pool, log, &small, owner[2], "small"); + EXPECT(log.wait_started(2)); + EXPECT(log.has_started("small")); + small.release(); + warm.release(); + EXPECT(log.wait_finished(3)); + pool.release(); +} + +void test_order() { + auto& pool = make_pool(2, 1); + Log log; + Gate first, second; + Owners owner; + submit(pool, log, &first, owner[0], "busy 1"); + submit(pool, log, &second, owner[1], "busy 2"); + EXPECT(log.wait_started(2)); + // Queued while both workers are busy. + submit(pool, log, nullptr, device, "checkpoint", SIZE_MAX); + submit(pool, log, nullptr, owner[2], "warm 200", 200); + submit(pool, log, nullptr, owner[3], "warm 100", 100); + submit(pool, log, nullptr, owner[4], "demand x"); + submit(pool, log, nullptr, owner[5], "demand y"); + EXPECT(pool.has_compile_waiter()); + second.release(); // one worker takes the demanded ones; "busy 1" keeps the other + EXPECT(log.wait_finished(3)); + std::this_thread::sleep_for(100ms); + // No warm-up while a demanded build ("busy 1") runs: the compile gate would hold submissions behind it. + EXPECT(!log.has_started("warm 100") && !log.has_started("warm 200")); + EXPECT(!log.has_started("checkpoint")); + EXPECT(pool.has_compile_waiter()); // the warm-ups + first.release(); + EXPECT(log.wait_finished(7)); + std::lock_guard lock(log.mutex); + const std::vector want{"busy 1", "busy 2", "demand x", "demand y", "warm 100", "warm 200", + "checkpoint"}; + EXPECT(log.started == want); + pool.release(); +} + +void test_one_job_of_a_pso_at_a_time() { + auto& pool = make_pool(4, 3); + Log log; + Gate hold; + Owners owner; + submit(pool, log, &hold, owner[0], "variant 0"); + EXPECT(log.wait_started(1)); + submit(pool, log, nullptr, owner[0], "variant 1"); + submit(pool, log, nullptr, owner[1], "other"); + EXPECT(log.wait_finished(1)); // "other" passes the second job of owner 0 + std::this_thread::sleep_for(100ms); + EXPECT(!log.has_started("variant 1")); + hold.release(); + EXPECT(log.wait_finished(3)); + pool.release(); +} + +// One finished job lets two held-back ones go: the worker that ran it takes one, an idle worker the other. +void test_a_finished_job_wakes_the_idle_workers() { + auto& pool = make_pool(3, 1); + Log log; + Gate first, second; + Owners owner; + submit(pool, log, &first, owner[0], "large a", 0, true); + EXPECT(log.wait_started(1)); + submit(pool, log, &second, owner[1], "large b", 0, true); // held: heavy count 1 + submit(pool, log, &second, owner[0], "a again"); // held: owner 0 runs + std::this_thread::sleep_for(100ms); + { + std::lock_guard lock(log.mutex); + EXPECT(log.started.size() == 1); + } + first.release(); + EXPECT(log.wait_started(3, 3s)); // both, while each still waits at `second` + second.release(); + EXPECT(log.wait_finished(3)); + pool.release(); +} + +void test_release_with_jobs_running_and_queued() { + auto& pool = make_pool(3, 2); + Log log; + Gate hold; + Owners owner; + submit(pool, log, &hold, owner[0], "running 1"); + submit(pool, log, &hold, owner[1], "running 2", 0, true); + EXPECT(log.wait_started(2)); + for (int i = 0; i < 5; ++i) submit(pool, log, &hold, owner[2], "queued " + std::to_string(i)); // one PSO + EXPECT(log.wait_started(3)); // the first of them takes the third worker; the rest wait for it + std::atomic released{false}; + std::thread releaser([&] { + pool.release(); // the last user: drops the queue, waits for the running jobs and joins the workers + released = true; + }); + std::this_thread::sleep_for(100ms); + EXPECT(!released); + hold.release(); + releaser.join(); + EXPECT(released); + EXPECT(!pool.worker_running()); + const auto stats = pool.stats(); + EXPECT(stats.completed == 3); + EXPECT(stats.dropped == 4); + // Submitting again starts the workers again. + pool.retain(); + Log again; + submit(pool, again, nullptr, owner[3], "after"); + EXPECT(again.wait_finished(1)); + pool.release(); +} + +void test_cancel_waits_for_a_devices_running_jobs() { + auto& pool = make_pool(3, 2); + Log log; + Gate hold; + Owners owner; + submit(pool, log, &hold, owner[0], "a"); + submit(pool, log, &hold, owner[1], "b"); + EXPECT(log.wait_started(2)); + submit(pool, log, &hold, owner[1], "b again"); // queued behind "b" (same PSO) + std::atomic cancelled{false}; + std::thread canceller([&] { + pool.cancel(device); + cancelled = true; + }); + std::this_thread::sleep_for(100ms); + EXPECT(!cancelled); + hold.release(); + canceller.join(); + { + std::lock_guard lock(log.mutex); + EXPECT(log.finished.size() == 2); + EXPECT(log.running == 0); + } + EXPECT(!log.has_started("b again")); + EXPECT(pool.stats().dropped == 1); + pool.release(); +} + +void test_stop_for_exit_does_not_wait_past_its_limit() { + auto& pool = make_pool(2, 1); + Log log; + auto hold = std::make_shared(); + Owners owner; + EXPECT(pool.submit(owner[0], device, 0, [&log, hold] { + log.start("stuck", false); + hold->wait(); + log.finish("stuck", false); + })); + EXPECT(log.wait_started(1)); + submit(pool, log, nullptr, owner[0], "queued"); // same PSO: waits behind "stuck" + const auto start = std::chrono::steady_clock::now(); + EXPECT(!pool.stop_for_exit(100ms)); + EXPECT(std::chrono::steady_clock::now() - start < 5s); + EXPECT(pool.closed()); + EXPECT(!pool.submit(owner[2], device, 0, [] {})); + EXPECT(pool.stats().refused == 1); + hold->release(); // the detached worker returns + EXPECT(log.wait_finished(1)); + std::this_thread::sleep_for(50ms); + EXPECT(!log.has_started("queued")); +} +} // namespace + +int main() { + test_pool_settings(); + test_long_build_does_not_hold_up_a_small_demanded_one(); + test_one_worker_keeps_the_old_order(); + test_heavy_count_and_the_free_worker(); + test_one_warm_up_at_a_time(); + test_demanded_builds_go_before_warm_ups(); + test_a_warm_up_and_a_large_build_leave_a_worker_free(); + test_order(); + test_one_job_of_a_pso_at_a_time(); + test_a_finished_job_wakes_the_idle_workers(); + test_release_with_jobs_running_and_queued(); + test_cancel_waits_for_a_devices_running_jobs(); + test_stop_for_exit_does_not_wait_past_its_limit(); + if (failures) { + std::fprintf(stderr, "%d failure(s)\n", failures); + return 1; + } + std::printf("PASS d3d12_compile_pool\n"); + return 0; +} From 2d56b685ac69d0447cb5bb560e132ad354d8779d Mon Sep 17 00:00:00 2001 From: Tyrannys <80750971+Tyrannys@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:53:26 -0600 Subject: [PATCH 2/5] d3d12: the checkpoint's second look also sees a running demanded build The startup cache checkpoint starts only when no compile worker is busy, but a demanded build can start on another worker while the checkpoint queries the cache size. has_compile_waiter() only looked at the queue, so the check after the size query went on to read the cache blob while that build ran. has_compile_waiter() now also answers true while a demanded build runs. New gated test in d3d12_compile_pool_test: the checkpoint waits at a gate standing in for the size query, a demanded build starts on the second worker, and the second look must see it. It fails without the fix. Reported by lixonik in review of #2233. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_pipeline_compile.h | 7 +++++- runtime/test/d3d12_compile_pool_test.cpp | 31 ++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/runtime/shims/d3d12_pipeline_compile.h b/runtime/shims/d3d12_pipeline_compile.h index 05be862604..d1bf35b0cb 100644 --- a/runtime/shims/d3d12_pipeline_compile.h +++ b/runtime/shims/d3d12_pipeline_compile.h @@ -342,9 +342,14 @@ class PipelineCompiler { // Lock-free: replay asks at every draw and dispatch whose pipeline is not built yet. bool closed() const { return closed_flag_.load(std::memory_order_acquire); } + // True while a build other than the checkpoint is queued, or a demanded build runs. The checkpoint asks twice: before + // and after the size query, during which a demanded build can start on another worker (no warm-up can: one runs + // only when no other speculative job does, and the checkpoint counts as one). bool has_compile_waiter() { std::lock_guard lock(mutex_); - return !jobs_.empty() && jobs_.begin()->first != SIZE_MAX; + if (!jobs_.empty() && jobs_.begin()->first != SIZE_MAX) return true; + return std::any_of(running_.begin(), running_.end(), + [](const Running& r) { return !r.speculative && !r.finished; }); } // Returns when no job is queued or running. A job owns its pipeline state, and through it the device, until it // finishes; a caller that counts references (rt::d3d12_xs::device_proxy_ref_count) waits here first. diff --git a/runtime/test/d3d12_compile_pool_test.cpp b/runtime/test/d3d12_compile_pool_test.cpp index 144d26cb05..752eb438a1 100644 --- a/runtime/test/d3d12_compile_pool_test.cpp +++ b/runtime/test/d3d12_compile_pool_test.cpp @@ -4,6 +4,7 @@ // - a long large build does not hold up a small build a submission waits for (with one worker it still does); // - large builds keep within the heavy count, and large and speculative ones together leave one worker free; // - demanded jobs go first, in the order they came, then warm-ups by size, and a checkpoint only when nothing runs; +// - a checkpoint's second look sees a demanded build that started on another worker meanwhile; // - one job of a PSO at a time; // - the last release with jobs running and queued: the queued ones are dropped, the running ones finish, the // workers are joined; a device's cancel waits for its running jobs; stop_for_exit does not wait past its limit. @@ -321,6 +322,35 @@ void test_order() { pool.release(); } +// The checkpoint starts only when nothing runs, but a demanded build can start on another worker while the checkpoint +// asks the driver for the cache size. Its second look (save_session_pipeline_cache) must see that build running, or it +// goes on to read the cache blob while the build holds the driver. +void test_a_checkpoint_sees_a_demand_that_started_during_it() { + auto& pool = make_pool(2, 1); + Log log; + Gate query; + Owners owner; + std::atomic second_look{-1}; + EXPECT(pool.submit(device, device, SIZE_MAX, [&] { + log.start("checkpoint", false); + EXPECT(!pool.has_compile_waiter()); // the first look: nothing else queued or running + query.wait(); // the size query + second_look = pool.has_compile_waiter(); + log.finish("checkpoint", false); + })); + EXPECT(log.wait_started(1)); + Gate build; + submit(pool, log, &build, owner[0], "demand"); + EXPECT(log.wait_started(2)); // on the second worker, while the checkpoint runs + query.release(); + EXPECT(log.wait_finished(1)); + EXPECT(second_look == 1); + build.release(); + EXPECT(log.wait_finished(2)); + EXPECT(!pool.has_compile_waiter()); + pool.release(); +} + void test_one_job_of_a_pso_at_a_time() { auto& pool = make_pool(4, 3); Log log; @@ -454,6 +484,7 @@ int main() { test_demanded_builds_go_before_warm_ups(); test_a_warm_up_and_a_large_build_leave_a_worker_free(); test_order(); + test_a_checkpoint_sees_a_demand_that_started_during_it(); test_one_job_of_a_pso_at_a_time(); test_a_finished_job_wakes_the_idle_workers(); test_release_with_jobs_running_and_queued(); From 9b8760d32856fa71981fce702e710c77a1874b94 Mon Sep 17 00:00:00 2001 From: Tyrannys <80750971+Tyrannys@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:19:53 -0600 Subject: [PATCH 3/5] d3d12: one build of a PSO at a time with one worker plus the graphics worker With LEONIDA_COMPILE_THREADS=1 (the layout of main: one general worker and the graphics-only one) next_locked did not look at the owner, so two variants of one graphics PSO could build at once, one on each worker. A last Release meanwhile hands the PSO's deletion to the running build it finds first (after_running), and that worker deleted the PSO while the other was still in build() on it. The single-worker selection now skips a job whose PSO has a build running, as the pool already did. New test in d3d12_compile_pool_test: two graphics variants of one PSO with one worker plus the graphics worker; the second must not start while the first runs, another PSO's build still uses the free worker, and a last Release runs after the first build with the second dropped. It fails without the fix. Docs: the heavy count also bounds LEONIDA_SERIAL_BIG_COMPILES=0 on the workers; only compute creates pass the compile gate. Found by qhukz13 in review of #2233. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 6 ++-- runtime/README.md | 2 +- runtime/shims/d3d12_pipeline_compile.h | 19 +++++++---- runtime/test/d3d12_compile_pool_test.cpp | 42 +++++++++++++++++++++++- 4 files changed, 59 insertions(+), 10 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index a14e10f36f..dc071c2d63 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2619,8 +2619,10 @@ submitting thread; at the maintainers' decision it was replaced by this one when about 800 KB, and that with `LEONIDA_COMPILE_GATE=0` the same boot reached game state 3); and a PSO has one build running at a time, so `after_running` and the teardown rules hold as they were. `LEONIDA_COMPILE_THREADS=1` is the layout before the pool: - one general worker and the graphics-only one. A submission still waits at the compile gate for every create in - flight, so more workers do not shorten that wait (`SubmitMutex::CompileTurn`; `LEONIDA_COMPILE_GATE=0` turns it off). + one general worker and the graphics-only one; there too a PSO has one build running at a time (two variants of one + graphics PSO, one on each worker, let its last release delete it under the other build, qhukz13). A submission still + waits at the compile gate for every compute create in flight (graphics builds do not pass the gate), so more workers + do not shorten that wait (`SubmitMutex::CompileTurn`; `LEONIDA_COMPILE_GATE=0` turns it off). - **Warm-ups while the title submits.** A compute warm-up holds the compile gate for its whole create, and every submission waits behind it: a native boot's submissions waited 140 s in all at the gate behind compute warm-ups, and past the story load the worker went through 694 warm-ups of modules over 128 KiB (those over 640 KiB take 4-25 s diff --git a/runtime/README.md b/runtime/README.md index ffd166f7d4..197aefe14a 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -328,7 +328,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_LAZY_PIPELINES` | on | Graphics pipelines are built at their first draw. `0` builds each at `CreatePipelineState`, as before; the title creates far more pipelines at startup than it draws with. | | `LEONIDA_LAZY_COMPUTE` | on | Compute pipelines are built at the first dispatch that names them, or earlier by the warm-up thread. `0` builds each at `CreateComputePipelineState`. | | `LEONIDA_COMPUTE_WARMUP_MAX_BYTES` | `1048576` | The largest SPIR-V module, in bytes, the background warm-up thread (`LEONIDA_COMPUTE_WARMUP`) builds ahead of its first dispatch. Larger modules wait for that dispatch. | -| `LEONIDA_SERIAL_BIG_COMPILES` | unset | Large pipelines (compute modules over 128 KiB of SPIR-V, graphics pipelines of 1 MiB or more) compile side by side while their estimates, 512 bytes of memory for each byte of SPIR-V, fit a budget (`LEONIDA_BIG_COMPILE_BUDGET_MB`): one always does, what a submission waits for goes before the warm-up, and the warm-up takes a quarter of the budget at most. `1` compiles the compute ones one at a time, and the graphics ones of a submission one after another, as before there was a budget. `0` lets all of them compile side by side. | +| `LEONIDA_SERIAL_BIG_COMPILES` | unset | Large pipelines (compute modules over 128 KiB of SPIR-V, graphics pipelines of 1 MiB or more) compile side by side while their estimates, 512 bytes of memory for each byte of SPIR-V, fit a budget (`LEONIDA_BIG_COMPILE_BUDGET_MB`): one always does, what a submission waits for goes before the warm-up, and the warm-up takes a quarter of the budget at most. `1` compiles the compute ones one at a time, and the graphics ones of a submission one after another, as before there was a budget. `0` lets all of them compile side by side, within the compile workers' heavy count (`LEONIDA_COMPILE_HEAVY_MAX`) for the asynchronous builds and the warm-up. | | `LEONIDA_BIG_COMPILE_BUDGET_MB` | unset | The budget, in MiB: a fixed number (`0`: one large pipeline at a time) instead of three quarters of the memory that is free at the moment, which is the smaller of the free RAM and the room under the commit limit, read again for each pipeline. Text that is not a number is ignored. | | `LEONIDA_CONSOLE_FORMATS` | on | Texture descriptions the console accepts and a PC GPU may not (an R9G9B9E5 render target, an sRGB RGBA8 or BGRA8 texture with unordered access) get a host format that can do the job. `0` refuses them, as a PC D3D12 runtime does. | | `LEONIDA_CONSOLE_HEAP_SHADOW` | on | A console descriptor heap has a copy in the descriptor arena that the shaders read. `0` keeps its bytes in the title's memory only (the comparison for a run that misbehaves with the copy). | diff --git a/runtime/shims/d3d12_pipeline_compile.h b/runtime/shims/d3d12_pipeline_compile.h index d1bf35b0cb..4c44344578 100644 --- a/runtime/shims/d3d12_pipeline_compile.h +++ b/runtime/shims/d3d12_pipeline_compile.h @@ -263,7 +263,9 @@ inline CompilePool compile_pool_from_environment() { // large, keeps within the heavy count; when it is speculative, runs alone among speculative ones and only while // no demanded build is queued or running. // So a long driver compile holds up only the jobs of its own PSO, and a small build a submission asked for gets a free -// worker while large ones run. With one worker the order is the old one: the next job, whatever it is. +// worker while large ones run. With one worker the order is the old one: the next job, whatever it is, except that +// with the graphics-only worker beside it one build of a PSO at a time holds there too (a PSO's last Release waits only +// for the build of it that runs: two at once, one on each worker, left the other using the deleted PSO). // // Lifetime. A job names its owner (the PSO it builds, or the device for a cache checkpoint) and the device whose // Vulkan objects it uses, and holds no reference to either: a reference kept the device alive past the title's last @@ -526,11 +528,17 @@ class PipelineCompiler { } // The first job this worker may take, most urgent first (see the class comment). With one worker: any job for the - // general worker, a graphics job for the graphics one. + // general worker, a graphics job for the graphics one, but not one whose PSO has a build running on the other. std::multimap::iterator next_locked(bool graphics_only) { + // Either way a job whose PSO has one running waits: two variants of one graphics PSO, one on each worker, and + // its last release (after_running, which waits for the running job only) would delete the PSO under the other. + const auto pso_busy = [this](const Job& job) { + return std::any_of(running_.begin(), running_.end(), [&](const Running& r) { return r.owner == job.owner; }); + }; if (!pool_ || pool_->threads < 2) { - if (!graphics_only) return jobs_.begin(); - return std::find_if(jobs_.begin(), jobs_.end(), [](const auto& entry) { return entry.second.graphics; }); + return std::find_if(jobs_.begin(), jobs_.end(), [&](const auto& entry) { + return (!graphics_only || entry.second.graphics) && !pso_busy(entry.second); + }); } unsigned heavy = 0, large = 0, speculative = 0, demanded = 0; for (const Running& r : running_) { @@ -545,8 +553,7 @@ class PipelineCompiler { if (running_.empty()) return it; continue; } - if (std::any_of(running_.begin(), running_.end(), [&](const Running& r) { return r.owner == job.owner; })) - continue; + if (pso_busy(job)) continue; if ((job.large || it->first != 0) && heavy >= pool_->threads - 1) continue; if (job.large && large >= pool_->heavy) continue; if (it->first != 0 && (speculative || demanded)) continue; diff --git a/runtime/test/d3d12_compile_pool_test.cpp b/runtime/test/d3d12_compile_pool_test.cpp index 752eb438a1..4ba9c09820 100644 --- a/runtime/test/d3d12_compile_pool_test.cpp +++ b/runtime/test/d3d12_compile_pool_test.cpp @@ -5,7 +5,7 @@ // - large builds keep within the heavy count, and large and speculative ones together leave one worker free; // - demanded jobs go first, in the order they came, then warm-ups by size, and a checkpoint only when nothing runs; // - a checkpoint's second look sees a demanded build that started on another worker meanwhile; -// - one job of a PSO at a time; +// - one job of a PSO at a time, also with one worker plus the graphics-only one; // - the last release with jobs running and queued: the queued ones are dropped, the running ones finish, the // workers are joined; a device's cancel waits for its running jobs; stop_for_exit does not wait past its limit. #include "../shims/d3d12_pipeline_compile.h" @@ -193,6 +193,45 @@ void test_one_worker_keeps_the_old_order() { pool.release(); } +// One general worker plus the graphics-only one (LEONIDA_COMPILE_THREADS=1, the layout of main): two variants of one +// graphics PSO must not build at once, one on each worker. A PSO's last release attaches its deletion to the job of +// that PSO that is running (after_running); a second one still in build() on the other worker would use the deleted +// PSO (qhukz13, #2233). Another PSO's graphics build still runs beside it on the graphics worker. +void test_one_worker_and_the_graphics_worker_build_one_job_of_a_pso() { + auto& pool = make_pool(1, 1); + Log log; + Gate first; + Owners owner; + const auto graphics = [&](const void* who, const std::string& name, Gate* gate) { + EXPECT(pool.submit(who, device, 0, [&log, gate, name] { + log.start(name, false); + if (gate) gate->wait(); + log.finish(name, false); + }, true)); + }; + graphics(owner[0], "variant 1", &first); + EXPECT(log.wait_started(1)); + graphics(owner[0], "variant 2", nullptr); + std::this_thread::sleep_for(100ms); + EXPECT(!log.has_started("variant 2")); // the other worker is free, but this PSO has a build running + graphics(owner[1], "other pso", nullptr); + EXPECT(log.wait_finished(1)); // the free worker takes another PSO's build meanwhile + EXPECT(log.has_started("other pso") && !log.has_started("variant 2")); + // The PSO's last release while "variant 1" runs: "variant 2" is dropped, and the deletion runs after "variant 1". + std::atomic deleted{false}, variant_running_at_delete{false}; + EXPECT(pool.after_running(owner[0], [&] { + std::lock_guard lock(log.mutex); + variant_running_at_delete = log.running != 0; + deleted = true; + })); + first.release(); + EXPECT(log.wait_finished(2)); + pool.wait_idle(); + EXPECT(deleted.load() && !variant_running_at_delete.load()); + EXPECT(!log.has_started("variant 2")); + pool.release(); +} + void test_heavy_count_and_the_free_worker() { auto& pool = make_pool(4, 2); Log log; @@ -479,6 +518,7 @@ int main() { test_pool_settings(); test_long_build_does_not_hold_up_a_small_demanded_one(); test_one_worker_keeps_the_old_order(); + test_one_worker_and_the_graphics_worker_build_one_job_of_a_pso(); test_heavy_count_and_the_free_worker(); test_one_warm_up_at_a_time(); test_demanded_builds_go_before_warm_ups(); From 03ec559ac1a829f9ff2c7f6c425e05b65f30df64 Mon Sep 17 00:00:00 2001 From: Tyrannys <80750971+Tyrannys@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:54:43 -0600 Subject: [PATCH 4/5] d3d12_compile_pool_test: wait for an idle pool before the checkpoint test's last check The demanded job leaves the running list only after its function returns, so has_compile_waiter() could still see it right after the log said it had finished (1 failure in 10 runs). Found while merging this into #2275. Co-Authored-By: Claude Opus 5.5 --- runtime/test/d3d12_compile_pool_test.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/test/d3d12_compile_pool_test.cpp b/runtime/test/d3d12_compile_pool_test.cpp index 4ba9c09820..2bf1cdb61c 100644 --- a/runtime/test/d3d12_compile_pool_test.cpp +++ b/runtime/test/d3d12_compile_pool_test.cpp @@ -385,7 +385,7 @@ void test_a_checkpoint_sees_a_demand_that_started_during_it() { EXPECT(log.wait_finished(1)); EXPECT(second_look == 1); build.release(); - EXPECT(log.wait_finished(2)); + pool.wait_idle(); // the job leaves the running list after its function returns EXPECT(!pool.has_compile_waiter()); pool.release(); } From 78a5eab40a4dec56adcef7bbe5d157c0c3584da4 Mon Sep 17 00:00:00 2001 From: Tyrannys <80750971+Tyrannys@users.noreply.github.com> Date: Fri, 27 Nov 2026 05:56:51 -0600 Subject: [PATCH 5/5] d3d12: single-worker owner check written as in #2361 qhukz13 claimed and fixed the same race for main in #2361 (RT-COMPILE-OWNER-RACE). The single-worker branch of next_locked now uses their code line for line, so whichever of the two lands second merges trivially. The pool branch is as before 9b8760d32. No behaviour change; d3d12_compile_pool_test passes 5 of 5 repeats. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_pipeline_compile.h | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/runtime/shims/d3d12_pipeline_compile.h b/runtime/shims/d3d12_pipeline_compile.h index b0192716d3..2a79989837 100644 --- a/runtime/shims/d3d12_pipeline_compile.h +++ b/runtime/shims/d3d12_pipeline_compile.h @@ -557,14 +557,14 @@ class PipelineCompiler { // The first job this worker may take, most urgent first (see the class comment). With one worker: any job for the // general worker, a graphics job for the graphics one, but not one whose PSO has a build running on the other. std::multimap::iterator next_locked(bool graphics_only) { - // Either way a job whose PSO has one running waits: two variants of one graphics PSO, one on each worker, and - // its last release (after_running, which waits for the running job only) would delete the PSO under the other. - const auto pso_busy = [this](const Job& job) { - return std::any_of(running_.begin(), running_.end(), [&](const Running& r) { return r.owner == job.owner; }); - }; + // As on main with #2361 (qhukz13, RT-COMPILE-OWNER-RACE): a job whose PSO has an entry running waits, so + // after_running never deletes a PSO while another build of it runs on the other worker. if (!pool_ || pool_->threads < 2) { - return std::find_if(jobs_.begin(), jobs_.end(), [&](const auto& entry) { - return (!graphics_only || entry.second.graphics) && !pso_busy(entry.second); + return std::find_if(jobs_.begin(), jobs_.end(), [this, graphics_only](const auto& entry) { + if (graphics_only && !entry.second.graphics) return false; + const void* owner = entry.second.owner; + // A finished entry may still be running what comes after its job (the PSO's deletion): it counts too. + return std::none_of(running_.begin(), running_.end(), [owner](const Running& r) { return r.owner == owner; }); }); } unsigned heavy = 0, large = 0, speculative = 0, demanded = 0; @@ -580,7 +580,8 @@ class PipelineCompiler { if (running_.empty()) return it; continue; } - if (pso_busy(job)) continue; + if (std::any_of(running_.begin(), running_.end(), [&](const Running& r) { return r.owner == job.owner; })) + continue; if ((job.large || it->first != 0) && heavy >= pool_->threads - 1) continue; if (job.large && large >= pool_->heavy) continue; if (it->first != 0 && (speculative || demanded)) continue;