diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 6df6657bdf..ae6995bfae 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2387,22 +2387,47 @@ Pipeline creation: compute programs and drops their dispatches, direct and indirect; the first dropped dispatch of each is logged. It is a way past a program that hangs the GPU while the program or its input is fixed, not a fix. `LEONIDA_STARTUP_CACHE_CHECKPOINTS=1` also schedules a snapshot after a successful pipeline build, - at most once per 120 seconds. It starts on the compile worker when queued builds have drained and the device - has no active builds. These snapshots have an additional 512 MiB ceiling. The driver fills a mapped staging + at most once per 120 seconds. It starts on a compile worker when queued builds have drained, no worker is in a build + and the device has no active builds. These snapshots have an additional 512 MiB ceiling. The driver fills a mapped staging file directly. A successful snapshot atomically replaces the session. An interrupted write preserves the previous cache; the next launch removes unheld staging files older than ten minutes. `LEONIDA_TRACE_PIPELINE_COMPILE=1` records each graphics and compute build's trigger, thread, elapsed time, SPIR-V size, shader names and Vulkan application-cache feedback (1 hit, 0 miss, -1 unavailable). It also times cache reads, merges, writes and draw/dispatch pipeline lookups that take at least 1 ms. - `LEONIDA_ASYNC_PIPELINES=1` schedules cold first-use builds on the warm-up worker ahead of speculative work. + `LEONIDA_ASYNC_PIPELINES=1` schedules cold first-use builds on the compile workers ahead of speculative work. Replay skips a draw or dispatch while its pipeline is pending. Later uses find the completed handle. A skipped dispatch can lose a one-time resource update. Synchronous first use is the default and strict - replay always uses it. `LEONIDA_COMPUTE_WARMUP=0` restricts the worker to pipelines requested by the title. + replay always uses it. `LEONIDA_COMPUTE_WARMUP=0` restricts the workers to pipelines requested by the title. + The compile workers (`PipelineCompiler`) run those builds, the warm-up and the cache checkpoint on + `LEONIDA_COMPILE_THREADS` threads below normal priority: unset, half the logical processors, at least 2 and at most + 8; `1` is the one thread there was (RT-ASYNC-COMPILE-POOL). A worker takes the first job it may start: the builds a + draw or dispatch asked for in the order they came, then the warm-up's by module size, then the checkpoint. All but + one of the workers at most are in heavy builds at a time, which are the warm-up's and the demanded ones of large + pipelines (below; by size, whatever `LEONIDA_SERIAL_BIG_COMPILES` says), so one worker is left for a build that is + not heavy and a submission asked for: it no longer waits behind a module the driver takes minutes over, or behind + the warm-up. Light builds are not limited, so graphics pipelines below the large size (a mesh pipeline of a few + hundred KiB, say) can still occupy every worker at once. Of + the very large builds, 1 MiB of SPIR-V or more, one runs at a time, demanded or not + (`LEONIDA_COMPILE_HEAVY_MAX=`; `0`: no limit of their own): the memory gate lets in what fits the free memory, + and a driver may fail modules it takes half an hour over when it compiles several side by side. A large build + waits for its place at the memory gate (below) inside its job, and counts as heavy while it waits. One PSO has one + build at a time, the next of its variants after the one that runs. A checkpoint starts only when no worker is in a + build, and gives way to one that starts while it reads the cache's size. With several workers the pipelines become + ready in an order that differs from run to run, and so do the draws skipped meanwhile; the driver holds memory for + each thread that compiles (about 50 MiB, below). The pool shortens the time a demanded pipeline is pending and does + not end it: a draw or dispatch is still skipped for as long as its own build takes. Measured with synthetic modules + no run had compiled (`d3d12_compile_pool_test measure 4194304 200 `; RTX 4060, NVIDIA 610.88, Windows 11, 12 + logical processors, two alternating runs each, on a machine that was building other things): a dispatch asks for a + compute module of 4 MiB, which the driver takes 92 to 173 s over, and the next submission for 200 modules of + 12 KiB. With 6 workers the 200 are ready 1.3 and 6.9 s after the first dispatch, 200 compiles on 5 other threads + inside the large one; with one thread, after 99 and 152 s, behind it. Peak commit 714 and 720 MiB against 645 and + 681. Tested by `pipeline_compiler_pool` (the rules, with made-up jobs), `d3d12_compile_teardown` and + `d3d12_compile_pool` (a GPU; each with the default, 1 and 4 workers). A queued build holds no reference to its PSO or device (`PipelineCompiler`, `runtime/shims/d3d12_pipeline_compile.h`). A PSO's last release drops its queued builds and returns at once; one already running is left to finish, and the worker deletes the PSO after it (`PipelineState::last_release`). The PSO's device reference goes at the release, so the release that tears the device down waits for that build, drops the device's cache checkpoint, and the last - device stops and joins the worker before any Vulkan object goes; the session cache is written after that. gta6rt, + device stops and joins the workers before any Vulkan object goes; the session cache is written after that. gta6rt, which ends with the device alive, drops the queue and waits up to 2 s for a running build before `ExitProcess` and on a console Ctrl+C, Ctrl+Break or close; after that nothing is queued, and a first use builds in place (`d3d12_compile_teardown_test`). @@ -2439,16 +2464,35 @@ Pipeline creation: 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 + Large pipelines (below) are compiled within a memory budget, and the variants of one PSO one after another. + `LEONIDA_ASYNC_PIPELINES=1` is not changed: its builds stay on the compile workers (above). 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`. +- Large pipelines: a compile takes the driver some hundred bytes of memory for each byte of SPIR-V + ([pipeline_check.md](pipeline_check.md), "Limiting concurrent compilation of large modules"), so compute modules over + 128 KiB and graphics pipelines of 1 MiB or more compile side by side only while their estimates (512 bytes for each + byte of SPIR-V) fit a budget: three quarters of the smaller of the free RAM and the room under the commit limit, read + again whenever a place at the gate (`runtime/src/large_module_gate.h`, one for the process) is given or returned. One + always gets in when none is, so a pipeline larger than the budget compiles alone. An estimate counts in full until + the compile ends, although the driver has taken part of it by then. They get in in the order they came, the ones a + submission waits for (and those of `LEONIDA_ASYNC_PIPELINES`) before the warm-up's, which take a quarter of the + budget at most and none while a submission that has large ones is compiling on its workers. A thread that waits for + its place holds no PSO's lock, and one that has a place waits for none. `PipelineCompiles::build` gives a submission + as many jobs for large ones as its smallest could be in at once, largest first; where the next one does not fit, the + job compiles small ones in the meantime. `LEONIDA_SERIAL_BIG_COMPILES=1` compiles them one after another instead, as + before there was a budget, `=0` has no limit, `LEONIDA_BIG_COMPILE_BUDGET_MB` fixes the budget. Measured with + synthetic integer modules never compiled before and the warm-up off (RTX 3080, NVIDIA 621.24, Ryzen 7 5800X3D, 8 + workers and the submitting thread, three alternating runs each): the first submission of 16 modules of 256 KiB takes + 0.8 s instead of 4.0 to 4.8 s, 16 of 512 KiB 2.0 to 2.2 s instead of 10.2 to 11.4, 15 of 1 MiB 5.8 to 6.1 s instead + of 29.2 to 31.2, 12 of 0.5 to 2 MiB 8.0 to 10.5 s instead of 38.9 to 39.9. While the 15 of 1 MiB compile, private + memory peaks 656 to 676 MiB over what it was, instead of 140 to 147 (one compile takes 85 to 131 bytes for each byte + of SPIR-V here, and the driver keeps memory for each thread that compiles). With a budget of 1536 MiB, two at once, + they take 18.5 s and peak 202 MiB over. Not measured: other drivers, and the title. Tested by `big_compile_gate`, + `replay_pipeline_compiles` and `d3d12_big_compute`. **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/docs/pipeline_check.md b/docs/pipeline_check.md index d5d76cb931..47e3a409c5 100644 --- a/docs/pipeline_check.md +++ b/docs/pipeline_check.md @@ -256,7 +256,7 @@ acceptance only. A SPIR-V module larger than 4 MiB is "large". [#884](https://github.com/ItsNotRexed/Leonida/issues/884) showed why that matters: several compiles that each needed gigabytes of host RAM ran at the same time. Large -modules now share a memory budget (`runtime/test/large_module_gate.h`): each one reserves 512 bytes of RAM per +modules now share a memory budget (`runtime/src/large_module_gate.h`): each one reserves 512 bytes of RAM per SPIR-V byte, and they enter the driver while their reservations fit three quarters of the memory available when the run starts, up to `--jobs` of them. One large module always gets in when none is compiling, so a module bigger than the whole budget still compiles, alone among the large ones. Small modules are never held back. On diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 0947b53031..8871e5ca9f 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -783,6 +783,12 @@ if(BUILD_TESTING) add_executable(xdxr_build_output_test test/xdxr_build_output_test.cpp) add_test(NAME xdxr_build_output COMMAND xdxr_build_output_test) + # The gate of large_module_gate.h as the runtime uses it for large pipelines (LEONIDA_BIG_COMPILE_BUDGET_MB): pure + # stdlib. + add_executable(big_compile_gate_test test/big_compile_gate_test.cpp) + target_link_libraries(big_compile_gate_test PRIVATE Threads::Threads) + add_test(NAME big_compile_gate COMMAND big_compile_gate_test) + set_tests_properties(big_compile_gate PROPERTIES TIMEOUT 120) # vk_pipeline_check's memory budget for large modules: pure stdlib, no Vulkan device. add_executable(large_module_gate_test test/large_module_gate_test.cpp) find_package(Threads REQUIRED) @@ -2377,8 +2383,53 @@ if(TARGET Vulkan::Headers) 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-") + # One large pipeline after another: the jobs of the pool are then known (d3d12_big_compute has the budget). + set_tests_properties(d3d12_pipeline_workers PROPERTIES ENVIRONMENT "LEONIDA_SERIAL_BIG_COMPILES=1") set_tests_properties(d3d12_pipeline_workers_eager PROPERTIES - ENVIRONMENT "LEONIDA_LAZY_PIPELINES=0;LEONIDA_LAZY_COMPUTE=0") + ENVIRONMENT "LEONIDA_LAZY_PIPELINES=0;LEONIDA_LAZY_COMPUTE=0;LEONIDA_SERIAL_BIG_COMPILES=1") + # Large pipelines compiled within a memory budget, with real large compute modules: the same values for each setting + # (read once for each process). 260 MiB holds three of the modules, 1 MiB none. The modules' compile runs on the test's + # threads, so they get the loader's stack (docs/pipeline_check.md, "Stack reserve"). + add_executable(d3d12_big_compute_test test/d3d12_big_compute_test.cpp) + target_link_libraries(d3d12_big_compute_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_big_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_big_compute_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(d3d12_big_compute_test PRIVATE /STACK:${GTA6RT_STACK}) + add_test(NAME d3d12_big_compute COMMAND d3d12_big_compute_test) + add_test(NAME d3d12_big_compute_budget COMMAND d3d12_big_compute_test) + add_test(NAME d3d12_big_compute_tight COMMAND d3d12_big_compute_test) + add_test(NAME d3d12_big_compute_serial COMMAND d3d12_big_compute_test) + add_test(NAME d3d12_big_compute_unlimited COMMAND d3d12_big_compute_test) + add_test(NAME d3d12_big_compute_warmup COMMAND d3d12_big_compute_test warmup) + add_test(NAME d3d12_big_compute_eager COMMAND d3d12_big_compute_test eager) + set_tests_properties(d3d12_big_compute d3d12_big_compute_budget d3d12_big_compute_tight d3d12_big_compute_serial + d3d12_big_compute_unlimited d3d12_big_compute_warmup d3d12_big_compute_eager + PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + set_tests_properties(d3d12_big_compute_budget PROPERTIES ENVIRONMENT "LEONIDA_BIG_COMPILE_BUDGET_MB=260") + set_tests_properties(d3d12_big_compute_tight d3d12_big_compute_warmup PROPERTIES + ENVIRONMENT "LEONIDA_BIG_COMPILE_BUDGET_MB=1") + set_tests_properties(d3d12_big_compute_eager PROPERTIES + ENVIRONMENT "LEONIDA_BIG_COMPILE_BUDGET_MB=1;LEONIDA_LAZY_COMPUTE=0") + set_tests_properties(d3d12_big_compute_serial PROPERTIES # neither of these two has a budget + ENVIRONMENT "LEONIDA_SERIAL_BIG_COMPILES=1;LEONIDA_BIG_COMPILE_BUDGET_MB=4096") + set_tests_properties(d3d12_big_compute_unlimited PROPERTIES + ENVIRONMENT "LEONIDA_SERIAL_BIG_COMPILES=0;LEONIDA_BIG_COMPILE_BUDGET_MB=1") + # The pipeline compiler's workers under LEONIDA_ASYNC_PIPELINES=1, with a large compute module's build held in flight: + # with more than one worker the small pipelines a submission asks for are built meanwhile, with one they wait, as + # before the pool. The builds run on the compiler's threads, which get the loader's stack as the title's do. + add_executable(d3d12_compile_pool_test test/d3d12_compile_pool_test.cpp) + target_link_libraries(d3d12_compile_pool_test PRIVATE gta6rt_d3d12_com psapi) + 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) + target_link_options(d3d12_compile_pool_test PRIVATE /STACK:${GTA6RT_STACK}) + add_test(NAME d3d12_compile_pool COMMAND d3d12_compile_pool_test) + add_test(NAME d3d12_compile_pool_one_thread COMMAND d3d12_compile_pool_test) + add_test(NAME d3d12_compile_pool_four_threads COMMAND d3d12_compile_pool_test) + set_tests_properties(d3d12_compile_pool d3d12_compile_pool_one_thread d3d12_compile_pool_four_threads PROPERTIES + SKIP_RETURN_CODE 77 TIMEOUT 600 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + set_tests_properties(d3d12_compile_pool_one_thread PROPERTIES ENVIRONMENT "LEONIDA_COMPILE_THREADS=1") + set_tests_properties(d3d12_compile_pool_four_threads PROPERTIES ENVIRONMENT "LEONIDA_COMPILE_THREADS=4") # 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) @@ -3628,8 +3679,15 @@ if(TARGET Vulkan::Headers) target_compile_definitions(d3d12_compile_teardown_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") target_compile_options(d3d12_compile_teardown_test PRIVATE /W4 /permissive- /utf-8) + # Three times: with the compiler's default number of workers, with the one thread there was before the pool, + # and with 4, which is more than the default of a machine with fewer than 8 logical processors. add_test(NAME d3d12_compile_teardown COMMAND d3d12_compile_teardown_test) - set_tests_properties(d3d12_compile_teardown PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) + add_test(NAME d3d12_compile_teardown_one_thread COMMAND d3d12_compile_teardown_test) + add_test(NAME d3d12_compile_teardown_four_threads COMMAND d3d12_compile_teardown_test) + set_tests_properties(d3d12_compile_teardown d3d12_compile_teardown_one_thread d3d12_compile_teardown_four_threads + PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) + set_tests_properties(d3d12_compile_teardown_one_thread PROPERTIES ENVIRONMENT "LEONIDA_COMPILE_THREADS=1") + set_tests_properties(d3d12_compile_teardown_four_threads PROPERTIES ENVIRONMENT "LEONIDA_COMPILE_THREADS=4") # 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}) @@ -4258,6 +4316,16 @@ if(TARGET Vulkan::Headers) 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") + if(WIN32) + # The rules of the workers that run LEONIDA_ASYNC_PIPELINES builds, the warm-up and the cache checkpoint + # (shims/d3d12_pipeline_compile.h), with made-up jobs: no Vulkan device, no GPU. + add_executable(pipeline_compiler_pool_test test/pipeline_compiler_pool_test.cpp) + target_link_libraries(pipeline_compiler_pool_test PRIVATE Vulkan::Headers Threads::Threads) + target_compile_definitions(pipeline_compiler_pool_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(pipeline_compiler_pool_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME pipeline_compiler_pool COMMAND pipeline_compiler_pool_test) + set_tests_properties(pipeline_compiler_pool PROPERTIES TIMEOUT 180) + endif() 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/README.md b/runtime/README.md index b89a82a711..3a5a89e17a 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -321,7 +321,10 @@ 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` | on | Compute modules over 128 KiB of SPIR-V compile one at a time, because the driver's compiler needs hundreds of MiB for each. `0` lets them compile side by side. | +| `LEONIDA_COMPILE_THREADS` | unset | How many threads run the background pipeline builds: the warm-up's, the first-use builds of `LEONIDA_ASYNC_PIPELINES=1` and the startup cache checkpoint. Unset: half the logical processors, at least 2 and at most 8. All but one of them at most are in heavy builds at a time (the warm-up's, and demanded builds of large pipelines), so a small pipeline a draw or dispatch asked for does not wait behind them. `1` is the one thread there was. The driver holds about 50 MiB for each thread that compiles. | +| `LEONIDA_COMPILE_HEAVY_MAX` | `1` | How many very large pipelines (1 MiB of SPIR-V or more) the `LEONIDA_COMPILE_THREADS` workers build at a time, whether a draw or dispatch asked for them or the warm-up did, on top of the memory budget below. A driver that compiles several modules it takes half an hour over side by side may fail them. `0`: no limit of their own. Text that is not a number counts as unset. | +| `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_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). | | `LEONIDA_IMPORT_BELOW_ARENA` | unset | `1` keeps a host-memory import that the driver put below the GPU address arena. By default such an import is not used and the shadow buffer in the arena answers, because a V# cannot name an address below the arena. | diff --git a/runtime/shims/d3d12_pipeline_compile.h b/runtime/shims/d3d12_pipeline_compile.h index 3a5e045840..11a2a2b458 100644 --- a/runtime/shims/d3d12_pipeline_compile.h +++ b/runtime/shims/d3d12_pipeline_compile.h @@ -1,10 +1,12 @@ // Timing and scheduling for Vulkan pipeline creation on the D3D12 device. #pragma once +#include "../src/pipeline_workers.h" #include "../src/vulkan_replay.h" #include #include #include +#include #include #include #include @@ -12,6 +14,7 @@ #include #include #include +#include #include namespace rt::d3d12 { @@ -85,9 +88,42 @@ struct CompileTrace { }; +// LEONIDA_COMPILE_THREADS: how many threads the PipelineCompiler below runs its jobs on. Unset, empty or not a number: +// half the logical processors, at least 2 and at most 8 (leonida::pipeline_threads). 1 is the one thread there was +// before the pool; 0 counts as 1, and more than 64 as 64. +inline constexpr unsigned kMaxCompileThreads = leonida::PipelineWorkers::kMaxThreads; +inline unsigned compile_threads(const char* text, unsigned logical_processors) { + const auto parsed = leonida::pipeline_threads(text, logical_processors); + if (!text || !*text || !parsed.valid) return (std::max)(2u, parsed.count); + return (std::max)(1u, parsed.count); +} + +// LEONIDA_COMPILE_HEAVY_MAX: how many very large builds (PipelineCompiler::Size::huge) its workers are in at a time. +// Unset, empty or not a number: 1. 0: as many as the other rules allow. +inline unsigned compile_heavy_max(const char* text) { + if (!text || !*text) return 1; + const auto parsed = leonida::pipeline_threads(text, 0); + if (!parsed.valid) return 1; + return parsed.count ? parsed.count : UINT_MAX; +} + // 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. // +// Workers. N threads take the jobs (compile_threads above). A worker takes the first queued job, in that order, that +// these rules let start; with one worker that is always the first job, so the order is the one above. +// - Lane. A job is heavy when it is speculative (a priority other than zero) or was submitted as large or huge. At most +// N-1 heavy jobs run at a time (one, with one worker), so a worker is always left for a small demanded build: a +// submission's pipeline is not held behind N modules the driver takes minutes over. A heavy job that waits for +// memory inside its work (the gate of large_module_gate.h) still counts. +// - Very large. Of the jobs submitted as huge, one runs at a time (LEONIDA_COMPILE_HEAVY_MAX), demanded or +// speculative: a driver that compiles several modules it takes half an hour over side by side may fail all of +// them. They are heavy too. The memory gate does not do this: it lets in what fits the memory that is free. +// - Owner. One job of an owner at a time. Two builds of one PSO would wait for each other on the PSO's lock, and +// after_running() hands the PSO's deletion to the one running job it finds: a second one would use a deleted PSO. +// - Checkpoint (priority SIZE_MAX). Starts only when no worker is in a build. A build may start while it runs: +// has_compile_waiter() tells it so. +// // 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 // Release until the worker reached the job, so a released device's builds ran on (a test that then destroyed its @@ -97,16 +133,36 @@ struct CompileTrace { // 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. +// - 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; } + // What the build is, by the size of its module: `large` and `huge` builds are heavy (the lane rule), and `huge` + // ones have a limit of their own. + enum class Size : unsigned char { regular, large, huge }; + + // `threads` workers and `huge_max` very large builds at a time; 0 reads LEONIDA_COMPILE_THREADS and + // LEONIDA_COMPILE_HEAVY_MAX, once for the process. + explicit PipelineCompiler(unsigned threads = 0, unsigned huge_max = 0) : threads_(threads), huge_max_(huge_max) {} + PipelineCompiler(const PipelineCompiler&) = delete; + PipelineCompiler& operator=(const PipelineCompiler&) = delete; + // Tests make their own: drops the queue and joins the workers, after the jobs they are in. + ~PipelineCompiler() { + std::vector dropped; + std::vector workers; + { + std::lock_guard lock(mutex_); + workers = stop_locked(dropped); + } + finish(std::move(workers), true); + } + struct Stats { std::uint64_t submitted = 0; std::uint64_t completed = 0; // jobs the worker ran @@ -116,18 +172,29 @@ class PipelineCompiler { std::uint64_t deferred = 0; // after_running calls that left something to run after a running job }; - // False, with nothing queued, after stop_for_exit. - bool submit(const void* owner, const void* device, std::size_t priority, std::function work) { + // False, with nothing queued, after stop_for_exit. `size`: a demanded build (priority zero) of a module the + // driver takes long over counts as heavy, as every speculative build does, and a huge one has its own limit too. + bool submit(const void* owner, const void* device, std::size_t priority, std::function work, + Size size = Size::regular) { std::lock_guard lock(mutex_); if (closed_) { ++stats_.refused; return false; } - if (!worker_.joinable()) { + if (workers_.empty()) { const std::uint64_t generation = ++generation_; - worker_ = std::thread([this, generation] { run(generation); }); + const unsigned count = threads_locked(); + workers_.reserve(count); + // A thread that cannot start leaves fewer workers, and the rules count the ones there are. + try { + for (unsigned i = 0; i < count; ++i) workers_.emplace_back([this, generation] { run(generation); }); + } catch (...) { + if (workers_.empty()) throw; + } } - jobs_.emplace(priority, Job{owner, device, std::move(work)}); + const bool checkpoint = priority == SIZE_MAX; + const Kind kind = checkpoint ? Kind::checkpoint : size != Size::regular || priority ? Kind::heavy : Kind::demand; + jobs_.emplace(priority, Job{owner, device, std::move(work), kind, !checkpoint && size == Size::huge}); ++stats_.submitted; wake_.notify_one(); return true; @@ -138,9 +205,14 @@ class PipelineCompiler { return closed_; } + // True when a build is queued, or running on another worker: what a checkpoint gives way to. 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; + const auto me = std::this_thread::get_id(); + return std::any_of(running_.begin(), running_.end(), [&](const Running& r) { + return r.kind != Kind::checkpoint && r.thread != me; + }); } // 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. @@ -172,9 +244,10 @@ class PipelineCompiler { return dropped.size(); // the dropped jobs' captures are destroyed here, outside the lock } - // Drops the queued jobs filed under `owner`. When one of its jobs is running, `last` is run on the worker after it - // returns, before the job counts as done (a device's cancel waits for both), and the answer is true; otherwise - // false, and `last` is not kept. On the worker inside that job itself, `last` runs after the job returns too. + // Drops the queued jobs filed under `owner`. When one of its jobs is running (there is at most one: the owner + // rule), `last` is run on that worker after it returns, before the job counts as done (a device's cancel waits for + // both), and the answer is true; otherwise false, and `last` is not kept. On the worker inside that job itself, + // `last` runs after the job returns too. bool after_running(const void* owner, std::function last) { std::vector dropped; std::lock_guard lock(mutex_); @@ -198,39 +271,39 @@ 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 lets that one return after the job it is in. void retain() { std::lock_guard lock(mutex_); ++users_; } void release() { std::vector dropped; - std::thread worker; + std::vector 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; - std::thread worker; + std::vector workers; bool idle = true; { std::unique_lock lock(mutex_); closed_ = true; - 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; } @@ -240,7 +313,12 @@ class PipelineCompiler { } bool worker_running() { std::lock_guard lock(mutex_); - return worker_.joinable(); + return !workers_.empty(); + } + // How many workers a start makes (LEONIDA_COMPILE_THREADS, or the constructor's number). + unsigned threads() { + std::lock_guard lock(mutex_); + return threads_locked(); } // 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) { @@ -249,15 +327,20 @@ class PipelineCompiler { } private: + enum class Kind : unsigned char { demand, heavy, checkpoint }; struct Job { const void* owner = nullptr; const void* device = nullptr; std::function work; + Kind kind = Kind::demand; + bool huge = false; }; struct Running { const void* owner; const void* device; std::thread::id thread; + Kind kind; + bool huge; std::function after; // after_running bool finished = false; // the job returned; `after` may be running }; @@ -274,17 +357,79 @@ class PipelineCompiler { } } - std::thread stop_locked(std::vector& dropped) { + unsigned threads_locked() { + if (!threads_) { + static const unsigned from_environment = [] { + char text[32]{}; + const DWORD n = GetEnvironmentVariableA("LEONIDA_COMPILE_THREADS", text, sizeof(text)); + const bool present = n > 0 && n < sizeof(text); + const unsigned count = compile_threads(present ? text : "", std::thread::hardware_concurrency()); + if (present && !leonida::pipeline_threads(text, 0).valid) + std::fprintf(stderr, "[rt] d3d12: LEONIDA_COMPILE_THREADS=%s is not a number; using %u\n", text, + count); + return count; + }(); + threads_ = from_environment; + } + return threads_; + } + + unsigned huge_max_locked() { + if (!huge_max_) { + static const unsigned from_environment = [] { + char text[32]{}; + const DWORD n = GetEnvironmentVariableA("LEONIDA_COMPILE_HEAVY_MAX", text, sizeof(text)); + const bool present = n > 0 && n < sizeof(text); + if (present && !leonida::pipeline_threads(text, 0).valid) + std::fprintf(stderr, "[rt] d3d12: LEONIDA_COMPILE_HEAVY_MAX=%s is not a number; using 1\n", text); + return compile_heavy_max(present ? text : ""); + }(); + huge_max_ = from_environment; + } + return huge_max_; + } + + std::vector stop_locked(std::vector& dropped) { drop_locked(dropped, [](const Job&) { return true; }); - ++generation_; // the worker returns when it next looks: after the job it is running, if any + ++generation_; // a worker returns when it next looks: after the job it is running, if any wake_.notify_all(); - return std::move(worker_); + return std::exchange(workers_, {}); + } + + static void finish(std::vector workers, bool join) { + for (std::thread& worker : workers) { + if (!worker.joinable()) continue; + if (join && worker.get_id() != std::this_thread::get_id()) worker.join(); + else worker.detach(); + } } - static void finish(std::thread worker, bool join) { - if (!worker.joinable()) return; - if (join && worker.get_id() != std::this_thread::get_id()) worker.join(); - else worker.detach(); + // The first queued job the rules let a worker start now (the class comment), or the end. + std::multimap::iterator next_locked() { + std::size_t heavy = 0, huge = 0; + bool compiling = false; + for (const Running& r : running_) { // a job has its place until it counts as done (after_running included) + heavy += r.kind == Kind::heavy; + huge += r.huge; + compiling |= r.kind != Kind::checkpoint; + } + // A stopped worker may still be in a job: its job counts, and it is not among workers_. + const std::size_t lane = workers_.size() > 1 ? workers_.size() - 1 : 1; + const bool lane_full = heavy >= lane; + const bool huge_full = huge >= huge_max_locked(); + for (auto it = jobs_.begin(); it != jobs_.end();) { + const Job& job = it->second; + const bool blocked = job.kind == Kind::heavy ? lane_full || (job.huge && huge_full) + : job.kind == Kind::checkpoint && compiling; + const bool owner_busy = std::any_of(running_.begin(), running_.end(), [&](const Running& r) { + return r.owner == job.owner; + }); + if (!blocked && !owner_busy) return it; + // Every job with a priority between zero and the checkpoint's is heavy: none of them can start either. + if (job.kind == Kind::heavy && lane_full && it->first) it = jobs_.lower_bound(SIZE_MAX); + else ++it; + } + return jobs_.end(); } Running& mine(std::thread::id me) { @@ -296,12 +441,12 @@ class PipelineCompiler { const auto me = std::this_thread::get_id(); std::unique_lock lock(mutex_); for (;;) { - wake_.wait(lock, [&] { return generation_ != generation || !jobs_.empty(); }); + auto first = jobs_.end(); + wake_.wait(lock, [&] { return generation_ != generation || (first = next_locked()) != jobs_.end(); }); if (generation_ != generation) return; - auto first = jobs_.begin(); 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.kind, job.huge}); const auto probe = probe_; lock.unlock(); try { @@ -329,6 +474,7 @@ class PipelineCompiler { return r.thread == me; })); done_.notify_all(); + wake_.notify_all(); // a job of this owner, a heavy job or a checkpoint may start now } } @@ -337,7 +483,9 @@ class PipelineCompiler { 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::vector workers_; + unsigned threads_ = 0; // how many workers a start makes; 0 until LEONIDA_COMPILE_THREADS is read + unsigned huge_max_ = 0; // how many huge jobs run at a time; 0 until LEONIDA_COMPILE_HEAVY_MAX is read 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 36f3556090..90ebd171e3 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -46,6 +46,7 @@ #include "../src/pipeline_profile.h" #include "../src/submit_phases.h" #include "../src/pipeline_cache_store.h" +#include "../src/large_module_gate.h" #include "../src/conservative_raster.h" #include "../src/resource_detile.h" #include "../src/console_texture_layout.h" @@ -1403,14 +1404,39 @@ 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 = [] { +// A driver's compiler needs hundreds of MiB for a very large module; several at once exhausted host memory. Large are +// compute modules over 128 KiB and graphics pipelines of PipelineCompiles::large_spirv_bytes or more. They compile side by +// side while their estimates fit the memory that is free (big_compile_gate). LEONIDA_SERIAL_BIG_COMPILES=1: one at a time, +// as before there was a budget (graphics: one after another in each submission). 0: as many as are asked for. +enum class BigCompiles { budget, serial, unlimited }; +BigCompiles big_compiles() { + static const BigCompiles mode = [] { wchar_t v[2]{}; - return !(GetEnvironmentVariableW(L"LEONIDA_SERIAL_BIG_COMPILES", v, 2) == 1 && v[0] == L'0'); + const DWORD n = GetEnvironmentVariableW(L"LEONIDA_SERIAL_BIG_COMPILES", v, 2); + if (n == 0) return BigCompiles::budget; + return n == 1 && v[0] == L'0' ? BigCompiles::unlimited : BigCompiles::serial; }(); - return serial && spirv_bytes > 128 * 1024; + return mode; +} +bool big_compute(std::size_t spirv_bytes) { return spirv_bytes > 128 * 1024; } + +// Where large compiles wait for memory: one for the process, as the memory is the machine's. Never destroyed: static +// destruction must not race the compile worker. +leonida::LargeModuleGate& big_compile_gate() { + static auto* const gate = [] { + char text[32]{}; + std::size_t length = 0; + const bool present = getenv_s(&length, text, "LEONIDA_BIG_COMPILE_BUDGET_MB") == 0 && length > 1; + const auto setting = leonida::large_compile_budget(present ? text : ""); + if (!setting.valid) + std::fprintf(stderr, "[rt] d3d12: LEONIDA_BIG_COMPILE_BUDGET_MB=%s is not a number; not used\n", text); + auto budget = [fixed = setting.fixed] { return fixed ? *fixed : leonida::large_compile_budget_bytes(); }; + std::fprintf(stderr, "[rt] d3d12: large pipelines compile side by side within %llu MiB (%s)\n", + static_cast(budget() >> 20), + setting.fixed ? "LEONIDA_BIG_COMPILE_BUDGET_MB" : "3/4 of the memory free now"); + return new leonida::LargeModuleGate(std::move(budget)); + }(); + return *gate; } bool startup_cache_checkpoints_enabled() { @@ -8931,7 +8957,9 @@ 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; + graphics_.large = spirv_bytes >= leonida::PipelineCompiles::large_spirv_bytes && + big_compiles() != BigCompiles::unlimited; + graphics_.estimate = leonida::large_module_estimate(spirv_bytes); if (code_stage) { VkDeviceSize offset = 0; @@ -9061,6 +9089,7 @@ class PipelineState final if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &pipeline_.layout) != VK_SUCCESS) return E_FAIL; compute_entry_ = entry; stage_bytes_ = spirv_bytes; + pipeline_.estimate = leonida::large_module_estimate(spirv_bytes); // The title creates hundreds of compute pipelines from job threads during startup and one of its init tasks // waits for all of them; some modules (wave64-emulated ray-tracing resolves, 4 MiB of SPIR-V) take the driver // minutes each. So the Vulkan pipeline is built on first use (build_compute): at the first dispatch that names @@ -9096,7 +9125,7 @@ class PipelineState final 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); + pipeline_.large = big_compute(spirv_bytes) && big_compiles() != BigCompiles::unlimited; } else if (!build_compute("compute-create")) { return E_FAIL; } @@ -9117,12 +9146,32 @@ class PipelineState final } private: + using Work = leonida::LargeModuleGate::Work; + + // Locks the PSO (`lock`, on variants_mutex_) for a build and, with an `estimate`, takes the build's place at the gate. A + // thread that waits for its place holds no PSO's lock, and one that has its place waits for none: another thread may be + // building that PSO, with a place of its own. Returns without a place when the PSO is `built` already. + template + leonida::LargeModuleGate::Ticket enter_build(std::unique_lock& lock, std::uint64_t estimate, Work work, + Built&& built) { + for (;;) { + lock.lock(); + if (!estimate || built()) return {}; + lock.unlock(); + leonida::LargeModuleGate::Ticket place(big_compile_gate(), estimate, work); + if (lock.try_lock()) return place; + } + } + // The compute pipeline, built once: by create_compute (LEONIDA_LAZY_COMPUTE=0), by the first dispatch that names // it (the replay layer calls ComputePipeline::build) or by the warm-up thread. Null when it cannot be built; the // failure is logged and not retried. - VkPipeline build_compute(const char* trigger) { + VkPipeline build_compute(const char* trigger, Work work = Work::demand) { CompileActivity activity(device_.active_compiles); - std::lock_guard lock(variants_mutex_); + std::unique_lock lock(variants_mutex_, std::defer_lock); + const bool budgeted = big_compute(stage_bytes_) && big_compiles() == BigCompiles::budget; + auto place = enter_build(lock, budgeted ? pipeline_.estimate : 0, work, + [this] { return pipeline_.pipeline || compute_failed_; }); if (pipeline_.pipeline || compute_failed_) return pipeline_.pipeline; compute_failed_ = true; // until the pipeline exists auto& vk = device_.context->vk; @@ -9132,7 +9181,7 @@ class PipelineState final if (!library || !entry) return VK_NULL_HANDLE; static std::mutex big_compile; std::unique_lock big_lock(big_compile, std::defer_lock); - if (serial_big_compile(stage_bytes_)) big_lock.lock(); + if (big_compute(stage_bytes_) && big_compiles() == BigCompiles::serial) 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()); @@ -9167,6 +9216,7 @@ class PipelineState final profile.finish(int(created)); trace.end(trigger, entry->name.c_str(), 0, bytes, created); if (big_lock.owns_lock()) big_lock.unlock(); + place.release(); vk.vkDestroyShaderModule(dev, module, nullptr); // Vulkan lets a module go once the pipeline exists const ULONGLONG took = GetTickCount64() - started; if (created != VK_SUCCESS || !built) { @@ -9184,9 +9234,9 @@ class PipelineState final } // Lazy compute pipelines are also built in the background, smallest module first, so most exist before their - // first dispatch. One low-priority thread; modules over LEONIDA_COMPUTE_WARMUP_MAX_BYTES of SPIR-V (default - // 1 MiB) are left to their first dispatch, since some take the driver minutes each. LEONIDA_COMPUTE_WARMUP=0 - // turns the thread off. A queued build holds no reference: a PSO released first drops it (last_release). + // first dispatch. The compiler's low-priority workers, all but one of them at most (PipelineCompiler); modules over + // LEONIDA_COMPUTE_WARMUP_MAX_BYTES of SPIR-V (default 1 MiB) are left to their first dispatch, since some take + // the driver minutes each. LEONIDA_COMPUTE_WARMUP=0 turns the warm-up off. A queued build holds no reference: a PSO released first drops it (last_release). // The startup cache checkpoint is the device's job, not this PSO's: ~Device cancels it before the cache goes. void maybe_checkpoint(VkPipelineCache cache) { if (!cache || !startup_cache_checkpoints_enabled()) return; @@ -9226,12 +9276,22 @@ class PipelineState final if (!it->second.handle) ++it->second.skips; if (!inserted) return it->second.handle; } + // A demanded build of a large module is heavy for the compiler's workers, as the warm-up is: one of them stays + // free for the small builds a submission asks for (PipelineCompiler, the lane rule). 1 MiB of SPIR-V or more + // is very large, demanded or not: one of those at a time (LEONIDA_COMPILE_HEAVY_MAX). By size alone, whatever + // LEONIDA_SERIAL_BIG_COMPILES says about memory. + const std::uint64_t huge_estimate = leonida::large_module_estimate(leonida::PipelineCompiles::large_spirv_bytes); + const auto size = (compute ? pipeline_.estimate : graphics_.estimate) >= huge_estimate + ? PipelineCompiler::Size::huge + : compute && big_compute(stage_bytes_) ? PipelineCompiler::Size::large + : PipelineCompiler::Size::regular; bool queued = false; try { queued = PipelineCompiler::instance().submit(compile_owner(), &device_, warm_bytes, [this, compute, warm, unbound] { VkPipeline built{}; try { - built = compute ? build_compute(warm ? "warmup" : "dispatch-worker") + built = compute ? build_compute(warm ? "warmup" : "dispatch-worker", + warm ? Work::speculative : Work::demand) : variant(unbound, "draw-worker"); if (async_replay_compile()) { unsigned long long skipped = 0; @@ -9249,7 +9309,7 @@ class PipelineState final } catch (const std::exception& e) { std::fprintf(stderr, "[rt] pipeline compile worker failed: %s\n", e.what()); } - }); + }, size); } catch (...) { } // Not queued (refused by a stop that came after the check above, or out of memory): no request stays @@ -9555,7 +9615,10 @@ class PipelineState final // Built on first use and kept until the PSO is released (replay may call this from any queue). VkPipeline variant(std::uint32_t unbound, const char* trigger) { - std::lock_guard lock(variants_mutex_); + std::unique_lock lock(variants_mutex_, std::defer_lock); + const bool budgeted = graphics_.large && big_compiles() == BigCompiles::budget; + const auto place = enter_build(lock, budgeted ? graphics_.estimate : 0, Work::demand, + [&] { return variants_.contains(unbound); }); if (const auto it = variants_.find(unbound); it != variants_.end()) return it->second; const VkPipeline pipeline = build(unbound, trigger); if (!pipeline) { @@ -10952,6 +11015,10 @@ class Device final threads.count); if (threads.count) state_.context->set_pipeline_workers(std::make_unique(threads.count)); + if (big_compiles() == BigCompiles::budget) + state_.context->set_large_compiles( + [] { return big_compile_gate().budget(); }, + [] { return std::make_shared(big_compile_gate()); }); } leonida::title_va_aliases().set_hooks( &state_, diff --git a/runtime/src/large_module_gate.h b/runtime/src/large_module_gate.h new file mode 100644 index 0000000000..2185f20cf0 --- /dev/null +++ b/runtime/src/large_module_gate.h @@ -0,0 +1,275 @@ +// How many large SPIR-V modules vk_pipeline_check and the runtime let into the driver at once, by a memory budget. +// +// Measured on RADV GFX1201 (Mesa 25.3.6) with the Mesa shader cache off: a 5.7 MB translated ray-tracing compute +// module peaks at 1.96 GB of process memory compiling alone (~330 bytes per SPIR-V byte), a 0.36 MB one at 94 MB. +// Compiling the large ones strictly one at a time left the other threads idle: 40 modules (27 over 4 MiB) on 6 +// threads took 308 s exclusively and 75 s in parallel, 7.0 GB and 8.7 GB peak. kBytesPerSpirvByte keeps a margin +// over the measurement. The NVIDIA 621.24 driver (RTX 3080) took 85 to 131 bytes per SPIR-V byte for synthetic compute +// modules of 128 KiB to 4 MiB (docs/d3d12_vulkan.md, "Large pipelines"). +// +// The process grew past one module's peak even one at a time because glibc keeps freed memory in per-thread arenas +// (6 threads: 6.2 GB; MALLOC_ARENA_MAX=1: 2.1 GB, same modules). release_free_memory() hands it back after each +// large module. +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#endif +#if defined(__GLIBC__) +#include +#endif + +namespace leonida { + +inline constexpr uint64_t kBytesPerSpirvByte = 512; + +inline uint64_t large_module_estimate(uint64_t spirv_bytes) { return spirv_bytes * kBytesPerSpirvByte; } + +#if defined(__linux__) +// The first unsigned number in a file ("max" and unreadable files give no value). +inline bool read_u64_file(const std::string& path, uint64_t& value) { + std::FILE* f = std::fopen(path.c_str(), "r"); + if (!f) return false; + unsigned long long v = 0; + const bool ok = std::fscanf(f, "%llu", &v) == 1; + std::fclose(f); + value = v; + return ok; +} + +// The room left under the cgroup v2 memory.max of this process and of every cgroup above it (a container or +// systemd-run -p MemoryMax=...), or UINT64_MAX when none sets a limit. cgroup_root is a parameter for the tests. +inline uint64_t cgroup_memory_room(const std::string& self_cgroup_file = "/proc/self/cgroup", + const std::string& cgroup_root = "/sys/fs/cgroup") { + std::FILE* f = std::fopen(self_cgroup_file.c_str(), "r"); + if (!f) return UINT64_MAX; + char line[4096]; + std::string rel; + while (std::fgets(line, sizeof(line), f)) { + std::string l(line); + if (l.rfind("0::", 0) == 0) { // the cgroup v2 line + rel = l.substr(3); + while (!rel.empty() && (rel.back() == '\n' || rel.back() == '\r')) rel.pop_back(); + break; + } + } + std::fclose(f); + uint64_t room = UINT64_MAX; + for (std::string dir = rel; !dir.empty();) { + // In a cgroup namespace, "/" can be a constrained cgroup mounted as the visible root. + const std::string base = dir == "/" ? cgroup_root : cgroup_root + dir; + uint64_t max = 0, current = 0; + if (read_u64_file(base + "/memory.max", max) && read_u64_file(base + "/memory.current", current)) + room = std::min(room, max > current ? max - current : 0); + const auto slash = dir.find_last_of('/'); + if (dir == "/" || slash == std::string::npos) break; + dir.resize(slash == 0 ? 1 : slash); + } + return room; +} +#endif + +// Memory the OS could give this process now, or 0 when it can't tell (then the caller keeps the old exclusive gate). +inline uint64_t available_memory_bytes() { +#ifdef _WIN32 + MEMORYSTATUSEX status{}; + status.dwLength = sizeof(status); + return GlobalMemoryStatusEx(&status) ? uint64_t(status.ullAvailPhys) : 0; +#elif defined(__linux__) + std::FILE* f = std::fopen("/proc/meminfo", "r"); + if (!f) return 0; + char line[256]; + unsigned long long kb = 0; + bool found = false; + while (std::fgets(line, sizeof(line), f)) + if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) { found = true; break; } + std::fclose(f); + if (!found) return 0; + const uint64_t room = cgroup_memory_room(); + return std::max(1, std::min(uint64_t(kb) * 1024, room)); // 0 would mean "unknown" +#else + return 0; +#endif +} + +// What large compiles may use of the free RAM and of the room under the commit limit: three quarters of the smaller. (On +// Windows an allocation that the limit has no room for fails, whatever RAM is free.) +inline uint64_t large_compile_share(uint64_t free_ram, uint64_t commit_room) { + return std::min(free_ram, commit_room) / 4 * 3; +} + +// The same of the memory that is free at this moment. 0 when it is unknown: then they compile one at a time. +inline uint64_t large_compile_budget_bytes() { +#ifdef _WIN32 + MEMORYSTATUSEX status{}; + status.dwLength = sizeof(status); + if (!GlobalMemoryStatusEx(&status)) return 0; + return large_compile_share(status.ullAvailPhys, status.ullAvailPageFile); +#else + return large_compile_share(available_memory_bytes(), UINT64_MAX); +#endif +} + +// LEONIDA_BIG_COMPILE_BUDGET_MB: a fixed budget in MiB instead of the share of the free memory (0: one at a time). Unset +// or empty, and text that is not a number: none. `valid` is false for the latter. +struct LargeCompileBudget { + std::optional fixed{}; + bool valid = true; +}; + +inline LargeCompileBudget large_compile_budget(const char* text) { + if (!text || !*text) return {}; + uint64_t mib = 0; + for (const char* c = text; *c; ++c) { + if (*c < '0' || *c > '9') return {std::nullopt, false}; + mib = std::min(mib * 10 + uint64_t(*c - '0'), UINT64_MAX >> 20); + } + return {mib << 20, true}; +} + +// Return memory freed by the driver's compiler to the OS (glibc keeps it in the arena of the thread that freed it). +inline void release_free_memory() { +#if defined(__GLIBC__) + malloc_trim(0); +#endif +} + +// Lets large modules in while their estimates fit the budget and fewer than max_inflight are in. One always gets in +// when none is, so a module bigger than the whole budget still compiles (alone among the large ones). +// +// The second constructor is the runtime's: the budget is read again whenever a place is given or returned, and the +// modules get in in the order they came, those a submission waits for (demand) before the others (speculative). A +// speculative one gets in only while no demand waits and no submission has a Demand, and only within a quarter of the +// budget, so that a demand finds the rest free. An estimate counts in full until its module leaves, although the driver +// has allocated part of it by then and the budget is that much smaller: what is in has not taken all it is going to. +class LargeModuleGate { +public: + enum class Work { demand, speculative }; + + LargeModuleGate(uint64_t budget, unsigned max_inflight) + : budget_(budget), max_inflight_(max_inflight ? max_inflight : 1) {} + explicit LargeModuleGate(std::function budget) + : budget_(0), max_inflight_(UINT32_MAX), read_budget_(std::move(budget)) {} + + bool admits(uint64_t estimate) const { + std::lock_guard g(mu_); + return admits_locked(estimate, Work::demand); + } + void enter(uint64_t estimate, Work work = Work::demand) { + std::unique_lock l(mu_); + if (!read_budget_) { + cv_.wait(l, [&] { return admits_locked(estimate, work); }); + } else { + auto& queue = waiting_[work == Work::demand ? 0 : 1]; + const auto me = queue.insert(queue.end(), 0); + cv_.wait(l, [&] { + return queue.begin() == me && (work == Work::demand || (waiting_[0].empty() && !demanded_)) && + admits_locked(estimate, work); + }); + queue.erase(me); + } + used_ += estimate; + ++inflight_; + if (!waiting_[0].empty() || !waiting_[1].empty()) cv_.notify_all(); // the next in the queue may fit as well + } + void leave(uint64_t estimate) { + { + std::lock_guard g(mu_); + used_ -= estimate; + --inflight_; + } + cv_.notify_all(); + } + unsigned inflight() const { + std::lock_guard g(mu_); + return inflight_; + } + size_t waiting(Work work) const { // in order: the threads in enter(), with a budget that is read + std::lock_guard g(mu_); + return waiting_[work == Work::demand ? 0 : 1].size(); + } + uint64_t budget() const { return read_budget_ ? read_budget_() : budget_; } + unsigned max_inflight() const { return max_inflight_; } + + // A submission that has large modules to build: until it ends, the places that its modules leave between one and the + // next are not taken by speculative ones. + class Demand { + public: + explicit Demand(LargeModuleGate& gate) : gate_(gate) { + std::lock_guard g(gate_.mu_); + ++gate_.demanded_; + } + ~Demand() { + { + std::lock_guard g(gate_.mu_); + --gate_.demanded_; + } + gate_.cv_.notify_all(); + } + Demand(const Demand&) = delete; + Demand& operator=(const Demand&) = delete; + + private: + LargeModuleGate& gate_; + }; + + // Holds a place from construction until destruction (or release()), then hands freed memory back. + class Ticket { + public: + Ticket() = default; + Ticket(LargeModuleGate& gate, uint64_t estimate, Work work = Work::demand) : gate_(&gate), estimate_(estimate) { + gate.enter(estimate, work); + } + Ticket(Ticket&& o) noexcept : gate_(o.gate_), estimate_(o.estimate_) { o.gate_ = nullptr; } + Ticket& operator=(Ticket&& o) noexcept { + if (this != &o) { release(); gate_ = o.gate_; estimate_ = o.estimate_; o.gate_ = nullptr; } + return *this; + } + Ticket(const Ticket&) = delete; + Ticket& operator=(const Ticket&) = delete; + ~Ticket() { release(); } + void release() { + if (!gate_) return; + gate_->leave(estimate_); + gate_ = nullptr; + release_free_memory(); + } + private: + LargeModuleGate* gate_ = nullptr; + uint64_t estimate_ = 0; + }; + +private: + bool admits_locked(uint64_t estimate, Work work) const { + if (inflight_ == 0) return true; + const uint64_t limit = work == Work::demand ? budget() : budget() / 4; + return inflight_ < max_inflight_ && used_ + estimate <= limit; + } + + const uint64_t budget_; + const unsigned max_inflight_; + const std::function read_budget_; + mutable std::mutex mu_; + std::condition_variable cv_; + std::list waiting_[2]; // demand, speculative: one entry for each thread in enter(), in the order they came + uint64_t used_ = 0; + unsigned inflight_ = 0; + unsigned demanded_ = 0; // the Demands +}; + +} // namespace leonida diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index ac84df7a4d..b539fd5c09 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1570,6 +1570,14 @@ class VulkanContext { std::unique_lock lock(resource_mutex_); pipeline_workers_.swap(workers); } + // For the large pipelines of a submission: the memory they may use while they compile together + // (PipelineCompiles::build), and what is kept while they do (LargeModuleGate::Demand). None (the default): they compile + // one after another. + void set_large_compiles(std::function budget, std::function()> demand) { + std::unique_lock lock(resource_mutex_); + large_compile_budget_ = std::move(budget); + large_compile_demand_ = std::move(demand); + } PipelineWorkers::Stats pipeline_worker_stats() { std::shared_lock lock(resource_mutex_); return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{}; @@ -2186,6 +2194,8 @@ class VulkanContext { std::unordered_map pipelines_; std::unordered_map graphics_pipelines_; std::unique_ptr pipeline_workers_; + std::function large_compile_budget_; + std::function()> large_compile_demand_; std::unordered_map acceleration_structures_; LayoutTracker tracker_; std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only @@ -3122,11 +3132,15 @@ class VulkanQueue : private QueueHolds::Holder { statistics_segments += prepared[i].statistics_segment_count; has_queries = has_queries || !prepared[i].queries.empty(); } + std::shared_ptr demand; + if (context_.large_compile_demand_ && compiles.any_large()) demand = context_.large_compile_demand_(); 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); - }); + }, + context_.large_compile_budget_); + demand.reset(); if (prepare_result != ReplayResult::success) return prepare_result; const auto segment_pool = [this](VkQueryType type, std::uint32_t count, std::shared_ptr& out) { diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 5a3e569dd6..2753eb1c90 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -60,6 +60,7 @@ #include #include #include +#include #include #include #include @@ -868,8 +869,9 @@ struct ComputePipeline { // 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 large = false; // PipelineCompiles limits how many of these compile at once bool skipped = false; // never built on request (LEONIDA_SKIP_COMPUTE): its dispatches are dropped + std::uint64_t estimate = 0; // large: the bytes of memory its compile is expected to take }; // A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it @@ -903,6 +905,7 @@ struct GraphicsPipeline { std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count bool async_build = false; bool nonunit_vertex_divisor = false; // an actual instance divisor > 1, not a zero-stride emulation + std::uint64_t estimate = 0; // as ComputePipeline::estimate }; // The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base. @@ -1000,7 +1003,7 @@ class PipelineCompiles { 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`. + // pipelines of this much or more are `large`. For compute pipelines the D3D12 layer decides. static constexpr std::uint64_t large_spirv_bytes = 1u << 20; Ticket add(const GraphicsPipeline& pipeline, std::uint32_t flags) { @@ -1009,26 +1012,66 @@ class PipelineCompiles { Ticket add(const ComputePipeline& pipeline, User user) { return add({nullptr, &pipeline, 0}, user); } bool empty() const { return jobs_.empty(); } + bool any_large() const { + return std::any_of(jobs_.begin(), jobs_.end(), [](const Job& job) { return is_large(job); }); + } 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. + // Compiles all of them through run(count, job) (PipelineWorkers::run). The large ones share budget() bytes of memory: + // the largest first, as many at once as their estimates fit, one at least; while the next one does not fit, the + // others are compiled first. No budget, or 0: the large ones one after another, as without workers, beside the others. template - void build(Run&& run) { + void build(Run&& run, const std::function& read_budget = {}) { std::vector single, large; for (std::size_t i = 0; i < jobs_.size(); ++i) (is_large(jobs_[i]) ? large : single).push_back(i); + // The first jobs of the run are lanes, which take large ones until none is left: no more of them than there are + // large ones that fit the budget together (the smallest), so that no thread waits here for room in vain. + std::size_t lanes = large.empty() ? 0 : 1; + const std::uint64_t budget = lanes && read_budget ? read_budget() : 0; + if (budget) { + std::stable_sort(large.begin(), large.end(), [this](std::size_t a, std::size_t b) { + return estimate(jobs_[a]) > estimate(jobs_[b]); + }); + std::uint64_t sum = estimate(jobs_[large.back()]); + while (lanes < large.size() && (sum += estimate(jobs_[large[large.size() - 1 - lanes]])) <= budget) ++lanes; + } 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); + std::mutex mutex; // guards the four below + std::size_t next_single = 0, next_large = 0, compiling = 0; + std::uint64_t reserved = 0; // the estimates of the large ones compiling + run(lanes + single.size(), [&](std::size_t i) { + std::unique_lock lock(mutex); + if (i >= lanes) { + if (next_single == single.size()) return; // a lane has taken it + const std::size_t index = single[next_single++]; + lock.unlock(); + compile(index); + return; + } + while (next_large < large.size()) { + const std::uint64_t need = estimate(jobs_[large[next_large]]); + const bool fits = !compiling || reserved + need <= budget; + if (!fits && next_single < single.size()) { + const std::size_t index = single[next_single++]; + lock.unlock(); + compile(index); + lock.lock(); + continue; + } + const std::size_t index = large[next_large++]; + ++compiling; + reserved += need; + lock.unlock(); + compile(index); + lock.lock(); + --compiling; + reserved -= need; + } }); } @@ -1040,6 +1083,9 @@ class PipelineCompiles { VkPipeline built = VK_NULL_HANDLE; }; static bool is_large(const Job& job) { return job.graphics ? job.graphics->large : job.compute->large; } + static std::uint64_t estimate(const Job& job) { + return job.graphics ? job.graphics->estimate : job.compute->estimate; + } 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)); @@ -2944,12 +2990,12 @@ class PreparedList { // 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. +// draw or an indirect dispatch, and a dispatch is dropped as prepare() drops one. `budget`: PipelineCompiles::build. template ReplayResult build_pipelines(PipelineCompiles& compiles, std::span lists, ReplayResult result, - Run&& run) { + Run&& run, const std::function& budget = {}) { if (compiles.empty()) return result; - compiles.build(run); + compiles.build(run, budget); for (const PipelineCompiles::Use& use : compiles.uses()) { if (compiles.built(use.ticket)) continue; if (use.user == PipelineCompiles::User::draw) return unsupported_at(__LINE__); diff --git a/runtime/test/big_compile_gate_test.cpp b/runtime/test/big_compile_gate_test.cpp new file mode 100644 index 0000000000..5756f99abd --- /dev/null +++ b/runtime/test/big_compile_gate_test.cpp @@ -0,0 +1,426 @@ +// LargeModuleGate with a budget that is read (runtime/src/large_module_gate.h): who gets in, in which order and when, and +// the settings. The threads that wait for a place are real; every check that waits for one gives up after 10 s, so a +// missing wake-up fails the test and does not hang it. Fixed budgets (vk_pipeline_check's) are large_module_gate_test.cpp's. +// No Vulkan. +#include "../src/large_module_gate.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace std::chrono_literals; +using leonida::LargeModuleGate; +using Work = LargeModuleGate::Work; + +// Ends the process: the threads that the failed check left waiting would keep the rest from ending. +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); \ + std::fflush(stderr); \ + std::_Exit(1); \ + } \ +} while (0) + +bool eventually(const std::function& what) { + const auto end = std::chrono::steady_clock::now() + 10s; + while (!what()) { + if (std::chrono::steady_clock::now() > end) return false; + std::this_thread::sleep_for(1ms); + } + return true; +} + +// A thread in enter() for one estimate, which keeps its place until leave() is called. +class Entrant { +public: + Entrant(LargeModuleGate& gate, std::uint64_t estimate, Work work = Work::demand) { + thread_ = std::thread([&gate, estimate, work, this] { + LargeModuleGate::Ticket place(gate, estimate, work); + in_ = true; + std::unique_lock lock(mutex_); + go_.wait(lock, [this] { return leave_; }); + lock.unlock(); + }); + } + ~Entrant() { + if (thread_.joinable()) { + leave(); + join(); + } + } + Entrant(const Entrant&) = delete; + Entrant& operator=(const Entrant&) = delete; + bool in() const { return in_; } + void leave() { + std::lock_guard lock(mutex_); + leave_ = true; + go_.notify_all(); + } + void join() { thread_.join(); } + +private: + std::atomic in_{false}; + std::mutex mutex_; + std::condition_variable go_; + bool leave_ = false; + std::thread thread_; +}; + +bool waiting(LargeModuleGate& gate, Work work, std::size_t count) { + return eventually([&] { return gate.waiting(work) == count; }); +} +bool in(const Entrant& e) { return eventually([&] { return e.in(); }); } +// The time a wrong admission would need to happen. +bool stays_out(const Entrant& e) { + std::this_thread::sleep_for(50ms); + return !e.in(); +} + +LargeModuleGate fixed(std::uint64_t budget) { + return LargeModuleGate([budget] { return budget; }); +} + +void bound_and_one_always() { + auto gate = fixed(10); + Entrant big(gate, 25); // more than the whole budget: it compiles alone + CHECK(in(big)); + Entrant first(gate, 6), second(gate, 4); + CHECK(stays_out(first) && stays_out(second)); + big.leave(); + big.join(); + CHECK(in(first) && in(second)); // 10 fits exactly + Entrant third(gate, 1); + CHECK(waiting(gate, Work::demand, 1) && stays_out(third)); + first.leave(); + CHECK(in(third)); + CHECK(gate.inflight() == 2); + second.leave(); + third.leave(); + second.join(); + third.join(); + first.join(); + CHECK(eventually([&] { return gate.inflight() == 0; })); +} + +// Whatever the sizes, what is in fits, or is one alone; everything gets in, once. +void many_threads() { + for (const std::uint64_t budget : {0u, 1u, 10u, 40u}) { + auto gate = fixed(budget); + std::atomic used{0}; + std::atomic inside{0}, most{0}; + std::atomic over{0}, done{0}; + std::vector threads; + for (unsigned t = 0; t < 8; ++t) + threads.emplace_back([&, t] { + for (unsigned i = 0; i < 150; ++i) { + const std::uint64_t estimate = 1 + (t * 7 + i) % 13; + const LargeModuleGate::Ticket place(gate, estimate, + (t + i) % 3 ? Work::demand : Work::speculative); + const std::uint64_t sum = used += estimate; + const unsigned n = ++inside; + if (sum > budget && n > 1) ++over; + unsigned m = most; + while (n > m && !most.compare_exchange_weak(m, n)) {} + for (int spin = 0; spin < 20; ++spin) std::this_thread::yield(); + --inside; + used -= estimate; + ++done; + } + }); + for (auto& t : threads) t.join(); + CHECK(over == 0); + CHECK(done == 8 * 150); + CHECK(gate.inflight() == 0); + CHECK(budget < 40 || most > 1); // and where there is room, several are in + } +} + +// Those that wait get in in the order they came: what came later and is small does not overtake the big one before it. +void order() { + auto gate = fixed(10); + Entrant first(gate, 8); + CHECK(in(first)); + Entrant big(gate, 9); + CHECK(waiting(gate, Work::demand, 1)); + Entrant little(gate, 1); + CHECK(waiting(gate, Work::demand, 2)); + CHECK(stays_out(big)); + CHECK(stays_out(little)); // it would fit beside the first + first.leave(); + CHECK(in(big)); + CHECK(in(little)); // the place that the big one leaves free is the next one's + big.leave(); + little.leave(); +} + +// The first in the queue leaves it, and the next one, which fits as well, gets in at once and not when something leaves. +void one_admission_wakes_the_next() { + auto gate = fixed(10); + Entrant first(gate, 10); + CHECK(in(first)); + Entrant a(gate, 4), b(gate, 4), c(gate, 2); + CHECK(waiting(gate, Work::demand, 3)); + first.leave(); + CHECK(in(a) && in(b) && in(c)); + CHECK(gate.inflight() == 3); + a.leave(); + b.leave(); + c.leave(); +} + +void leaving_wakes_all_that_fit() { + auto gate = fixed(10); + Entrant a(gate, 5), b(gate, 5); + CHECK(in(a) && in(b)); + Entrant c(gate, 3), d(gate, 2); + CHECK(waiting(gate, Work::demand, 2) && stays_out(c)); + a.leave(); + CHECK(in(c) && in(d)); + b.leave(); + c.leave(); + d.leave(); +} + +// What a submission waits for goes first, whenever it came. +void demand_before_speculative() { + auto gate = fixed(10); + Entrant first(gate, 10); + CHECK(in(first)); + Entrant speculative(gate, 1, Work::speculative); + CHECK(waiting(gate, Work::speculative, 1)); + Entrant demand(gate, 9); + CHECK(waiting(gate, Work::demand, 1)); + first.leave(); + CHECK(in(demand)); // the speculative one came first and would have fitted + CHECK(stays_out(speculative)); + demand.leave(); + CHECK(in(speculative)); + speculative.leave(); +} + +// Waiting demand keeps out speculative work that fits, also the one that is first in line. +void waiting_demand_keeps_speculative_out() { + auto gate = fixed(100); + Entrant first(gate, 40, Work::demand); + CHECK(in(first)); + Entrant blocked(gate, 100); // waits for the first + CHECK(waiting(gate, Work::demand, 1)); + Entrant speculative(gate, 5, Work::speculative); // a quarter holds it + CHECK(waiting(gate, Work::speculative, 1)); + CHECK(stays_out(speculative)); + first.leave(); + CHECK(in(blocked)); + CHECK(stays_out(speculative)); + blocked.leave(); + CHECK(in(speculative)); + speculative.leave(); +} + +// While a submission has more to build, the room between two of its modules is not a speculative one's. +void a_demand_keeps_speculative_out() { + auto gate = fixed(100); + auto one = std::make_unique(gate), other = std::make_unique(gate); + Entrant speculative(gate, 10, Work::speculative); + CHECK(waiting(gate, Work::speculative, 1)); + CHECK(stays_out(speculative)); // it fits, and nothing is in + for (int i = 0; i < 2; ++i) { + Entrant built(gate, 10); + CHECK(in(built)); + built.leave(); + built.join(); + CHECK(stays_out(speculative)); // between two of the submission's modules + } + one.reset(); + CHECK(stays_out(speculative)); // another submission has some + other.reset(); + CHECK(in(speculative)); // the end of the last one wakes it + speculative.leave(); +} + +// A speculative one gets in within a quarter of the budget, and what is free of it is there for a demand. +void speculative_share() { + auto gate = fixed(100); + Entrant demand(gate, 30); + CHECK(in(demand)); + Entrant over(gate, 26, Work::speculative); // 56 of 100, but more than 25 with the rest + CHECK(waiting(gate, Work::speculative, 1)); + CHECK(stays_out(over)); + demand.leave(); + CHECK(in(over)); // alone, whatever its size + Entrant quick(gate, 70); + CHECK(in(quick)); // 96 of 100: the speculative one does not count against it + quick.leave(); + over.leave(); + quick.join(); + over.join(); + CHECK(eventually([&] { return gate.inflight() == 0; })); + Entrant share(gate, 25, Work::speculative); + CHECK(in(share)); + Entrant second(gate, 1, Work::speculative); + CHECK(waiting(gate, Work::speculative, 1)); // one more byte is past the quarter + CHECK(stays_out(second)); + Entrant next(gate, 75); + CHECK(in(next)); // the whole rest + CHECK(stays_out(second)); + next.leave(); + share.leave(); + CHECK(in(second)); + second.leave(); +} + +// Speculative ones get in in the order they came, and alone when nothing is in. +void speculative_order_and_alone() { + auto gate = fixed(0); // unknown memory: one at a time + Entrant a(gate, 5, Work::speculative); + CHECK(in(a)); + Entrant b(gate, 5, Work::speculative); + CHECK(waiting(gate, Work::speculative, 1)); + Entrant c(gate, 5, Work::demand); + CHECK(waiting(gate, Work::demand, 1)); + CHECK(stays_out(b) && stays_out(c)); + a.leave(); + CHECK(in(c)); + CHECK(stays_out(b)); + c.leave(); + CHECK(in(b)); + b.leave(); +} + +// The budget is read when a place is asked for and when one is given back, not once. +void budget_follows_the_moment() { + std::atomic free{100}; + LargeModuleGate gate([&] { return free.load(); }); + CHECK(gate.budget() == 100); + Entrant a(gate, 30), b(gate, 10); + CHECK(in(a) && in(b)); + free = 35; + Entrant c(gate, 20); // 60 of 100 a moment ago + CHECK(waiting(gate, Work::demand, 1)); + CHECK(stays_out(c)); + free = 100; + b.leave(); + CHECK(in(c)); // 50 of 100 now; it would not be within 35 + CHECK(gate.inflight() == 2); + a.leave(); + c.leave(); + a.join(); + c.join(); + // A budget that shrinks while a module is in does not throw it out, and holds the next. + Entrant d(gate, 100); + CHECK(in(d)); + free = 1; + Entrant e(gate, 1); + CHECK(waiting(gate, Work::demand, 1)); + CHECK(stays_out(e)); + CHECK(gate.inflight() == 1); + d.leave(); + CHECK(in(e)); +} + +// An estimate counts for as long as its module is in, whatever the driver has taken of it already. +void estimates_stay_reserved() { + auto gate = fixed(100); // the driver has taken nothing yet: the memory is all there + Entrant a(gate, 60); + CHECK(in(a)); + Entrant b(gate, 60); + CHECK(waiting(gate, Work::demand, 1)); + CHECK(stays_out(b)); + a.leave(); + CHECK(in(b)); + b.leave(); +} + +// A ticket gives its place back once, however it ends. +void tickets() { + auto gate = fixed(10); + { + LargeModuleGate::Ticket a(gate, 6, Work::speculative); + LargeModuleGate::Ticket moved = std::move(a); + CHECK(gate.inflight() == 1); + LargeModuleGate::Ticket b; + b = LargeModuleGate::Ticket(gate, 3); + CHECK(gate.inflight() == 2); + b.release(); + b.release(); + CHECK(gate.inflight() == 1); + } + CHECK(gate.inflight() == 0); +} + +// The memory budget's setting: what it says, and nothing else. +void settings() { + using leonida::large_compile_budget; + const auto check = [](const char* text, bool valid, bool has, std::uint64_t mib) { + const auto s = large_compile_budget(text); + CHECK(s.valid == valid); + CHECK(s.fixed.has_value() == has); + if (has) CHECK(*s.fixed == mib << 20); + }; + check(nullptr, true, false, 0); + check("", true, false, 0); + check("0", true, true, 0); + check("1", true, true, 1); + check("512", true, true, 512); + check("0512", true, true, 512); + check("12a", false, false, 0); + check(" 5", false, false, 0); + check("-1", false, false, 0); + check("1.5", false, false, 0); + check("99999999999999999999999", true, true, UINT64_MAX >> 20); // saturates: no limit, not a small number + CHECK(*large_compile_budget("99999999999999999999999").fixed >= (UINT64_MAX >> 20) << 20); +} + +// The share of the memory, and what the machine gives now: nothing unknown on Windows and Linux, and no more than three +// quarters of either limit. +void machine() { + using leonida::large_compile_share; + CHECK(large_compile_share(1000, 4000) == 750); + CHECK(large_compile_share(4000, 1000) == 750); // the commit limit has less room than the RAM + CHECK(large_compile_share(0, 4000) == 0); + const std::uint64_t budget = leonida::large_compile_budget_bytes(); +#if defined(_WIN32) || defined(__linux__) + CHECK(budget > 0); +#endif + // Read a moment apart on a running machine: the budget may not exceed either limit by more than that moment. + const std::uint64_t slack = std::uint64_t(256) << 20; + CHECK(budget <= leonida::available_memory_bytes() / 4 * 3 + slack); + CHECK(leonida::large_module_estimate(1 << 20) == (std::uint64_t(1) << 20) * leonida::kBytesPerSpirvByte); +#ifdef _WIN32 + MEMORYSTATUSEX status{}; + status.dwLength = sizeof(status); + CHECK(GlobalMemoryStatusEx(&status) != 0); + CHECK(budget <= status.ullAvailPageFile / 4 * 3 + slack); +#endif +} + +} // namespace + +int main() { + bound_and_one_always(); + many_threads(); + order(); + one_admission_wakes_the_next(); + leaving_wakes_all_that_fit(); + demand_before_speculative(); + waiting_demand_keeps_speculative_out(); + a_demand_keeps_speculative_out(); + speculative_share(); + speculative_order_and_alone(); + budget_follows_the_moment(); + estimates_stay_reserved(); + tickets(); + settings(); + machine(); + std::puts("big_compile_gate: ok"); + return 0; +} diff --git a/runtime/test/big_compute_module.h b/runtime/test/big_compute_module.h new file mode 100644 index 0000000000..28dde996f9 --- /dev/null +++ b/runtime/test/big_compute_module.h @@ -0,0 +1,298 @@ +// Large compute modules that are work for a driver's compiler, not padding: a register file in a Function array that every +// instruction loads from and stores to (as the translator's modules have it), integer instructions, selections, nested +// conditionals and loops, and loads from memory the compiler knows nothing about. The same instructions run on the CPU, so +// the value that a dispatch stores is known. Made from a seed; no game data. +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace bigmodule { + +using Words = std::vector; + +inline 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()); +} + +enum class Kind : std::uint8_t { add, sub, mul, xor_, and_, or_, shl, shr, select, load, if_, end_if, loop, end_loop }; + +struct Instruction { + Kind kind; + std::uint8_t d = 0, a = 0, b = 0, c = 0; // registers; c is a shift count or a loop count for those kinds +}; + +constexpr unsigned kRegisters = 48, kConstants = 64, kDepth = 3; +constexpr unsigned kLoadBase = 256, kLoadWords = 64; // the words of the buffer the loads read (the CPU takes them as 0) + +struct Program { + std::vector code; + std::uint32_t constants[kConstants]; + + // What the module stores for the dispatch with this root constant. + std::uint32_t run(std::uint32_t root_constant) const { + std::uint32_t v[kRegisters]; + for (unsigned i = 0; i < kRegisters; ++i) v[i] = constants[i % kConstants] ^ (root_constant + i); + walk(0, v); + std::uint32_t out = 0; + for (unsigned i = 0; i < kRegisters; ++i) out ^= v[i]; + return out; + } + +private: + // Runs from `at` to the end marker of its block and returns the index after it. + std::size_t walk(std::size_t at, std::uint32_t* v) const { + for (; at < code.size();) { + const Instruction& i = code[at]; + const std::uint32_t k = constants[i.c % kConstants]; + switch (i.kind) { + case Kind::add: v[i.d] = v[i.a] + v[i.b] + k; break; + case Kind::sub: v[i.d] = v[i.a] - v[i.b] - k; break; + case Kind::mul: v[i.d] = v[i.a] * v[i.b] * k; break; + case Kind::xor_: v[i.d] = v[i.a] ^ v[i.b] ^ k; break; + case Kind::and_: v[i.d] = v[i.a] & (v[i.b] | k); break; + case Kind::or_: v[i.d] = v[i.a] | (v[i.b] & k); break; + case Kind::shl: v[i.d] = (v[i.a] << (i.c & 31)) ^ v[i.b]; break; + case Kind::shr: v[i.d] = (v[i.a] >> (i.c & 31)) ^ v[i.b]; break; + case Kind::select: v[i.d] = v[i.a] < v[i.b] ? v[i.c % kRegisters] : v[i.a]; break; + case Kind::load: v[i.d] = v[i.b]; break; // + the loaded word, which is 0 + case Kind::if_: { + std::size_t after = at + 1; + if (v[i.a] < v[i.b]) + after = walk(at + 1, v); + else + after = skip(at + 1); + at = after; + continue; + } + case Kind::loop: { + std::size_t after = at + 1; + for (unsigned n = 0; n < i.c; ++n) after = walk(at + 1, v); + at = after; + continue; + } + case Kind::end_if: + case Kind::end_loop: return at + 1; + } + ++at; + } + return at; + } + std::size_t skip(std::size_t at) const { + for (int depth = 1; at < code.size(); ++at) { + const Kind k = code[at].kind; + if (k == Kind::if_ || k == Kind::loop) ++depth; + if ((k == Kind::end_if || k == Kind::end_loop) && !--depth) return at + 1; + } + return at; + } +}; + +// A module of about `bytes` bytes of SPIR-V (a few KiB more), and the program it runs. `seed` decides everything. It has the +// translator's push-constant block: s[4]:s[5] is the console VA of a root UAV, s[6] a root constant. A dispatch stores +// Program::run(s[6]) at the UAV's word s[6], and reads its words kLoadBase to kLoadBase + kLoadWords - 1, which have to +// be 0. +inline Words make(std::size_t bytes, std::uint64_t seed, Program* out = nullptr) { + std::mt19937_64 random(seed); + Program program; + for (auto& c : program.constants) c = std::uint32_t(random()); + // Ids. + enum : std::uint32_t { + id_void = 1, id_fn, id_main, id_uint, id_ulong, id_bool, id_block, id_sarr, id_c32, id_ptr_push_block, + id_push, id_ptr_push_uint, id_ptr_push_ulong, id_data, id_ptr_data, id_ptr_phys_uint, id_regs, id_cregs, + id_ptr_regs, id_ptr_fn_uint, id_vregs, id_entry, id_c64_32, id_c64_2, id_mask, id_base, + id_index0 = 40, // uint constants 0..127 + id_const0 = id_index0 + 128, // the program's constants + id_counter0 = id_const0 + kConstants, // loop counters by depth + id_first = id_counter0 + kDepth + 1, + }; + std::uint32_t next = id_first; + Words w = {0x07230203u, 0x00010500u, 0u, 0u, 0u}; + op(w, 17, {1}); // Shader + op(w, 17, {11}); // Int64 + op(w, 17, {5347}); // PhysicalStorageBufferAddresses + op(w, 14, {5348, 1}); + op(w, 15, {5, id_main, 0x6e69616du, 0u, id_push}); + op(w, 16, {id_main, 17, 1, 1, 1}); + op(w, 71, {id_sarr, 6, 4}); + op(w, 71, {id_block, 2}); + op(w, 72, {id_block, 0, 35, 0}); + op(w, 72, {id_block, 1, 35, 128}); + op(w, 72, {id_block, 2, 35, 136}); + op(w, 71, {id_data, 2}); + op(w, 72, {id_data, 0, 35, 0}); + op(w, 19, {id_void}); + op(w, 33, {id_fn, id_void}); + op(w, 21, {id_uint, 32, 0}); + op(w, 21, {id_ulong, 64, 0}); + op(w, 20, {id_bool}); + op(w, 43, {id_uint, id_c32, 32}); + op(w, 28, {id_sarr, id_uint, id_c32}); + op(w, 30, {id_block, id_sarr, id_ulong, id_ulong}); + op(w, 32, {id_ptr_push_block, 9, id_block}); + op(w, 59, {id_ptr_push_block, id_push, 9}); + op(w, 32, {id_ptr_push_uint, 9, id_uint}); + op(w, 32, {id_ptr_push_ulong, 9, id_ulong}); + op(w, 30, {id_data, id_uint}); + op(w, 32, {id_ptr_data, 5349, id_data}); + op(w, 32, {id_ptr_phys_uint, 5349, id_uint}); + op(w, 43, {id_uint, id_cregs, kRegisters}); + op(w, 28, {id_regs, id_uint, id_cregs}); + op(w, 32, {id_ptr_regs, 7, id_regs}); + op(w, 32, {id_ptr_fn_uint, 7, id_uint}); + op(w, 43, {id_ulong, id_c64_32, 32, 0}); + op(w, 43, {id_ulong, id_c64_2, 2, 0}); + op(w, 43, {id_uint, id_mask, kLoadWords - 1}); + op(w, 43, {id_uint, id_base, kLoadBase}); + for (std::uint32_t i = 0; i < 128; ++i) op(w, 43, {id_uint, id_index0 + i, i}); + for (std::uint32_t i = 0; i < kConstants; ++i) op(w, 43, {id_uint, id_const0 + i, program.constants[i]}); + op(w, 54, {id_void, id_main, 0, id_fn}); + op(w, 248, {id_entry}); + op(w, 59, {id_ptr_regs, id_vregs, 7}); + for (std::uint32_t i = 0; i <= kDepth; ++i) op(w, 59, {id_ptr_fn_uint, id_counter0 + i, 7}); + const auto unary = [&](std::uint16_t code, std::uint32_t type, std::uint32_t a) { + op(w, code, {type, next, a}); + return next++; + }; + const auto binary = [&](std::uint16_t code, std::uint32_t type, std::uint32_t a, std::uint32_t b) { + op(w, code, {type, next, a, b}); + return next++; + }; + const auto push_word = [&](std::uint32_t index) { + op(w, 65, {id_ptr_push_uint, next, id_push, id_index0, id_index0 + index}); + return unary(61, id_uint, next++); + }; + const std::uint32_t lo = push_word(4), hi = push_word(5); + op(w, 65, {id_ptr_push_ulong, next, id_push, id_index0 + 1}); + const std::uint32_t heap = unary(61, id_ulong, next++); + const std::uint32_t lo64 = unary(113, id_ulong, lo), hi64 = unary(113, id_ulong, hi); + const std::uint32_t high = binary(196, id_ulong, hi64, id_c64_32); + const std::uint32_t va = binary(197, id_ulong, high, lo64); + const std::uint32_t base = binary(128, id_ulong, va, heap); + const std::uint32_t root = push_word(6); + const auto slot = [&](std::uint32_t r) { + op(w, 65, {id_ptr_fn_uint, next, id_vregs, id_index0 + r}); + return next++; + }; + const auto load_reg = [&](std::uint32_t r) { return unary(61, id_uint, slot(r)); }; + const auto store_reg = [&](std::uint32_t r, std::uint32_t value) { + const std::uint32_t p = slot(r); + op(w, 62, {p, value}); + }; + for (std::uint32_t i = 0; i < kRegisters; ++i) { + const std::uint32_t seeded = binary(128, id_uint, root, id_index0 + i); + store_reg(i, binary(198, id_uint, id_const0 + i % kConstants, seeded)); + } + struct Open { + Kind kind; + std::uint32_t merge, header, cont, counter; + unsigned left; + }; + std::vector open; + unsigned loops = 0; + const auto pick = [&](std::uint32_t n) { return std::uint8_t(random() % n); }; + const auto close = [&] { + const Open o = open.back(); + open.pop_back(); + if (o.kind == Kind::if_) { + op(w, 249, {o.merge}); + op(w, 248, {o.merge}); + program.code.push_back({Kind::end_if}); + } else { + op(w, 249, {o.cont}); + op(w, 248, {o.cont}); + const std::uint32_t n = unary(61, id_uint, o.counter); + op(w, 62, {o.counter, binary(128, id_uint, n, id_index0 + 1)}); + op(w, 249, {o.header}); + op(w, 248, {o.merge}); + program.code.push_back({Kind::end_loop}); + --loops; + } + }; + while (w.size() * 4 + 256 < bytes) { + const std::uint32_t roll = std::uint32_t(random() % 100); + if (roll < 4 && open.size() < kDepth) { + const std::uint8_t a = pick(kRegisters), b = pick(kRegisters); + const std::uint32_t condition = binary(176, id_bool, load_reg(a), load_reg(b)); // ULessThan + const std::uint32_t then = next++, merge = next++; + op(w, 247, {merge, 0}); + op(w, 250, {condition, then, merge}); + op(w, 248, {then}); + open.push_back({Kind::if_, merge, 0, 0, 0, 10 + unsigned(random() % 30)}); + program.code.push_back({Kind::if_, 0, a, b, 0}); + } else if (roll < 5 && open.size() < kDepth && loops < 1) { + const std::uint8_t count = std::uint8_t(2 + random() % 3); + const std::uint32_t counter = id_counter0 + loops++; + op(w, 62, {counter, id_index0}); + const std::uint32_t header = next++, check = next++, body = next++, cont = next++, merge = next++; + op(w, 249, {header}); + op(w, 248, {header}); + op(w, 246, {merge, cont, 0}); + op(w, 249, {check}); + op(w, 248, {check}); + const std::uint32_t n = unary(61, id_uint, counter); + const std::uint32_t more = binary(176, id_bool, n, id_index0 + count); + op(w, 250, {more, body, merge}); + op(w, 248, {body}); + open.push_back({Kind::loop, merge, header, cont, counter, 20 + unsigned(random() % 20)}); + program.code.push_back({Kind::loop, 0, 0, 0, count}); + } else { + Instruction i{Kind(random() % 10), pick(kRegisters), pick(kRegisters), pick(kRegisters), pick(kConstants)}; + if (i.kind == Kind::load && random() % 2) i.kind = Kind::add; + const std::uint32_t k = id_const0 + i.c % kConstants; + std::uint32_t value = 0; + const std::uint32_t a = load_reg(i.a), b = load_reg(i.b); + switch (i.kind) { + case Kind::add: value = binary(128, id_uint, binary(128, id_uint, a, b), k); break; + case Kind::sub: value = binary(130, id_uint, binary(130, id_uint, a, b), k); break; + case Kind::mul: value = binary(132, id_uint, binary(132, id_uint, a, b), k); break; + case Kind::xor_: value = binary(198, id_uint, binary(198, id_uint, a, b), k); break; + case Kind::and_: value = binary(199, id_uint, a, binary(197, id_uint, b, k)); break; + case Kind::or_: value = binary(197, id_uint, a, binary(199, id_uint, b, k)); break; + case Kind::shl: value = binary(198, id_uint, binary(196, id_uint, a, id_index0 + (i.c & 31)), b); break; + case Kind::shr: value = binary(198, id_uint, binary(194, id_uint, a, id_index0 + (i.c & 31)), b); break; + case Kind::select: { + const std::uint32_t c = load_reg(i.c % kRegisters); + const std::uint32_t less = binary(176, id_bool, a, b); + op(w, 169, {id_uint, next, less, c, a}); + value = next++; + break; + } + default: { // load + const std::uint32_t index = binary(128, id_uint, binary(199, id_uint, a, id_mask), id_base); + const std::uint32_t offset = binary(196, id_ulong, unary(113, id_ulong, index), id_c64_2); + const std::uint32_t address = binary(128, id_ulong, base, offset); + const std::uint32_t data = unary(120, id_ptr_data, address); + op(w, 65, {id_ptr_phys_uint, next, data, id_index0}); + const std::uint32_t pointer = next++; + op(w, 61, {id_uint, next, pointer, 2, 4}); + const std::uint32_t loaded = next++; + value = binary(128, id_uint, b, loaded); + break; + } + } + store_reg(i.d, value); + program.code.push_back(i); + } + if (!open.empty() && !open.back().left--) close(); + } + while (!open.empty()) close(); + std::uint32_t result = load_reg(0); + for (std::uint32_t i = 1; i < kRegisters; ++i) result = binary(198, id_uint, result, load_reg(i)); + const std::uint32_t out_offset = binary(196, id_ulong, unary(113, id_ulong, root), id_c64_2); + const std::uint32_t out_data = unary(120, id_ptr_data, binary(128, id_ulong, base, out_offset)); + op(w, 65, {id_ptr_phys_uint, next, out_data, id_index0}); + op(w, 62, {next++, result, 2, 4}); + op(w, 253, {}); + op(w, 56, {}); + w[3] = next; + if (out) *out = std::move(program); + return w; +} + +} // namespace bigmodule diff --git a/runtime/test/d3d12_big_compute_test.cpp b/runtime/test/d3d12_big_compute_test.cpp new file mode 100644 index 0000000000..d660fab8b5 --- /dev/null +++ b/runtime/test/d3d12_big_compute_test.cpp @@ -0,0 +1,1007 @@ +// Large pipelines that a submission compiles (LEONIDA_SERIAL_BIG_COMPILES, LEONIDA_BIG_COMPILE_BUDGET_MB), through the D3D12 +// layer on a GPU: real compute modules of more than 128 KiB (big_compute_module.h), small ones, and graphics pipelines of more than +// 1 MiB. Both settings are read once for each process, so the test runs once for each: with a fixed budget, one that holds +// nothing, the one read from the machine, one at a time and without a limit. Every run +// - stores what the CPU computes for each dispatch, and draws the graphics pipelines' cells; +// - compiles as many large ones at once as the setting allows and no more, and the small ones meanwhile; +// - gives a pipeline the driver refuses the result it has always had, and its place to the next; +// - compiles each pipeline once when two queues need the same ones; +// - ends when the device's last references go while its workers compile and wait for memory. +// `warmup`: a submission's compiles go before those of the warm-up thread, which waits without holding a pipeline state. +// `eager`: pipeline states compiled when they are created (LEONIDA_LAZY_COMPUTE=0), by several threads, keep the budget too. +// The calls that create pipelines 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 "big_compute_module.h" +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "test_temp_dir.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_pipeline_compile.h" +#include "../src/large_module_gate.h" +#include "../src/shader_library.h" + +#include +#include +#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 bigmodule::Words; +using bigmodule::op; + +constexpr unsigned kBig = 6, kSmall = 4, kCompute = kBig + kSmall, kGraphics = 2; +constexpr std::size_t kBigBytes = 132 * 1024, kSmallBytes = 12 * 1024; +constexpr unsigned kExtent = 4; // the render target; each graphics pipeline draws one 2x2 cell +constexpr unsigned kWords = bigmodule::kLoadBase + bigmodule::kLoadWords; + +#define CHECK(expr) \ + do { \ + if (!(expr)) { \ + std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #expr); \ + return false; \ + } \ + } while (0) + +// ---- What the settings of this process say. ---- + +std::string setting(const char* name) { + char text[64]{}; + std::size_t length = 0; + return getenv_s(&length, text, name) == 0 && length > 1 ? text : ""; +} +const bool serial = setting("LEONIDA_SERIAL_BIG_COMPILES") == "1"; +const bool unlimited = setting("LEONIDA_SERIAL_BIG_COMPILES") == "0"; +const bool budgeted = !serial && !unlimited; +const auto fixed_budget = leonida::large_compile_budget(setting("LEONIDA_BIG_COMPILE_BUDGET_MB").c_str()).fixed; + +// ---- The driver's pipeline calls, watched. ---- + +struct Start { + std::thread::id thread; + int program = -1; // compute: the index of its module + bool large = false; +}; + +struct Hooks { + std::mutex mutex; + std::condition_variable changed; + std::map programs; // the hash of a compute module's words: its index + std::map> modules; // bytes, program + bool closed = false; // large creations wait while it is + std::chrono::milliseconds linger{0}; // and each takes at least this long, as does what follows it on its thread + std::vector started; + int large_in = 0, most_large = 0, small_done = 0, large_compute_in = 0, most_large_compute = 0; + std::uint64_t reserved = 0; // the estimates of the large ones in the driver + int over = 0; // how often several were in past the budget, or two where one is allowed + int fail_large = -1; // the large compute create (counted from 0) the driver refuses + int large_compute = 0; + bool track = false; // threads that create a pipeline are counted until they end + int live = 0, in_flight = 0, cache_reads = 0; + bool cache_read_during_create = false, cache_read_with_workers = false; + + void reset() { + std::lock_guard lock(mutex); + closed = track = cache_read_during_create = cache_read_with_workers = false; + started.clear(); + most_large = small_done = most_large_compute = over = large_compute = cache_reads = 0; + fail_large = -1; + linger = 0ms; + } + void open() { + std::lock_guard lock(mutex); + closed = false; + changed.notify_all(); + } + template + bool wait(Until&& until) { + std::unique_lock lock(mutex); + return changed.wait_for(lock, 20s, until); + } + bool wait_large(int count) { + return wait([&] { return large_in >= count; }); + } + std::size_t creates() { + std::lock_guard lock(mutex); + return started.size(); + } + std::size_t large_creates() { + std::lock_guard lock(mutex); + return std::size_t(std::count_if(started.begin(), started.end(), [](const Start& s) { return s.large; })); + } +} 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_vkCreateShaderModule real_create_module = nullptr; +PFN_vkDestroyShaderModule real_destroy_module = nullptr; +PFN_vkCreateGraphicsPipelines real_create_graphics = nullptr; +PFN_vkCreateComputePipelines real_create_compute = nullptr; +PFN_vkGetPipelineCacheData real_cache_data = nullptr; + +std::uint64_t hash(const std::uint32_t* words, std::size_t count) { + std::uint64_t h = 0xcbf29ce484222325u; + for (std::size_t i = 0; i < count; ++i) h = (h ^ words[i]) * 0x100000001b3u; + return h; +} + +struct Creation { + bool large = false, compute = false, refused = false; + std::uint64_t estimate = 0; +}; + +Creation enter_create(bool compute, std::initializer_list modules) { + std::unique_lock lock(hooks.mutex); + Creation c; + c.compute = compute; + std::size_t bytes = 0; + Start start{std::this_thread::get_id(), -1, false}; + for (const VkShaderModule module : modules) { + const auto found = hooks.modules.find(module); + if (found == hooks.modules.end()) continue; + bytes += found->second.first; + if (compute) start.program = found->second.second; + } + c.large = start.large = bytes > (compute ? 128 * 1024 : leonida::PipelineCompiles::large_spirv_bytes - 1); + c.estimate = leonida::large_module_estimate(bytes); + ++hooks.in_flight; + hooks.started.push_back(start); + if (hooks.track && !tracked.on) { + tracked.on = true; + ++hooks.live; + } + if (c.large) { + ++hooks.large_in; + if (compute) ++hooks.large_compute_in; + hooks.most_large = std::max(hooks.most_large, hooks.large_in); + hooks.most_large_compute = std::max(hooks.most_large_compute, hooks.large_compute_in); + hooks.reserved += c.estimate; + // One large compute module at a time; with a budget, several only within it. + if (serial && hooks.large_compute_in > 1) ++hooks.over; + if (budgeted && fixed_budget && hooks.large_in > 1 && hooks.reserved > *fixed_budget) ++hooks.over; + if (compute && hooks.large_compute++ == hooks.fail_large) c.refused = true; + } + hooks.changed.notify_all(); + if (c.large) hooks.changed.wait(lock, [] { return !hooks.closed; }); + const auto linger = hooks.linger; + lock.unlock(); + if (c.large && linger > 0ms) std::this_thread::sleep_for(linger); + return c; +} + +void leave_create(const Creation& c) { + std::lock_guard lock(hooks.mutex); + --hooks.in_flight; + if (c.large) { + --hooks.large_in; + if (c.compute) --hooks.large_compute_in; + hooks.reserved -= c.estimate; + } else { + ++hooks.small_done; + } + hooks.changed.notify_all(); +} + +VKAPI_ATTR VkResult VKAPI_CALL create_module(VkDevice device, const VkShaderModuleCreateInfo* info, + const VkAllocationCallbacks* allocator, VkShaderModule* out) { + const VkResult result = real_create_module(device, info, allocator, out); + if (result == VK_SUCCESS) { + std::lock_guard lock(hooks.mutex); + const auto found = hooks.programs.find(hash(info->pCode, info->codeSize / 4)); + hooks.modules[*out] = {info->codeSize, found == hooks.programs.end() ? -1 : found->second}; + } + return result; +} + +// Called between the place a compile gives back and the next one its thread asks for: with a linger, time for another +// thread to take that place. +VKAPI_ATTR void VKAPI_CALL destroy_module(VkDevice device, VkShaderModule module, const VkAllocationCallbacks* allocator) { + std::chrono::milliseconds linger; + { + std::lock_guard lock(hooks.mutex); + linger = hooks.linger; + } + if (linger > 0ms) std::this_thread::sleep_for(linger); + real_destroy_module(device, module, allocator); +} + +VKAPI_ATTR VkResult VKAPI_CALL create_graphics(VkDevice device, VkPipelineCache cache, std::uint32_t count, + const VkGraphicsPipelineCreateInfo* infos, + const VkAllocationCallbacks* allocator, VkPipeline* out) { + VkShaderModule modules[2]{}; + for (std::uint32_t i = 0; i < std::min(infos->stageCount, 2u); ++i) modules[i] = infos->pStages[i].module; + const Creation c = enter_create(false, {modules[0], modules[1]}); + const VkResult result = real_create_graphics(device, cache, count, infos, allocator, out); + leave_create(c); + 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) { + const Creation c = enter_create(true, {infos->stage.module}); + const VkResult result = c.refused ? VK_ERROR_UNKNOWN + : real_create_compute(device, cache, count, infos, allocator, out); + leave_create(c); + 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; + const auto watch = [&](const char* which, auto& kept, auto* mine) -> PFN_vkVoidFunction { + if (std::strcmp(name, which)) return nullptr; + kept = reinterpret_cast>(real); + return reinterpret_cast(mine); + }; + if (const auto f = watch("vkCreateShaderModule", real_create_module, create_module)) return f; + if (const auto f = watch("vkDestroyShaderModule", real_destroy_module, destroy_module)) return f; + if (const auto f = watch("vkCreateGraphicsPipelines", real_create_graphics, create_graphics)) return f; + if (const auto f = watch("vkCreateComputePipelines", real_create_compute, create_compute)) return f; + if (const auto f = watch("vkGetPipelineCacheData", real_cache_data, cache_data)) return f; + 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. ---- + +std::uint32_t bits(float f) { return std::bit_cast(f); } + +// 1.25 MiB of OpString, which compile to nothing: a graphics pipeline that is large. +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; + 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}); // Capability Shader + op(w, 14, {0, 1}); // MemoryModel Logical GLSL450 + op(w, 15, {0, 4, 0x6e69616du, 0u, 10, 11}); // EntryPoint Vertex "main" + op(w, 71, {10, 11, 0}); // BuiltIn Position + op(w, 71, {11, 11, 42}); // BuiltIn VertexIndex + op(w, 19, {1}); + op(w, 33, {2, 1}); + op(w, 22, {3, 32}); + op(w, 23, {6, 3, 4}); + op(w, 21, {15, 32, 1}); + op(w, 32, {7, 3, 6}); + op(w, 32, {8, 1, 15}); + op(w, 59, {7, 10, 3}); + op(w, 59, {8, 11, 1}); + op(w, 43, {15, 24, 1}); + op(w, 43, {15, 25, 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}); + op(w, 248, {30}); + op(w, 61, {15, 31, 11}); + op(w, 196, {15, 32, 31, 24}); // index << 1 + op(w, 199, {15, 33, 32, 25}); // & 2 + op(w, 199, {15, 34, 31, 25}); // index & 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}); + op(w, 129, {3, 40, 38, 27}); + op(w, 80, {6, 41, 39, 40, 28, 29}); + op(w, 62, {10, 41}); + op(w, 253, {}); + op(w, 56, {}); + return w; +} + +// The colour (n / 255, 1 - n / 255, 0, 1). +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, 9}); // EntryPoint Fragment "main" + op(w, 16, {4, 7}); // OriginUpperLeft + pad(w, 30); + op(w, 71, {9, 30, 0}); // 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, {10, 3, 6}); + op(w, 59, {10, 9, 3}); + op(w, 43, {3, 20, bits(float(n) / 255.0f)}); + op(w, 43, {3, 21, bits(float(255 - n) / 255.0f)}); + op(w, 43, {3, 22, bits(0.0f)}); + op(w, 43, {3, 23, bits(1.0f)}); + op(w, 44, {6, 24, 20, 21, 22, 23}); + op(w, 54, {1, 4, 0, 2}); + op(w, 248, {11}); + op(w, 62, {9, 24}); + op(w, 253, {}); + op(w, 56, {}); + return w; +} + +std::vector program(unsigned stage, unsigned n) { + return d3d12test::fssm_program({0x42434f00u + stage, n, 0xbf810000u}); +} + +std::vector programs(kCompute); // what each compute module runs +std::vector module_bytes(kCompute); + +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) { + 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); + // Every large one a little larger than the one before, so that the order by size is known. + const Words words = bigmodule::make(n < kBig ? kBigBytes + n * 1024 : kSmallBytes, 20251125 + n, &programs[n]); + module_bytes[n] = words.size() * 4; + CHECK((module_bytes[n] > 128 * 1024) == (n < kBig)); + hooks.programs[hash(words.data(), words.size())] = int(n); + CHECK(write(name, words)); + 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 runs. ---- + +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 compute, graphics; + ~Pipelines() { release(); } + void release() { + for (auto* s : compute) + if (s) s->Release(); + for (auto* s : graphics) s->Release(); + compute.clear(); + graphics.clear(); + } + + static ID3D12PipelineState* compute_state(ID3D12Device* dev, ID3D12RootSignature* root, unsigned n) { + const auto cs = d3d12test::shader_container(program(2, n)); + D3D12_COMPUTE_PIPELINE_STATE_DESC pd{}; + pd.pRootSignature = root; + pd.CS = {cs.data(), cs.size()}; + ID3D12PipelineState* state = nullptr; + return SUCCEEDED(dev->CreateComputePipelineState(&pd, IID_PPV_ARGS(&state))) ? state : nullptr; + } + + // The compute states on `threads` threads. + bool create(ID3D12Device* dev, unsigned threads = 1) { + 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)))); + compute.assign(kCompute, nullptr); + std::vector creating; + for (unsigned t = 1; t < threads; ++t) + creating.emplace_back([&, t] { + for (unsigned n = t; n < kCompute; n += threads) compute[n] = compute_state(dev, root.p, n); + }); + for (unsigned n = 0; n < kCompute; n += threads) compute[n] = compute_state(dev, root.p, n); + for (auto& t : creating) t.join(); + CHECK(std::find(compute.begin(), compute.end(), nullptr) == compute.end()); + const auto vs = d3d12test::shader_container(program(0, 0)); + for (unsigned n = 0; n < kGraphics; ++n) { + const auto ps = d3d12test::shader_container(program(1, n)); + D3D12_GRAPHICS_PIPELINE_STATE_DESC pd{}; + pd.pRootSignature = root.p; + 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 = 1; + pd.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + pd.SampleDesc = {1, 0}; + ID3D12PipelineState* state = nullptr; + CHECK(SUCCEEDED(dev->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&state)))); + graphics.push_back(state); + } + return true; + } +}; + +// A queue and a list that dispatches `compute` (and draws the graphics pipelines), then copies what they wrote back. +struct Frame { + std::vector compute; + bool graphics = false; + Ref target, buffer, readback; + Ref rtvs; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + UINT64 fence_value = 0; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT foot{}; + + bool create(ID3D12Device* dev, const Pipelines& p, std::vector dispatched, bool draws) { + compute = std::move(dispatched); + graphics = draws; + 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 * kWords, 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); + CHECK(image_bytes <= 4096); + const auto rd = d3d12test::buffer_desc(4096 + 4 * kWords); + 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)))); + CHECK(SUCCEEDED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + const FLOAT clear[4] = {0, 0, 0, 0}; + list->ClearRenderTargetView(rtv, clear, 0, nullptr); + list->SetComputeRootSignature(p.root.p); + list->SetComputeRootUnorderedAccessView(0, buffer->GetGPUVirtualAddress()); + for (const unsigned n : compute) { + list->SetPipelineState(p.compute[n]); + list->SetComputeRoot32BitConstant(1, n, 0); + list->Dispatch(1, 1, 1); + } + if (graphics) { + list->SetGraphicsRootSignature(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); + for (unsigned n = 0; n < kGraphics; ++n) { + const D3D12_RECT cell{LONG(2 * n), 0, LONG(2 * n + 2), 2}; + list->RSSetScissorRects(1, &cell); + list->SetPipelineState(p.graphics[n]); + list->DrawInstanced(3, 1, 0, 0); + } + } + 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 * kWords); + const D3D12_RESOURCE_BARRIER back_again[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_again); + CHECK(SUCCEEDED(list->Close())); + return true; + } + + ReplayResult submit() { + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + const ReplayResult result = rt::d3d12::last_execute_result(queue.p); + queue->Signal(fence.p, ++fence_value); + fence->SetEventOnCompletion(fence_value, nullptr); + return result; + } + + // What the shaders stored and drew; `dropped` is the compute program that was not built, whose word stays 0. The + // readback buffer is cleared, so stale bytes cannot pass. + bool right(int dropped = -1) { + void* mapped = nullptr; + CHECK(SUCCEEDED(readback->Map(0, nullptr, &mapped)) && mapped); + auto* bytes = static_cast(mapped); + bool ok = true; + std::uint32_t words[kWords]; + std::memcpy(words, bytes + 4096, sizeof words); + for (const unsigned n : compute) { + const std::uint32_t want = int(n) == dropped ? 0 : programs[n].run(n); + if (words[n] != want) { + std::fprintf(stderr, "compute program %u stored 0x%08x, not 0x%08x\n", n, words[n], want); + ok = false; + } + } + for (unsigned n = 0; graphics && n < kGraphics; ++n) + for (unsigned y = 0; y < 2; ++y) + for (unsigned x = 2 * n; x < 2 * n + 2; ++x) { + const auto* pixel = bytes + foot.Offset + y * foot.Footprint.RowPitch + 4 * x; + if (pixel[0] != n || pixel[1] != 255 - n || pixel[2] != 0 || pixel[3] != 255) { + std::fprintf(stderr, "graphics pipeline %u drew %u %u %u %u\n", n, pixel[0], pixel[1], pixel[2], + pixel[3]); + ok = false; + } + } + std::memset(bytes, 0xee, 4096 + 4 * kWords); + readback->Unmap(0, nullptr); + return ok; + } +}; + +std::vector all_compute() { + std::vector out; + for (unsigned n = 0; n < kCompute; ++n) out.push_back(n); + return out; +} + +std::uint64_t estimate(unsigned n) { return leonida::large_module_estimate(module_bytes[n]); } + +// How many of the large compute modules are in the driver at once, with five threads to compile them; 0: not known (the +// budget is read from the machine). +int expected_at_once() { + if (serial) return 1; + if (unlimited) return 5; + if (!fixed_budget) return 0; + // The first wave is the largest, in order, while they fit. + std::uint64_t sum = 0; + int count = 0; + for (unsigned n = kBig; n-- > 0 && sum + estimate(n) <= *fixed_budget; ++count) sum += estimate(n); + return std::clamp(count, 1, 5); +} + +// The large compute modules are held back in the driver until as many as may be are in, and no more come. +bool side_by_side(const Setup& setup) { + Ref dev; + CHECK(setup.device("4", dev)); + Pipelines pipelines; + Frame frame; + hooks.reset(); + CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, all_compute(), false)); + CHECK(hooks.creates() == 0); // nothing is compiled at creation + const int at_once = expected_at_once(); + hooks.closed = true; + ReplayResult result = ReplayResult::unsupported; + std::thread submitting([&] { result = frame.submit(); }); + const bool filled = hooks.wait_large(std::max(at_once, 1)); + // With a thread to spare, the small ones are compiled while the large ones wait (unlimited: every thread has a large one). + const bool small_ones = unlimited || !at_once || hooks.wait([] { return hooks.small_done == int(kSmall); }); + std::this_thread::sleep_for(300ms); + int held = 0; + { + std::lock_guard lock(hooks.mutex); + held = hooks.large_in; + } + hooks.open(); + submitting.join(); + CHECK(filled); + CHECK(!at_once || held == at_once); + CHECK(small_ones); + CHECK(result == ReplayResult::success && frame.right()); + CHECK(hooks.over == 0); + CHECK(hooks.creates() == kCompute); // each once + CHECK(!at_once || hooks.most_large <= at_once || unlimited); + CHECK(frame.submit() == ReplayResult::success && frame.right() && hooks.creates() == kCompute); + return true; +} + +// The same values whatever compiles them, without workers (each where prepare() meets it) and with them. +bool same_values(const Setup& setup) { + for (const char* threads : {"0", "16"}) { + Ref dev; + CHECK(setup.device(threads, dev)); + Pipelines pipelines; + Frame frame; + hooks.reset(); + CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, all_compute(), true)); + CHECK(frame.submit() == ReplayResult::success && frame.right()); + CHECK(hooks.over == 0); + CHECK(hooks.creates() == kCompute + kGraphics); + CHECK(*threads != '0' || hooks.most_large == 1); + } + return true; +} + +// A graphics pipeline whose estimate is past the budget (or the one at a time of serial) is in alone among the large ones, +// and the small ones are compiled beside it. +bool graphics_among_the_large(const Setup& setup) { + Ref dev; + CHECK(setup.device("4", dev)); + Pipelines pipelines; + Frame frame; + hooks.reset(); + CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, all_compute(), true)); + hooks.closed = true; + ReplayResult result = ReplayResult::unsupported; + std::thread submitting([&] { result = frame.submit(); }); + const bool one = hooks.wait_large(1); + const bool small_ones = unlimited || !expected_at_once() || + hooks.wait([] { return hooks.small_done == int(kSmall); }); + std::this_thread::sleep_for(300ms); + int held = 0; + bool first_is_graphics = false; + { + std::lock_guard lock(hooks.mutex); + held = hooks.large_in; + for (const Start& s : hooks.started) + if (s.large) { + first_is_graphics = s.program < 0; + break; + } + } + hooks.open(); + submitting.join(); + CHECK(one && small_ones); + if (budgeted && fixed_budget) CHECK(held == 1 && first_is_graphics); // the largest first + if (serial) CHECK(held == 1); + CHECK(result == ReplayResult::success && frame.right()); + CHECK(hooks.over == 0); + CHECK(hooks.creates() == kCompute + kGraphics); + return true; +} + +// Two large graphics pipelines and nothing else: one after the other, or both at once without a limit. +bool graphics_only(const Setup& setup) { + Ref dev; + CHECK(setup.device("4", dev)); + Pipelines pipelines; + Frame frame; + hooks.reset(); + CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, {}, true)); + hooks.closed = true; + ReplayResult result = ReplayResult::unsupported; + std::thread submitting([&] { result = frame.submit(); }); + const int at_once = unlimited ? 2 : 1; + const bool filled = hooks.wait_large(at_once); + std::this_thread::sleep_for(300ms); + int held = 0; + { + std::lock_guard lock(hooks.mutex); + held = hooks.large_in; + } + hooks.open(); + submitting.join(); + CHECK(filled); + if (!budgeted || fixed_budget) CHECK(held == at_once); + CHECK(result == ReplayResult::success && frame.right()); + CHECK(hooks.over == 0 && hooks.creates() == kGraphics); + return true; +} + +// The driver refuses one large compute module: its dispatch is dropped, the rest runs, and it is not tried again. Its place +// goes to the next. +bool refused(const Setup& setup) { + for (const char* threads : {"0", "4"}) { + Ref dev; + CHECK(setup.device(threads, dev)); + Pipelines pipelines; + Frame frame; + hooks.reset(); + CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, all_compute(), false)); + hooks.fail_large = 2; + CHECK(frame.submit() == ReplayResult::success); + int dropped = -1; + { + std::lock_guard lock(hooks.mutex); + int seen = 0; + for (const Start& s : hooks.started) + if (s.large && s.program >= 0 && seen++ == 2) dropped = s.program; + } + CHECK(dropped >= 0); + CHECK(frame.right(dropped)); + CHECK(hooks.creates() == kCompute); + CHECK(frame.submit() == ReplayResult::success && frame.right(dropped)); + CHECK(hooks.creates() == kCompute); + } + return true; +} + +// Two queues submit the same pipelines at once: each is compiled once, the budget is kept, and nobody waits for ever. +bool two_queues(const Setup& setup) { + Ref dev; + CHECK(setup.device("4", dev)); + Pipelines pipelines; + Frame frames[2]; + CHECK(pipelines.create(dev.p)); + auto backwards = all_compute(); + std::reverse(backwards.begin(), backwards.end()); + CHECK(frames[0].create(dev.p, pipelines, all_compute(), true)); + CHECK(frames[1].create(dev.p, pipelines, backwards, true)); + hooks.reset(); + ReplayResult results[2]{}; + std::thread threads[2]; + for (int i = 0; i < 2; ++i) threads[i] = std::thread([&, i] { results[i] = frames[i].submit(); }); + for (auto& t : threads) t.join(); + for (int i = 0; i < 2; ++i) CHECK(results[i] == ReplayResult::success && frames[i].right()); + CHECK(hooks.creates() == kCompute + kGraphics); + CHECK(hooks.over == 0); + return true; +} + +// The device's last references are released by the thread whose submission compiles, with large ones waiting for room. +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(); + hooks.reset(); + CHECK(pipelines->create(dev.p) && frame->create(dev.p, *pipelines, all_compute(), true)); + hooks.track = true; + hooks.closed = true; + ReplayResult result = ReplayResult::unsupported; + bool ok = false; + std::thread submitting([&] { + result = frame->submit(); + ok = frame->right(); + frame.reset(); + pipelines.reset(); + }); + const bool compiling = hooks.wait_large(1); + std::this_thread::sleep_for(100ms); + dev.reset(); + hooks.open(); + submitting.join(); + _putenv_s("LEONIDA_PIPELINE_CACHE_BYTES", "0"); + CHECK(compiling); + CHECK(result == ReplayResult::success && ok); + CHECK(hooks.cache_reads > 0); + CHECK(!hooks.cache_read_during_create); + CHECK(!hooks.cache_read_with_workers); + CHECK(hooks.live == 0); + return true; +} + +// One place for large compiles. The warm-up thread has it, and wants the next one after it; a submission that needs four +// others, one of which the warm-up thread waits to build, gets them all first, and builds that one itself. +bool warmup(const Setup& setup) { + Ref dev; + CHECK(setup.device("4", dev)); + Pipelines pipelines; + Frame frame; + hooks.reset(); + hooks.closed = true; + hooks.linger = 100ms; + // The warm-up's builds run on the compiler's workers (LEONIDA_COMPILE_THREADS): whichever of them takes a job is + // one of the warm-up's threads. All but one of them may be in the warm-up, and wait at the gate, at a time. + struct WarmThreads { + std::mutex mutex; + std::set ids; + WarmThreads() { + rt::d3d12::PipelineCompiler::instance().set_job_probe([this](const void*) { + std::lock_guard lock(mutex); + ids.insert(std::this_thread::get_id()); + }); + } + ~WarmThreads() { rt::d3d12::PipelineCompiler::instance().set_job_probe(nullptr); } + bool has(std::thread::id id) { + std::lock_guard lock(mutex); + return ids.contains(id); + } + } warm; + CHECK(pipelines.create(dev.p)); + if (!hooks.wait_large(1)) { + hooks.open(); + CHECK(!"the warm-up thread compiles a large one"); + } + std::thread::id first_thread; + int first = -1; + { + std::lock_guard lock(hooks.mutex); + for (const Start& s : hooks.started) + if (s.large) first_thread = s.thread, first = s.program; + } + // Their sizes rise with their numbers, so one worker takes 0 first. Several take the first ones together, and + // whichever reaches the gate first is the one in the driver. + CHECK(first >= 0 && first < int(kBig)); + if (rt::d3d12::PipelineCompiler::instance().threads() == 1) CHECK(first == 0); + CHECK(warm.has(first_thread)); + // Four of the others, among them the next the warm-up builds (1 after 0). + std::vector wanted; + for (const unsigned n : {4u, 5u, 3u, 1u, 0u}) + if (int(n) != first && wanted.size() < 4) wanted.push_back(n); + CHECK(frame.create(dev.p, pipelines, wanted, false)); + // The large ones: the warm-up's small ones may still be starting on the compiler's other workers. + const std::size_t before = hooks.large_creates(); + ReplayResult result = ReplayResult::unsupported; + std::thread submitting([&] { result = frame.submit(); }); + std::this_thread::sleep_for(500ms); + const bool waits = hooks.large_creates() == before; // the place is taken + hooks.open(); + submitting.join(); + const bool done = result == ReplayResult::success && frame.right(); + rt::d3d12::PipelineCompiler::instance().wait_idle(); // the warm-up thread builds the rest + std::vector started; + { + std::lock_guard lock(hooks.mutex); + started = hooks.started; + } + CHECK(waits); + CHECK(done); + CHECK(hooks.over == 0 && hooks.most_large == 1); + std::set once; + for (const Start& s : started) once.insert(s.program); + CHECK(started.size() == kCompute && once.size() == kCompute); // each once + std::erase_if(started, [](const Start& s) { return !s.large; }); + std::set built; + for (std::size_t i = 1; i <= wanted.size(); ++i) { + CHECK(!warm.has(started[i].thread)); // none of the warm-up's between two of the submission's + built.insert(started[i].program); + } + CHECK(built == std::set(wanted.begin(), wanted.end())); + for (std::size_t i = wanted.size() + 1; i < started.size(); ++i) CHECK(warm.has(started[i].thread)); + return true; +} + +// The large ones that four threads create at once are held back in the driver until as many as may be are in. +bool eager(const Setup& setup) { + Ref dev; + CHECK(setup.device("4", dev)); + Pipelines pipelines; + Frame frame; + hooks.reset(); + hooks.closed = true; + bool created = false; + std::thread creating([&] { created = pipelines.create(dev.p, 4); }); + const bool one = hooks.wait_large(1); + std::this_thread::sleep_for(300ms); + int held = 0; + { + std::lock_guard lock(hooks.mutex); + held = hooks.large_in; + } + hooks.open(); + creating.join(); + CHECK(one && created); + CHECK(held == expected_at_once()); + CHECK(hooks.over == 0 && hooks.creates() == kCompute); + CHECK(frame.create(dev.p, pipelines, all_compute(), false)); + CHECK(frame.submit() == ReplayResult::success && frame.right()); + CHECK(hooks.creates() == kCompute); + return true; +} + +bool run(const Setup& setup, const std::string& scenario) { + if (scenario == "warmup") return warmup(setup); + if (scenario == "eager") return eager(setup); + return side_by_side(setup) && same_values(setup) && graphics_among_the_large(setup) && graphics_only(setup) && + refused(setup) && two_queues(setup) && device_destroyed(setup); +} + +} // namespace + +int main(int argc, char** argv) { + const std::string scenario = argc > 1 ? argv[1] : ""; + 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 + if (scenario != "warmup") _putenv_s("LEONIDA_COMPUTE_WARMUP", "0"); // every compile is a submission's + const testfiles::ScratchDir library("leonida_big_compute_test"); + if (!write_library(library.path())) return 1; + if (!run({&vk, library.path().string()}, scenario)) return 1; + if (vk.validation_errors()) { + std::fprintf(stderr, "FAIL: %u validation errors\n", vk.validation_errors()); + return 1; + } + std::printf("d3d12_big_compute_test: passed on %s\n", properties.deviceName); + return 0; +} diff --git a/runtime/test/d3d12_compile_pool_test.cpp b/runtime/test/d3d12_compile_pool_test.cpp new file mode 100644 index 0000000000..32fbb5902b --- /dev/null +++ b/runtime/test/d3d12_compile_pool_test.cpp @@ -0,0 +1,352 @@ +// The pipeline compiler's workers (shims/d3d12_pipeline_compile.h) under LEONIDA_ASYNC_PIPELINES=1, through the D3D12 +// layer on a GPU: one compute module of more than 128 KiB, which is a large build, and many small ones, each asked for by +// a dispatch (big_compute_module.h makes them; every dispatch stores a value the CPU computes too). +// hold (the default) the large module's build is parked on its worker by the compiler's job probe, after it counts as +// running and before it reaches the driver, so "a long compile in flight" is a state the test +// holds. With more than one worker every small pipeline is then built by the driver and its +// dispatch stores the right value, while the large one is still parked. With one worker +// (LEONIDA_COMPILE_THREADS=1) none is: they wait behind it, as before the pool. Let go, the +// large one builds, and every dispatch stores the right value. +// measure [seed] +// nothing parked: a large module of of SPIR-V and small ones, with the time after +// which the small ones were all ready, the time for the large one, and the process's peak commit. +// For a run by hand (4194304 200: the driver takes tens of seconds over the large one), with +// a seed it has not seen, since a driver keeps what it compiled across runs. +// The warm-up is off, so every build is one a dispatch asked for. Self-contained: the SPIR-V is made in memory. No game +// data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. +#include "big_compute_module.h" +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "test_temp_dir.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_pipeline_compile.h" +#include "../src/shader_library.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using d3d12test::Ref; +using rt::d3d12::PipelineCompiler; +using Clock = std::chrono::steady_clock; + +constexpr unsigned kWords = bigmodule::kLoadBase + bigmodule::kLoadWords; +constexpr unsigned kMaxSmall = bigmodule::kLoadBase - 1; // each program stores the word of its number +constexpr std::size_t kSmallBytes = 12 * 1024; + +#define CHECK(expr) \ + do { \ + if (!(expr)) { \ + std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #expr); \ + return false; \ + } \ + } while (0) + +long long ms_since(Clock::time_point start) { + return std::chrono::duration_cast(Clock::now() - start).count(); +} + +// Program 0 is the large one; 1 to `small_count` are the small ones. +unsigned small_count = 64; +std::size_t big_bytes = 132 * 1024; +std::uint32_t seed = 20261125; // other modules for another seed: ones the driver has not kept from a run before +std::vector programs; + +std::vector program(unsigned n) { return d3d12test::fssm_program({0x43504f00u, n, 0xbf810000u}); } + +bool write_library(const std::filesystem::path& dir) { + programs.resize(small_count + 1); + std::ofstream index(dir / "index.json", std::ios::binary | std::ios::trunc); + index << "{"; + for (unsigned n = 0; n <= small_count; ++n) { + const std::string name = "cs" + std::to_string(n); + const bigmodule::Words words = bigmodule::make(n ? kSmallBytes : big_bytes, seed + n, &programs[n]); + CHECK((words.size() * 4 > 128 * 1024) == (n == 0)); + std::ofstream f(dir / (name + ".spv"), std::ios::binary | std::ios::trunc); + f.write(reinterpret_cast(words.data()), std::streamsize(words.size() * 4)); + CHECK(bool(f)); + index << (n ? ",\n" : "") << "\"" << name << "\": {\"stage\": \"cs\", \"fssm_sha256\": \"" + << leonida::sha256_hex(program(n)) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"local_size\": [1, 1, 1], \"wave64\": false}"; + } + index << "}"; + return bool(index); +} + +struct Pipelines { + Ref root; + std::vector states; + ~Pipelines() { + for (auto* s : states) s->Release(); + } + 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 <= small_count; ++n) { + const auto cs = d3d12test::shader_container(program(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 a list that dispatches the programs `first` to `last` and copies what they stored back. +struct Frame { + unsigned first = 0, last = 0; + Ref buffer, readback; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + UINT64 fence_value = 0; + + bool create(ID3D12Device* dev, const Pipelines& p, unsigned from, unsigned to) { + first = from; + last = to; + const D3D12_HEAP_PROPERTIES def{D3D12_HEAP_TYPE_DEFAULT}, back{D3D12_HEAP_TYPE_READBACK}; + const auto bd = d3d12test::buffer_desc(4 * kWords, 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)))); + const auto rd = d3d12test::buffer_desc(4 * kWords); + CHECK(SUCCEEDED(dev->CreateCommittedResource(&back, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&readback.p)))); + 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)))); + CHECK(SUCCEEDED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + list->SetComputeRootSignature(p.root.p); + list->SetComputeRootUnorderedAccessView(0, buffer->GetGPUVirtualAddress()); + for (unsigned n = first; n <= last; ++n) { + list->SetPipelineState(p.states[n]); + list->SetComputeRoot32BitConstant(1, n, 0); + list->Dispatch(1, 1, 1); + } + const auto to_source = + d3d12test::transition(buffer.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_source); + list->CopyBufferRegion(readback.p, 0, buffer.p, 0, 4 * kWords); + const auto back_again = + d3d12test::transition(buffer.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list->ResourceBarrier(1, &back_again); + CHECK(SUCCEEDED(list->Close())); + return true; + } + + // Runs the list and returns how many of its programs stored what the CPU computes: a dispatch whose pipeline is not + // ready is left out (LEONIDA_ASYNC_PIPELINES), and its word stays what it was. + int stored() { + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + queue->Signal(fence.p, ++fence_value); + fence->SetEventOnCompletion(fence_value, nullptr); + void* mapped = nullptr; + if (FAILED(readback->Map(0, nullptr, &mapped)) || !mapped) return -1; + std::uint32_t words[kWords]; + std::memcpy(words, mapped, sizeof words); + std::memset(mapped, 0xee, sizeof words); // stale bytes cannot pass the next time + readback->Unmap(0, nullptr); + int right = 0; + for (unsigned n = first; n <= last; ++n) right += words[n] == programs[n].run(n); + return right; + } + int count() const { return int(last - first + 1); } + + // Runs the list again and again until every program stored its value. + bool all_stored(unsigned ms) { + const auto until = Clock::now() + std::chrono::milliseconds(ms); + for (;;) { + if (stored() == count()) return true; + if (Clock::now() > until) return false; + Sleep(10); + } + } +}; + +struct Event { + HANDLE handle = CreateEventW(nullptr, TRUE, FALSE, nullptr); + ~Event() { CloseHandle(handle); } + void set() const { SetEvent(handle); } + bool wait(DWORD ms) const { return WaitForSingleObject(handle, ms) == WAIT_OBJECT_0; } +}; + +bool make_device(vktest::Device& vk, const std::string& library, Ref& out) { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = vk.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; +} + +bool hold(vktest::Device& vk, const std::string& library) { + auto& compiler = PipelineCompiler::instance(); + const unsigned workers = compiler.threads(); + Event parked, proceed; + std::atomic target{nullptr}; + std::atomic let_go{false}; + { + Ref dev; + CHECK(make_device(vk, library, dev)); + Pipelines pipelines; + Frame large, smalls; + CHECK(pipelines.create(dev.p)); + CHECK(large.create(dev.p, pipelines, 0, 0) && smalls.create(dev.p, pipelines, 1, small_count)); + const auto before = compiler.stats(); + const std::uint64_t before_completed = before.completed; + target = pipelines.states[0]; + compiler.set_job_probe([&](const void* owner) { + if (owner != target.load()) return; + parked.set(); + proceed.wait(INFINITE); + }); + // A failed check leaves through here too: the device's teardown waits for the build, which must not stay parked. + struct Unpark { + PipelineCompiler& compiler; + Event& proceed; + ~Unpark() { + proceed.set(); + compiler.set_job_probe(nullptr); + } + } unpark{compiler, proceed}; + // A job counts as completed a moment after the pipeline it built can be used. + const auto completed = [&](std::uint64_t jobs) { + for (int i = 0; i < 1000 && compiler.stats().completed != before_completed + jobs; ++i) Sleep(5); + return compiler.stats().completed == before_completed + jobs; + }; + const auto start = Clock::now(); + CHECK(large.stored() == 0); // not built: asked for, and its dispatch left out + CHECK(parked.wait(30000)); + CHECK(smalls.stored() >= 0); // asks for every small one + CHECK(compiler.stats().submitted == before.submitted + small_count + 1); + if (workers > 1) { + // The other workers build them, in the driver, while the large one is in flight. + CHECK(smalls.all_stored(120000)); + const auto took = ms_since(start); + CHECK(!let_go && large.stored() == 0); + CHECK(completed(small_count)); + std::printf("hold (%u workers): %u small pipelines built and dispatched in %lld ms with the large build in " + "flight\n", workers, small_count, took); + } else { + Sleep(500); + CHECK(smalls.stored() == 0 && large.stored() == 0); + CHECK(completed(0)); + std::printf("hold (1 worker): no small pipeline built with the large build in flight, as before the pool\n"); + } + let_go = true; + proceed.set(); + CHECK(large.all_stored(300000) && smalls.all_stored(300000)); + compiler.wait_idle(); + CHECK(completed(small_count + 1)); + } + CHECK(!compiler.worker_running()); // the device's last release stopped and joined every worker + return true; +} + +bool measure(vktest::Device& vk, const std::string& library) { + auto& compiler = PipelineCompiler::instance(); + { + Ref dev; + CHECK(make_device(vk, library, dev)); + Pipelines pipelines; + Frame large, smalls; + CHECK(pipelines.create(dev.p)); + CHECK(large.create(dev.p, pipelines, 0, 0) && smalls.create(dev.p, pipelines, 1, small_count)); + const auto start = Clock::now(); + CHECK(large.stored() == 0); + Sleep(50); // the large build is the first a worker takes + CHECK(smalls.stored() >= 0); + CHECK(smalls.all_stored(1800000)); + const auto small_ms = ms_since(start); + const bool large_ready_first = large.stored() == 1; + CHECK(large.all_stored(1800000)); + const auto large_ms = ms_since(start); + compiler.wait_idle(); + PROCESS_MEMORY_COUNTERS memory{sizeof memory}; + GetProcessMemoryInfo(GetCurrentProcess(), &memory, sizeof memory); + std::printf("measure: workers=%u large_bytes=%zu small=%u small_ready_ms=%lld large_ready_ms=%lld " + "large_ready_before_small=%d peak_commit_mib=%zu\n", compiler.threads(), big_bytes, small_count, + small_ms, large_ms, int(large_ready_first), std::size_t(memory.PeakPagefileUsage >> 20)); + } + CHECK(!compiler.worker_running()); + return true; +} + +} // namespace + +int main(int argc, char** argv) { + const std::string scenario = argc > 1 ? argv[1] : "hold"; + if (scenario == "measure") { + if (argc > 2) big_bytes = std::strtoull(argv[2], nullptr, 10); + if (argc > 3) small_count = unsigned(std::strtoul(argv[3], nullptr, 10)); + if (argc > 4) seed = std::uint32_t(std::strtoul(argv[4], nullptr, 10)); + } else if (scenario != "hold") { + std::fprintf(stderr, "usage: d3d12_compile_pool_test [hold | measure [seed]]\n"); + return 2; + } + if (small_count < 1 || small_count > kMaxSmall || big_bytes <= 128 * 1024) { + std::fprintf(stderr, "1 to %u small modules, and more than 131072 bytes for the large one\n", kMaxSmall); + return 2; + } + 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; + } + _putenv_s("LEONIDA_ASYNC_PIPELINES", "1"); + _putenv_s("LEONIDA_STRICT_REPLAY", "0"); + _putenv_s("LEONIDA_LAZY_COMPUTE", "1"); + _putenv_s("LEONIDA_COMPUTE_WARMUP", "0"); // every build is one a dispatch asked for + _putenv_s("LEONIDA_PIPELINE_CACHE_BYTES", "0"); // no session file in or out + const testfiles::ScratchDir library("leonida_compile_pool_test"); + if (!write_library(library.path())) return 1; + if (!(scenario == "measure" ? measure(vk, library.path().string()) : hold(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_compile_pool_test: passed on %s\n", properties.deviceName); + return 0; +} diff --git a/runtime/test/d3d12_compile_teardown_test.cpp b/runtime/test/d3d12_compile_teardown_test.cpp index f9344c0694..8883e69787 100644 --- a/runtime/test/d3d12_compile_teardown_test.cpp +++ b/runtime/test/d3d12_compile_teardown_test.cpp @@ -18,7 +18,9 @@ // exit stop_pipeline_compiles with a device alive: the queue goes, later builds are refused, a warm-up // is skipped and a dispatch (LEONIDA_ASYNC_PIPELINES on) builds its pipeline in place and runs; // save_pipeline_caches_at_exit then writes the session cache with the device alive, once. -// After each case the compiler's thread is gone and the process's thread count is back where it was. +// After each case the compiler's threads are gone and the process's thread count is back where it was. +// Run with the compiler's default number of workers and with LEONIDA_COMPILE_THREADS=1 and 4 (runtime/CMakeLists.txt): +// "the worker" below is whichever of them has the job. // No game data: the shader is test/glsl/cs_user_data.comp, the programs are made-up FSSM bytes. #include "shader_fixture_path.h" #include "test_temp_dir.h" @@ -39,6 +41,7 @@ #include #include #include +#include #include #include #include @@ -348,22 +351,32 @@ bool drain(PipelineCompiler& compiler) { return done.wait(120000); } -// Holds the worker in a job of no device until open() (or the end of the scope). +// Holds every worker in a job of no device until open() (or the end of the scope): one small demanded job for each +// (LEONIDA_COMPILE_THREADS), each under an owner of its own, so nothing that is queued meanwhile starts. struct Gate { - Event entered, opened, left; + struct Hold { + Event entered, left; + }; + Event opened; + std::vector> holds; explicit Gate(PipelineCompiler& compiler) { - static const int gate = 0; - compiler.submit(&gate, nullptr, 0, [this] { - entered.set(); - opened.wait(INFINITE); - left.set(); - }); - entered.wait(); + static const char owners[rt::d3d12::kMaxCompileThreads] = {}; + const unsigned workers = compiler.threads(); + for (unsigned i = 0; i < workers; ++i) holds.push_back(std::make_unique()); + for (unsigned i = 0; i < workers; ++i) { + Hold* const hold = holds[i].get(); + compiler.submit(&owners[i], nullptr, 0, [this, hold] { + hold->entered.set(); + opened.wait(INFINITE); + hold->left.set(); + }); + } + for (const auto& hold : holds) hold->entered.wait(); } void open() { opened.set(); } ~Gate() { opened.set(); - left.wait(); // the job is out of this object before its events close + for (const auto& hold : holds) hold->left.wait(); // the jobs are out of this object before its events close } }; @@ -424,6 +437,7 @@ int main() { auto& compiler = PipelineCompiler::instance(); EXPECT(!compiler.worker_running()); + std::printf("workers: %u\n", compiler.threads()); // llvmpipe keeps no pipelines in a VkPipelineCache (measured: vkGetPipelineCacheData returns the 32-byte header // alone after the build), and the runtime writes no file of a bare header (save_session_pipeline_cache). VkPhysicalDeviceDriverProperties driver{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES}; diff --git a/runtime/test/large_module_gate.h b/runtime/test/large_module_gate.h index ea805c9268..fcd29ed0ed 100644 --- a/runtime/test/large_module_gate.h +++ b/runtime/test/large_module_gate.h @@ -1,181 +1,4 @@ -// How many large SPIR-V modules vk_pipeline_check lets into the driver at once, by a memory budget. -// -// Measured on RADV GFX1201 (Mesa 25.3.6) with the Mesa shader cache off: a 5.7 MB translated ray-tracing compute -// module peaks at 1.96 GB of process memory compiling alone (~330 bytes per SPIR-V byte), a 0.36 MB one at 94 MB. -// Compiling the large ones strictly one at a time left the other threads idle: 40 modules (27 over 4 MiB) on 6 -// threads took 308 s exclusively and 75 s in parallel, 7.0 GB and 8.7 GB peak. kBytesPerSpirvByte keeps a margin -// over the measurement. -// -// The process grew past one module's peak even one at a time because glibc keeps freed memory in per-thread arenas -// (6 threads: 6.2 GB; MALLOC_ARENA_MAX=1: 2.1 GB, same modules). release_free_memory() hands it back after each -// large module. +// Moved to runtime/src: the runtime uses it too (large_module_gate.h there). #pragma once -#include -#include -#include -#include -#include -#include - -#ifdef _WIN32 -#ifndef NOMINMAX -#define NOMINMAX -#endif -#include -#endif -#if defined(__GLIBC__) -#include -#endif - -namespace leonida { - -inline constexpr uint64_t kBytesPerSpirvByte = 512; - -inline uint64_t large_module_estimate(uint64_t spirv_bytes) { return spirv_bytes * kBytesPerSpirvByte; } - -#if defined(__linux__) -// The first unsigned number in a file ("max" and unreadable files give no value). -inline bool read_u64_file(const std::string& path, uint64_t& value) { - std::FILE* f = std::fopen(path.c_str(), "r"); - if (!f) return false; - unsigned long long v = 0; - const bool ok = std::fscanf(f, "%llu", &v) == 1; - std::fclose(f); - value = v; - return ok; -} - -// The room left under the cgroup v2 memory.max of this process and of every cgroup above it (a container or -// systemd-run -p MemoryMax=...), or UINT64_MAX when none sets a limit. cgroup_root is a parameter for the tests. -inline uint64_t cgroup_memory_room(const std::string& self_cgroup_file = "/proc/self/cgroup", - const std::string& cgroup_root = "/sys/fs/cgroup") { - std::FILE* f = std::fopen(self_cgroup_file.c_str(), "r"); - if (!f) return UINT64_MAX; - char line[4096]; - std::string rel; - while (std::fgets(line, sizeof(line), f)) { - std::string l(line); - if (l.rfind("0::", 0) == 0) { // the cgroup v2 line - rel = l.substr(3); - while (!rel.empty() && (rel.back() == '\n' || rel.back() == '\r')) rel.pop_back(); - break; - } - } - std::fclose(f); - uint64_t room = UINT64_MAX; - for (std::string dir = rel; !dir.empty();) { - // In a cgroup namespace, "/" can be a constrained cgroup mounted as the visible root. - const std::string base = dir == "/" ? cgroup_root : cgroup_root + dir; - uint64_t max = 0, current = 0; - if (read_u64_file(base + "/memory.max", max) && read_u64_file(base + "/memory.current", current)) - room = std::min(room, max > current ? max - current : 0); - const auto slash = dir.find_last_of('/'); - if (dir == "/" || slash == std::string::npos) break; - dir.resize(slash == 0 ? 1 : slash); - } - return room; -} -#endif - -// Memory the OS could give this process now, or 0 when it can't tell (then the caller keeps the old exclusive gate). -inline uint64_t available_memory_bytes() { -#ifdef _WIN32 - MEMORYSTATUSEX status{}; - status.dwLength = sizeof(status); - return GlobalMemoryStatusEx(&status) ? uint64_t(status.ullAvailPhys) : 0; -#elif defined(__linux__) - std::FILE* f = std::fopen("/proc/meminfo", "r"); - if (!f) return 0; - char line[256]; - unsigned long long kb = 0; - bool found = false; - while (std::fgets(line, sizeof(line), f)) - if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) { found = true; break; } - std::fclose(f); - if (!found) return 0; - const uint64_t room = cgroup_memory_room(); - return std::max(1, std::min(uint64_t(kb) * 1024, room)); // 0 would mean "unknown" -#else - return 0; -#endif -} - -// Return memory freed by the driver's compiler to the OS (glibc keeps it in the arena of the thread that freed it). -inline void release_free_memory() { -#if defined(__GLIBC__) - malloc_trim(0); -#endif -} - -// Lets large modules in while their estimates fit the budget and fewer than max_inflight are in. One always gets in -// when none is, so a module bigger than the whole budget still compiles (alone among the large ones). -class LargeModuleGate { -public: - LargeModuleGate(uint64_t budget, unsigned max_inflight) - : budget_(budget), max_inflight_(max_inflight ? max_inflight : 1) {} - - bool admits(uint64_t estimate) const { - std::lock_guard g(mu_); - return admits_locked(estimate); - } - void enter(uint64_t estimate) { - std::unique_lock l(mu_); - cv_.wait(l, [&] { return admits_locked(estimate); }); - used_ += estimate; - ++inflight_; - } - void leave(uint64_t estimate) { - { - std::lock_guard g(mu_); - used_ -= estimate; - --inflight_; - } - cv_.notify_all(); - } - unsigned inflight() const { - std::lock_guard g(mu_); - return inflight_; - } - uint64_t budget() const { return budget_; } - unsigned max_inflight() const { return max_inflight_; } - - // Holds a place from construction until destruction (or release()), then hands freed memory back. - class Ticket { - public: - Ticket() = default; - Ticket(LargeModuleGate& gate, uint64_t estimate) : gate_(&gate), estimate_(estimate) { gate.enter(estimate); } - Ticket(Ticket&& o) noexcept : gate_(o.gate_), estimate_(o.estimate_) { o.gate_ = nullptr; } - Ticket& operator=(Ticket&& o) noexcept { - if (this != &o) { release(); gate_ = o.gate_; estimate_ = o.estimate_; o.gate_ = nullptr; } - return *this; - } - Ticket(const Ticket&) = delete; - Ticket& operator=(const Ticket&) = delete; - ~Ticket() { release(); } - void release() { - if (!gate_) return; - gate_->leave(estimate_); - gate_ = nullptr; - release_free_memory(); - } - private: - LargeModuleGate* gate_ = nullptr; - uint64_t estimate_ = 0; - }; - -private: - bool admits_locked(uint64_t estimate) const { - if (inflight_ == 0) return true; - return inflight_ < max_inflight_ && used_ + estimate <= budget_; - } - - const uint64_t budget_; - const unsigned max_inflight_; - mutable std::mutex mu_; - std::condition_variable cv_; - uint64_t used_ = 0; - unsigned inflight_ = 0; -}; - -} // namespace leonida +#include "../src/large_module_gate.h" diff --git a/runtime/test/pipeline_compiler_pool_test.cpp b/runtime/test/pipeline_compiler_pool_test.cpp new file mode 100644 index 0000000000..d042ee47c8 --- /dev/null +++ b/runtime/test/pipeline_compiler_pool_test.cpp @@ -0,0 +1,561 @@ +// The rules of rt::d3d12::PipelineCompiler's workers (shims/d3d12_pipeline_compile.h), with made-up jobs: +// threads LEONIDA_COMPILE_THREADS as text: the default, 1, 0, not a number. +// lane with N workers at most N-1 heavy jobs run (large demanded builds, and every speculative one), and a +// small demanded build runs while they are held; a large demanded build waits for a place and gets it +// before the speculative ones. +// very large of the builds submitted as huge, as many at a time as LEONIDA_COMPILE_HEAVY_MAX says (1), demanded or +// speculative, with idle workers; a large build and a small one are not held by them. +// two freed a job whose end lets two others start: both do. +// owner one job of an owner at a time, the others' jobs meanwhile; after_running() with one job running and +// two queued drops the two and runs `last` once, after the job. +// checkpoint starts only when no worker is in a build; has_compile_waiter() counts a build that is running; a +// build starts while a checkpoint runs. +// one worker the order there was before the pool: demanded, speculative by size, checkpoint. +// cancel waits for every running job of a device; release() from inside a job; stop_for_exit() with jobs +// running and with none. +// mixed thousands of short jobs: no owner twice at a time, never more than N-1 heavy or one very large, +// every job run. +// The jobs wait on events the test holds, so "running" is a state and not a race; a check that waits gives up after +// 10 s, and the whole test after 120 s, so a missing wake-up fails it and does not hang it. No Vulkan device, no GPU. +#include "../shims/d3d12_pipeline_compile.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace std::chrono_literals; +using rt::d3d12::PipelineCompiler; +using Size = PipelineCompiler::Size; + +// Ends the process: the workers a failed check leaves in their jobs would keep the rest from ending. +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); \ + std::fflush(stderr); \ + std::_Exit(1); \ + } \ +} while (0) + +bool eventually(const std::function& what) { + const auto end = std::chrono::steady_clock::now() + 10s; + while (!what()) { + if (std::chrono::steady_clock::now() > end) return false; + std::this_thread::sleep_for(1ms); + } + return true; +} + +// Long enough for a worker that may start a job to have started it: what "does not start" is measured against. +void settle() { std::this_thread::sleep_for(150ms); } + +class Flag { +public: + void set() { + { + std::lock_guard lock(mutex_); + on_ = true; + } + changed_.notify_all(); + } + bool wait() { + std::unique_lock lock(mutex_); + return changed_.wait_for(lock, 10s, [this] { return on_; }); + } + void wait_forever() { + std::unique_lock lock(mutex_); + changed_.wait(lock, [this] { return on_; }); + } + bool is() { + std::lock_guard lock(mutex_); + return on_; + } + +private: + std::mutex mutex_; + std::condition_variable changed_; + bool on_ = false; +}; + +// A job that says when it started and stays in its work until go is set. +struct Held { + Flag started, go, done; + std::function job() { + return [this] { + started.set(); + go.wait_forever(); + done.set(); + }; + } +}; + +constexpr std::size_t kCheckpoint = SIZE_MAX; +int owners[64]; // addresses to file jobs under +int devices[4]; + +std::size_t count_started(std::vector>& jobs) { + std::size_t n = 0; + for (auto& job : jobs) n += job->started.is(); + return n; +} + +void test_threads() { + using rt::d3d12::compile_threads; + CHECK(compile_threads("", 16) == 8 && compile_threads(nullptr, 32) == 8 && compile_threads("", 12) == 6); + CHECK(compile_threads("", 4) == 2 && compile_threads("", 2) == 2 && compile_threads("", 0) == 2); // at least 2 + CHECK(compile_threads("1", 16) == 1); // the one thread there was + CHECK(compile_threads("0", 16) == 1); + CHECK(compile_threads("3", 16) == 3 && compile_threads("12", 4) == 12); + CHECK(compile_threads("many", 16) == 8 && compile_threads("-1", 16) == 8); + using rt::d3d12::compile_heavy_max; + CHECK(compile_heavy_max("") == 1 && compile_heavy_max(nullptr) == 1 && compile_heavy_max("no") == 1); + CHECK(compile_heavy_max("1") == 1 && compile_heavy_max("3") == 3 && compile_heavy_max("0") == UINT_MAX); + std::printf("threads: half the processors, 2 to 8; 1 keeps one thread; one very large build at a time\n"); +} + +void test_lane(unsigned workers) { + const std::size_t lane = workers - 1; + // Large demanded builds: more than there are workers. + { + std::vector> heavy; + Held small, late; + PipelineCompiler pool(workers); + CHECK(pool.threads() == workers); + for (unsigned i = 0; i < workers + 2; ++i) { + heavy.push_back(std::make_unique()); + CHECK(pool.submit(&owners[i], &devices[0], 0, heavy.back()->job(), Size::large)); + } + CHECK(eventually([&] { return count_started(heavy) == lane; })); + settle(); + CHECK(count_started(heavy) == lane); // one worker is kept out of them + // The small demanded build was submitted after all of them, and runs while they are held. + const auto start = std::chrono::steady_clock::now(); + small.go.set(); + CHECK(pool.submit(&owners[40], &devices[0], 0, small.job())); + CHECK(small.done.wait()); + const auto took = std::chrono::duration_cast( + std::chrono::steady_clock::now() - start).count(); + CHECK(count_started(heavy) == lane); + std::printf("lane (%u workers): %zu of %u large builds running, a small one ran past them in %lld ms\n", + workers, lane, workers + 2, static_cast(took)); + // A place that frees goes to the next large build, in the order they came. + heavy[0]->go.set(); + CHECK(heavy[0]->done.wait()); + CHECK(heavy[lane]->started.wait()); + settle(); + CHECK(count_started(heavy) == lane + 1); + for (auto& job : heavy) job->go.set(); + for (auto& job : heavy) CHECK(job->done.wait()); + pool.wait_idle(); + CHECK(pool.stats().completed == workers + 3); + } + // The warm-up is heavy too, and a large demanded build goes before what is left of it. + { + std::vector> warm; + Held small, large; + PipelineCompiler pool(workers); + for (unsigned i = 0; i < workers + 2; ++i) { + warm.push_back(std::make_unique()); + CHECK(pool.submit(&owners[i], &devices[0], 1000 + i, warm.back()->job())); + } + CHECK(eventually([&] { return count_started(warm) == lane; })); + settle(); + CHECK(count_started(warm) == lane); + CHECK(pool.submit(&owners[41], &devices[0], 0, large.job(), Size::large)); + small.go.set(); + CHECK(pool.submit(&owners[40], &devices[0], 0, small.job())); + CHECK(small.done.wait()); + settle(); + CHECK(!large.started.is()); // no place: the free worker is not for it + CHECK(count_started(warm) == lane); + // Smallest first, so the first `lane` of them are the ones running. + warm[0]->go.set(); + CHECK(large.started.wait()); + settle(); + CHECK(count_started(warm) == lane); // the place went to the demanded build + large.go.set(); + for (auto& job : warm) job->go.set(); + for (auto& job : warm) CHECK(job->done.wait()); + pool.wait_idle(); + std::printf("lane (%u workers): %zu speculative builds running, a small demanded one ran past them, a large " + "demanded one took the next place\n", workers, lane); + } +} + +// Very large builds: `limit` of them at a time, demanded or speculative, whatever the workers that are free. The other +// heavy builds and the small ones are not held by that. +void test_huge(unsigned workers, unsigned limit) { + std::vector> huge; + Held large, small, warm; + PipelineCompiler pool(workers, limit); + for (unsigned i = 0; i < limit + 2; ++i) { + huge.push_back(std::make_unique()); + CHECK(pool.submit(&owners[i], &devices[0], 0, huge.back()->job(), Size::huge)); + } + CHECK(pool.submit(&owners[30], &devices[0], 2000000, warm.job(), Size::huge)); // a warm-up of that size + CHECK(eventually([&] { return count_started(huge) == limit; })); + settle(); + CHECK(count_started(huge) == limit && !warm.started.is()); + // A large build that is not very large takes a place in the lane beside them, and a small one runs. + CHECK(pool.submit(&owners[31], &devices[0], 0, large.job(), Size::large)); + small.go.set(); + CHECK(pool.submit(&owners[32], &devices[0], 0, small.job())); + CHECK(small.done.wait()); + CHECK(large.started.wait()); + settle(); + CHECK(count_started(huge) == limit && !warm.started.is()); + // The place of one that ends goes to the next, the demanded ones first. + huge[0]->go.set(); + CHECK(huge[limit]->started.wait()); + settle(); + CHECK(count_started(huge) == limit + 1 && !warm.started.is()); + large.go.set(); + for (auto& job : huge) job->go.set(); + CHECK(warm.started.wait()); + warm.go.set(); + pool.wait_idle(); + std::printf("very large (%u workers, %u at a time): %u of %u demanded and one speculative held back, a large and " + "a small build meanwhile\n", workers, limit, 2u, limit + 2); +} + +// The end of one job lets two start: a small build of its owner and, in the place it leaves, a heavy one. The worker +// that ended it takes the first; another one has to be told of the second. +void test_two_freed(unsigned workers) { + const std::size_t lane = workers - 1; + std::vector> heavy; + Held same_owner, next_heavy; + PipelineCompiler pool(workers); + for (unsigned i = 0; i < lane; ++i) { + heavy.push_back(std::make_unique()); + CHECK(pool.submit(&owners[i], &devices[0], 0, heavy.back()->job(), Size::large)); + CHECK(heavy.back()->started.wait()); + } + CHECK(pool.submit(&owners[0], &devices[0], 0, same_owner.job())); // waits for its owner's build + CHECK(pool.submit(&owners[50], &devices[0], 900, next_heavy.job())); // waits for a place + settle(); + CHECK(!same_owner.started.is() && !next_heavy.started.is()); + heavy[0]->go.set(); + CHECK(same_owner.started.wait()); + CHECK(next_heavy.started.wait()); + same_owner.go.set(); + next_heavy.go.set(); + for (auto& job : heavy) job->go.set(); + pool.wait_idle(); + std::printf("two freed (%u workers): the end of a large build started a small one of its owner and the next " + "heavy one\n", workers); +} + +void test_owner(unsigned workers) { + if (workers > 1) { + std::vector> same; + Held other; + PipelineCompiler pool(workers); + for (unsigned i = 0; i < 3; ++i) { + same.push_back(std::make_unique()); + CHECK(pool.submit(&owners[0], &devices[0], 0, same.back()->job())); + } + other.go.set(); + CHECK(pool.submit(&owners[1], &devices[0], 0, other.job())); + CHECK(other.done.wait()); // behind them in the queue, and not held by them + settle(); + CHECK(count_started(same) == 1 && same[0]->started.is()); + same[0]->go.set(); + CHECK(same[1]->started.wait()); + settle(); + CHECK(count_started(same) == 2); + same[1]->go.set(); + same[2]->go.set(); + CHECK(same[2]->done.wait()); + pool.wait_idle(); + std::printf("owner (%u workers): three jobs of one owner ran one at a time, another owner's meanwhile\n", + workers); + } + // after_running: one job running and two queued. `last` is the PSO's deletion in the runtime. + { + Held running; + std::atomic queued_ran{0}, last_ran{0}; + std::atomic last_after_job{false}; + PipelineCompiler pool(workers); + CHECK(pool.submit(&owners[0], &devices[0], 0, running.job())); + CHECK(running.started.wait()); + CHECK(pool.submit(&owners[0], &devices[0], 0, [&] { ++queued_ran; })); + CHECK(pool.submit(&owners[0], &devices[0], 500, [&] { ++queued_ran; })); + settle(); + const auto before = pool.stats(); + CHECK(pool.after_running(&owners[0], [&] { + last_after_job = running.done.is(); + ++last_ran; + })); + const auto after = pool.stats(); + CHECK(after.dropped == before.dropped + 2 && after.deferred == before.deferred + 1); + settle(); + CHECK(last_ran == 0); + running.go.set(); + CHECK(pool.cancel(&devices[0]) == 0); // a device's teardown: back after the job and after `last` + CHECK(last_ran == 1 && last_after_job && queued_ran == 0); + pool.wait_idle(); + CHECK(!pool.after_running(&owners[0], [&] { ++last_ran; }) && last_ran == 1); // nothing running: not kept + std::printf("owner (%u workers): after_running dropped the two queued jobs and ran `last` once, after the " + "running one\n", workers); + } +} + +void test_checkpoint(unsigned workers) { + Held build, heavy, checkpoint, second, during; + std::atomic waiter_at_start{true}; + PipelineCompiler pool(workers); + CHECK(!pool.has_compile_waiter()); + CHECK(pool.submit(&owners[0], &devices[0], 0, build.job())); + CHECK(build.started.wait()); + CHECK(pool.has_compile_waiter()); // nothing queued, one build running on a worker + CHECK(pool.submit(&devices[0], &devices[0], kCheckpoint, [&] { + waiter_at_start = pool.has_compile_waiter(); + checkpoint.job()(); + })); + settle(); + CHECK(!checkpoint.started.is()); // idle workers, and it waits for the build + CHECK(pool.submit(&owners[1], &devices[0], 700, heavy.job())); + if (workers > 1) CHECK(heavy.started.wait()); + build.go.set(); + CHECK(build.done.wait()); + CHECK(heavy.started.wait()); + settle(); + CHECK(!checkpoint.started.is()); // the speculative build is one too + heavy.go.set(); + CHECK(checkpoint.started.wait()); + CHECK(!waiter_at_start); // nothing queued and nothing running but the checkpoint itself + CHECK(!pool.has_compile_waiter()); + if (workers > 1) { + // A build that comes while the checkpoint runs is not held, and the checkpoint is told. + CHECK(pool.submit(&owners[2], &devices[0], 0, during.job())); + CHECK(during.started.wait()); + CHECK(pool.has_compile_waiter()); + // A checkpoint that comes now waits for that build. + CHECK(pool.submit(&devices[1], &devices[1], kCheckpoint, second.job())); + settle(); + CHECK(!second.started.is()); + during.go.set(); + CHECK(second.started.wait()); + second.go.set(); + } + checkpoint.go.set(); + CHECK(checkpoint.done.wait()); + pool.wait_idle(); + std::printf("checkpoint (%u workers): waited for a demanded and a speculative build, then ran\n", workers); +} + +void test_one_worker() { + Held gate; + std::mutex mutex; + std::string order; + const auto note = [&](char c) { + return [&, c] { + std::lock_guard lock(mutex); + order += c; + }; + }; + PipelineCompiler pool(1); + CHECK(pool.submit(&owners[0], &devices[0], 0, gate.job())); + CHECK(gate.started.wait()); + CHECK(pool.submit(&devices[0], &devices[0], kCheckpoint, note('c'))); + CHECK(pool.submit(&owners[1], &devices[0], 300, note('w'))); + CHECK(pool.submit(&owners[2], &devices[0], 100, note('v'))); + CHECK(pool.submit(&owners[3], &devices[0], 0, note('L'), Size::large)); + CHECK(pool.submit(&owners[4], &devices[0], 0, note('d'))); + CHECK(pool.submit(&owners[2], &devices[0], 0, note('e'))); + settle(); + CHECK(order.empty()); + gate.go.set(); + pool.wait_idle(); + std::printf("one worker: order %s\n", order.c_str()); + CHECK(order == "Ldevwc"); +} + +void test_cancel(unsigned workers) { + // A device's teardown with its jobs running on several workers, and more queued. + { + std::vector> running; + std::atomic queued_ran{0}; + std::atomic returned{false}; + Held other; + PipelineCompiler pool(workers); + for (unsigned i = 0; i < (workers > 1 ? workers - 1 : 1); ++i) { + running.push_back(std::make_unique()); + CHECK(pool.submit(&owners[i], &devices[0], 0, running.back()->job())); + CHECK(running.back()->started.wait()); + } + for (unsigned i = 0; i < 5; ++i) CHECK(pool.submit(&owners[20 + i], &devices[0], 50 + i, [&] { ++queued_ran; })); + if (workers > 1) { + CHECK(pool.submit(&owners[30], &devices[1], 0, other.job())); + CHECK(other.started.wait()); + } + const auto before = pool.stats(); + std::thread teardown([&] { + pool.cancel(&devices[0]); + returned = true; + }); + for (std::size_t i = 0; i < running.size(); ++i) { + settle(); + CHECK(!returned); // one of its jobs is still running + running[i]->go.set(); + } + teardown.join(); + CHECK(pool.stats().waited == before.waited + 1 && queued_ran == 0); + CHECK(!other.done.is()); // the other device's job is not waited for + other.go.set(); + pool.wait_idle(); + std::printf("cancel (%u workers): waited for the device's %zu running jobs, dropped its queued ones\n", workers, + running.size()); + } + // The last release from inside a job: that worker lets itself go, the others are joined. Not destroyed, as the + // process's own is not: the worker that let itself go still returns through it. + { + auto* pool = new PipelineCompiler(workers); + Flag released; + Held neighbour; + pool->retain(); + neighbour.go.set(); + CHECK(pool->submit(&owners[1], &devices[0], 0, neighbour.job())); + CHECK(neighbour.done.wait()); + CHECK(pool->submit(&owners[0], &devices[0], 0, [&] { + pool->release(); + released.set(); + })); + CHECK(released.wait()); + CHECK(!pool->worker_running()); + pool->wait_idle(); + // A device made afterwards gets new workers. + Flag again; + pool->retain(); + CHECK(pool->submit(&owners[0], &devices[0], 0, [&] { again.set(); })); + CHECK(again.wait() && pool->worker_running()); + pool->wait_idle(); + pool->release(); + CHECK(!pool->worker_running()); + std::printf("release (%u workers): from inside a job, then new workers for the next device\n", workers); + } + // Process exit with jobs in the driver: not waited for past the time given, and nothing more is taken. + { + auto* pool = new PipelineCompiler(workers); + std::vector held; // one on every worker; not freed, as the workers that hold them are let go + std::atomic queued_ran{0}; + for (unsigned i = 0; i < workers; ++i) { + held.push_back(new Held); + CHECK(pool->submit(&owners[i], &devices[0], 0, held.back()->job())); + CHECK(held.back()->started.wait()); + } + for (unsigned i = 0; i < 3; ++i) CHECK(pool->submit(&owners[20 + i], &devices[0], 10, [&] { ++queued_ran; })); + CHECK(!pool->stop_for_exit(50ms)); + CHECK(pool->closed() && !pool->worker_running()); + CHECK(!pool->submit(&owners[9], &devices[0], 0, [] {})); + CHECK(pool->stats().refused == 1 && pool->stats().dropped == 3); + for (Held* job : held) job->go.set(); + pool->wait_idle(); + CHECK(queued_ran == 0); + + PipelineCompiler idle(workers); + Flag ran; + CHECK(idle.submit(&owners[0], &devices[0], 0, [&] { ran.set(); })); + CHECK(ran.wait()); + idle.wait_idle(); + CHECK(idle.stop_for_exit(10000ms) && !idle.worker_running()); + std::printf("exit (%u workers): a stop with jobs running gave up after its wait; one with none joined\n", + workers); + } +} + +// Short jobs of every kind from several threads. Each job counts itself in and out. +void test_mixed(unsigned workers) { + constexpr unsigned kOwners = 12; + constexpr unsigned kJobs = 6000; + const int lane = workers > 1 ? int(workers) - 1 : 1; + std::atomic in_owner[kOwners]{}; + std::atomic heavy{0}, huge{0}, all{0}, peak_heavy{0}, peak_all{0}, ran{0}; + std::atomic owner_twice{false}, lane_broken{false}, two_huge{false}; + PipelineCompiler pool(workers, 1); + const auto lift = [](std::atomic& peak, int value) { + int seen = peak.load(); + while (seen < value && !peak.compare_exchange_weak(seen, value)) {} + }; + std::vector submitters; + for (unsigned t = 0; t < 3; ++t) { + submitters.emplace_back([&, t] { + std::uint32_t seed = 12345 + t; + for (unsigned i = t; i < kJobs; i += 3) { + seed = seed * 1664525u + 1013904223u; + const unsigned owner = (seed >> 8) % kOwners; + const unsigned kind = (seed >> 16) % 8; // 0: checkpoint, 1-2: large, 3-4: speculative, 5-7: small + const bool is_huge = kind >= 1 && kind <= 4 && (seed >> 20) % 3 == 0; // a third of the heavy ones + const bool is_heavy = kind >= 1 && kind <= 4; + const std::size_t priority = kind == 0 ? kCheckpoint : kind >= 3 && kind <= 4 ? 100 + (seed >> 24) : 0; + const unsigned spin = (seed >> 4) % 4; + CHECK(pool.submit(&owners[owner], &devices[0], priority, [&, owner, is_heavy, is_huge, spin] { + if (in_owner[owner].fetch_add(1) != 0) owner_twice = true; + if (is_huge && huge.fetch_add(1) != 0) two_huge = true; + lift(peak_all, all.fetch_add(1) + 1); + if (is_heavy) { + const int now = heavy.fetch_add(1) + 1; + if (now > lane) lane_broken = true; + lift(peak_heavy, now); + } + // Long enough to overlap with the others, without the scheduler's 15 ms for a sleep. + if (spin == 0) std::this_thread::yield(); + else if (spin == 1) for (volatile int i = 0; i < 20000; i = i + 1) {} + if (is_heavy) --heavy; + if (is_huge) --huge; + --all; + --in_owner[owner]; + ++ran; + }, is_huge ? Size::huge : kind >= 1 && kind <= 2 ? Size::large : Size::regular)); + if ((seed & 15) == 0) std::this_thread::yield(); + } + }); + } + for (auto& thread : submitters) thread.join(); + pool.wait_idle(); + const auto stats = pool.stats(); + std::printf("mixed (%u workers): %d jobs, at most %d at a time and %d heavy (the lane holds %d)\n", workers, + ran.load(), peak_all.load(), peak_heavy.load(), lane); + CHECK(ran == int(kJobs) && stats.completed == kJobs && stats.dropped == 0); + CHECK(!owner_twice); + CHECK(!lane_broken); + CHECK(!two_huge); + CHECK(peak_all <= int(workers)); +} + +} // namespace + +int main() { + std::setvbuf(stdout, nullptr, _IONBF, 0); // a case that fails or hangs leaves the lines of those before it + std::thread([] { + std::this_thread::sleep_for(120s); + std::fprintf(stderr, "FAIL: not finished after 120 s (a job that never started, or a worker that never came " + "back)\n"); + std::fflush(stderr); + std::_Exit(1); + }).detach(); + test_threads(); + for (const unsigned workers : {2u, 4u, 8u}) test_lane(workers); + for (const unsigned workers : {2u, 4u}) test_two_freed(workers); + test_huge(4, 1); + test_huge(8, 1); + test_huge(8, 2); + for (const unsigned workers : {1u, 4u}) test_owner(workers); + for (const unsigned workers : {1u, 2u, 4u}) test_checkpoint(workers); + test_one_worker(); + for (const unsigned workers : {1u, 4u}) test_cancel(workers); + for (const unsigned workers : {1u, 2u, 4u, 8u}) test_mixed(workers); + std::printf("ok\n"); + return 0; +} diff --git a/runtime/test/replay_pipeline_compiles_test.cpp b/runtime/test/replay_pipeline_compiles_test.cpp index 35b6057edb..167358f52a 100644 --- a/runtime/test/replay_pipeline_compiles_test.cpp +++ b/runtime/test/replay_pipeline_compiles_test.cpp @@ -2,13 +2,16 @@ // 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. +// LEONIDA_STRICT_REPLAY=1, where a dispatch without a pipeline fails its list. Also which large pipelines compile at once +// within a budget (PipelineCompiles::build). No GPU: pipelines and resources are fakes. +#include "../src/large_module_gate.h" #include "../src/pipeline_workers.h" #include "../src/vulkan_replay.h" #include #include #include +#include #include #include #include @@ -39,9 +42,10 @@ T handle(std::uintptr_t 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. +// The large pipelines being built now, and how often there were two, where they are to compile one after another. std::atomic large_now = 0; std::atomic large_together = 0; +std::atomic large_one_at_a_time = true; // What a pipeline state owns: its variants, built on demand under its own lock, and what was asked of it. struct Owner { @@ -60,7 +64,7 @@ struct Owner { 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; + if (++large_now > 1 && large_one_at_a_time) ++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; @@ -84,6 +88,7 @@ struct PipelineSpec { bool fails = false; bool with_built = true; bool large = false; + std::uint64_t estimate = 0; 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 @@ -114,6 +119,7 @@ struct Registry { ComputePipeline p{}; p.layout = handle(7); p.large = spec.large; + p.estimate = spec.estimate; p.async_build = spec.async; p.skipped = spec.skipped; if (spec.bindless) p.bindless_set = handle(6); @@ -138,6 +144,7 @@ struct Registry { } p.mesh = spec.mesh; p.large = spec.large; + p.estimate = spec.estimate; 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); }; @@ -273,12 +280,12 @@ struct Outcome { 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 + std::size_t units = 0; // what run() was given: the large pipelines together are one (no budget) }; // `workers` null: prepare() builds each pipeline itself, as without workers. Outcome prepare_all(const std::vector& lists, const std::vector& specs, - PipelineWorkers* workers) { + PipelineWorkers* workers, const std::function& budget = {}) { Registry registry(specs); ReplayFunctions vk = functions(registry); PipelineCompiles compiles; @@ -294,7 +301,8 @@ Outcome prepare_all(const std::vector& lists, const std::vectorrun(count, job); - }); + }, + budget); 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) { @@ -312,10 +320,13 @@ Outcome prepare_all(const std::vector& lists, const std::vector& specs, - const std::vector>& commands, PipelineWorkers& workers) { + const std::vector>& commands, PipelineWorkers& workers, + const std::function& budget = {}) { const auto lists = record(commands); const Outcome serial = prepare_all(lists, specs, nullptr); - const Outcome together = prepare_all(lists, specs, &workers); + large_one_at_a_time = !budget; + const Outcome together = prepare_all(lists, specs, &workers, budget); + large_one_at_a_time = true; 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) @@ -516,6 +527,7 @@ void random_submissions(PipelineWorkers& workers) { s.with_built = chance(90); s.async = chance(8); s.large = chance(15); + s.estimate = rng() % 12; s.bindless = chance(2); s.skipped = s.compute && chance(4); if (s.skipped) s.fails = s.pending = true; @@ -540,13 +552,278 @@ void random_submissions(PipelineWorkers& workers) { 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; + const std::uint64_t memory = rng() % 24; // 0: no budget + const auto budget = [memory] { return memory; }; + const bool limited = chance(50); + succeeded += compare("random submission " + std::to_string(round), specs, commands, workers, + limited ? std::function(budget) : std::function{}) + .result == ReplayResult::success; } check(succeeded > 1000 && succeeded < 2900, "the random submissions both succeed and fail: " + std::to_string(succeeded)); } +// ---- Large pipelines within a budget. ---- + +// Pipelines that note the order they start in. One with `hold` does not end before `release` is called. +struct Shop { + struct Item { + Shop* shop = nullptr; + ComputePipeline pipeline{}; + std::string name; + bool hold = false; + }; + std::mutex mutex; + std::condition_variable changed; + std::vector started; + std::vector> items; + bool released = false; + int large_in = 0, most_large_in = 0; + LargeModuleGate* gate = nullptr; // set: a large one takes its place there, as in the layer + + ComputePipeline& add(const std::string& name, std::uint64_t estimate, bool large, bool hold = false) { + auto& item = *items.emplace_back(std::make_unique()); + item.shop = this; + item.name = name; + item.hold = hold; + item.pipeline.large = large; + item.pipeline.estimate = estimate; + item.pipeline.build_context = &item; + item.pipeline.build = [](void* context) { + auto& i = *static_cast(context); + Shop& shop = *i.shop; + LargeModuleGate::Ticket place; + if (shop.gate && i.pipeline.large) place = LargeModuleGate::Ticket(*shop.gate, i.pipeline.estimate); + std::unique_lock lock(shop.mutex); + shop.started.push_back(i.name); + if (i.pipeline.large) shop.most_large_in = std::max(shop.most_large_in, ++shop.large_in); + shop.changed.notify_all(); + if (i.hold) shop.changed.wait_for(lock, std::chrono::seconds(10), [&] { return shop.released; }); + if (i.pipeline.large) --shop.large_in; + return handle(std::uintptr_t(&i) | 1); + }; + return item.pipeline; + } + void fill(PipelineCompiles& compiles) { + for (auto& item : items) compiles.add(item->pipeline, PipelineCompiles::User::dispatch); + } + // Whether `count` have started, within 10 s. + bool wait_started(std::size_t count) { + std::unique_lock lock(mutex); + return changed.wait_for(lock, std::chrono::seconds(10), [&] { return started.size() >= count; }); + } + void release() { + std::lock_guard lock(mutex); + released = true; + changed.notify_all(); + } +}; + +// On `threads` threads, which take the jobs in order. +void on_threads(unsigned threads, std::size_t count, const std::function& job) { + std::atomic next = 0; + std::vector workers; + for (unsigned t = 0; t < threads; ++t) + workers.emplace_back([&] { + for (std::size_t i; (i = next++) < count;) job(i); + }); + for (auto& w : workers) w.join(); +} + +using Names = std::vector; + +// The order and the jobs of the run, on one thread: the largest first, then the others, and the budget read once. +void budget_order() { + struct Case { + std::vector large; + std::uint64_t budget; + std::size_t lanes; + Names order; // of the large ones + }; + for (const Case& c : {Case{{5, 2, 3, 2, 1}, 5, 3, {"5", "3", "2", "2", "1"}}, + Case{{5, 2, 3, 2, 1}, 4, 2, {"5", "3", "2", "2", "1"}}, + Case{{5, 2, 3, 2, 1}, 0, 1, {"5", "2", "3", "2", "1"}}, // no budget: in the order they came + Case{{5, 2, 3, 2, 1}, 100, 5, {"5", "3", "2", "2", "1"}}, + Case{{9}, 5, 1, {"9"}}, // more than the budget: one, alone + Case{{9, 9}, 5, 1, {"9", "9"}}, + Case{{9, 1}, 5, 1, {"9", "1"}}, + Case{{4, 4}, 8, 2, {"4", "4"}}}) { + Shop shop; + for (const auto size : c.large) shop.add(std::to_string(size), size, true); + for (int i = 0; i < 3; ++i) shop.add("s" + std::to_string(i), 0, false); + PipelineCompiles compiles; + shop.fill(compiles); + std::size_t units = 0; + unsigned reads = 0; + compiles.build([&](std::size_t count, const std::function& job) { + units = count; + for (std::size_t i = 0; i < count; ++i) job(i); + }, [&] { ++reads; return c.budget; }); + Names want = c.order; + for (int i = 0; i < 3; ++i) want.push_back("s" + std::to_string(i)); + const std::string name = "budget " + std::to_string(c.budget) + " of " + std::to_string(c.large.size()); + check(shop.started == want, name + ": another order"); + check(units == c.lanes + 3, name + ": " + std::to_string(units) + " jobs, not " + std::to_string(c.lanes + 3)); + check(reads == 1, name + ": the budget read " + std::to_string(reads) + " times"); + for (std::size_t i = 0; i < shop.items.size(); ++i) + check(compiles.built(PipelineCompiles::Ticket(i + 1)) != VK_NULL_HANDLE, name + ": not built"); + } + // Without a large pipeline the budget is not read, and the jobs are the pipelines. + Shop shop; + for (int i = 0; i < 3; ++i) shop.add("s" + std::to_string(i), 0, false); + PipelineCompiles compiles; + shop.fill(compiles); + std::size_t units = 0; + unsigned reads = 0; + compiles.build([&](std::size_t count, const std::function& job) { + units = count; + for (std::size_t i = 0; i < count; ++i) job(i); + }, [&] { ++reads; return 100u; }); + check(units == 3 && reads == 0, "the budget read for pipelines that are not large"); +} + +// A large one that does not fit beside the one in is not waited for while others are left: they come first. +void budget_others_first() { + Shop shop; + shop.add("8", 8, true, true); + shop.add("4a", 4, true); + shop.add("4b", 4, true); + for (int i = 0; i < 3; ++i) shop.add("s" + std::to_string(i), 0, false); + PipelineCompiles compiles; + shop.fill(compiles); + std::thread building([&] { + compiles.build([&](std::size_t count, const std::function& job) { + check(count == 2 + 3, "two lanes: the two of 4 fit 8 together"); + on_threads(2, count, job); + }, [] { return 8; }); + }); + const bool all = shop.wait_started(6); // "8" is held: the other lane does the rest + Names seen; + { + std::lock_guard lock(shop.mutex); + seen = shop.started; + } + shop.release(); + building.join(); + check(all && seen.size() == 6 && seen[0] == "8", "the large one first"); + check(all && std::set(seen.begin() + 1, seen.begin() + 4) == std::set{"s0", "s1", "s2"}, + "the others before the large ones that do not fit"); + check(all && seen[4] == "4a" && seen[5] == "4b", "then the next large ones"); +} + +// Those that fit together start together, before the others. +void budget_fits_together() { + Shop shop; + shop.add("3", 3, true, true); + shop.add("5", 5, true, true); + for (int i = 0; i < 2; ++i) shop.add("s" + std::to_string(i), 0, false); + PipelineCompiles compiles; + shop.fill(compiles); + std::thread building([&] { + compiles.build([&](std::size_t count, const std::function& job) { on_threads(2, count, job); }, + [] { return 8; }); + }); + const bool both = shop.wait_started(2); + Names seen; + { + std::lock_guard lock(shop.mutex); + seen = shop.started; + } + shop.release(); + building.join(); + check(both && std::set(seen.begin(), seen.begin() + 2) == std::set{"3", "5"}, + "two that fit the budget are in together"); + check(shop.most_large_in == 2, "two that fit the budget at once"); +} + +// The room that a large one leaves is the next large one's, before the others. +void budget_room_is_given_back() { + Shop shop; + shop.add("5", 5, true, true); + for (const char* name : {"3a", "3b", "3c"}) shop.add(name, 3, true); + for (int i = 0; i < 3; ++i) shop.add("s" + std::to_string(i), 0, false); + PipelineCompiles compiles; + shop.fill(compiles); + std::thread building([&] { + compiles.build([&](std::size_t count, const std::function& job) { + check(count == 2 + 3, "two lanes: two of 3 fit 8, three do not"); + on_threads(2, count, job); + }, [] { return 8; }); + }); + const bool all = shop.wait_started(7); // "5" is held: the other lane has room for one of 3 at a time + Names seen; + { + std::lock_guard lock(shop.mutex); + seen = shop.started; + } + shop.release(); + building.join(); + check(all && Names(seen.begin(), seen.begin() + 4) == Names{"5", "3a", "3b", "3c"}, + "a large one does not leave its room"); +} + +// Graphics and compute pipelines share the budget: what each is expected to take counts alike. +void budget_graphics_and_compute() { + Shop shop; + shop.add("3", 3, true); + shop.add("4", 4, true); + GraphicsPipeline graphics{}; + graphics.large = true; + graphics.estimate = 5; + graphics.variant = [&](std::uint32_t) { + std::lock_guard lock(shop.mutex); + shop.started.push_back("5"); + return handle(5); + }; + PipelineCompiles compiles; + shop.fill(compiles); + compiles.add(graphics, 0); + std::size_t units = 0; + compiles.build([&](std::size_t count, const std::function& job) { + units = count; + for (std::size_t i = 0; i < count; ++i) job(i); + }, [] { return 8; }); + check(shop.started == Names{"5", "4", "3"}, "the largest first, graphics or compute"); + check(units == 2, "3 and 4 fit 8, and 5 does not beside them"); +} + +// The lanes are no more than could be in: a thread is not kept waiting for room there is none of. +void budget_lanes_are_bounded() { + Shop shop; + for (int i = 0; i < 3; ++i) shop.add("5" + std::to_string(i), 5, true); + for (int i = 0; i < 6; ++i) shop.add("s" + std::to_string(i), 0, false); + PipelineCompiles compiles; + shop.fill(compiles); + compiles.build([&](std::size_t count, const std::function& job) { + check(count == 2 + 6, "10 bytes hold two of 5"); + on_threads(4, count, job); + }, [] { return 10; }); + check(shop.started.size() == 9 && shop.most_large_in <= 2, "no more than two large ones at once"); +} + +// Every one of them is built once, with the gate of the runtime holding what does not fit, whatever sizes and budget. +void budget_random(PipelineWorkers& workers) { + std::mt19937 rng(20251127); + for (int round = 0; round < 300; ++round) { + Shop shop; + const std::uint64_t budget = rng() % 20; + LargeModuleGate gate([budget] { return budget; }); + shop.gate = &gate; + const unsigned large = rng() % 10, others = rng() % 10; + for (unsigned i = 0; i < large; ++i) shop.add("l" + std::to_string(i), rng() % 12, true); + for (unsigned i = 0; i < others; ++i) shop.add("s" + std::to_string(i), 0, false); + PipelineCompiles compiles; + shop.fill(compiles); + compiles.build([&](std::size_t count, const std::function& job) { workers.run(count, job); }, + [budget] { return budget; }); + Names names = shop.started; + std::sort(names.begin(), names.end()); + check(std::adjacent_find(names.begin(), names.end()) == names.end() && names.size() == large + others, + "random budget " + std::to_string(round) + ": a pipeline built twice or not at all"); + check(gate.inflight() == 0, "random budget " + std::to_string(round) + ": a place not given back"); + } +} + } // namespace int main() { @@ -556,7 +833,14 @@ int main() { if (threads) many(workers); reused_lists(workers); random_submissions(workers); + budget_random(workers); } + budget_order(); + budget_others_first(); + budget_fits_together(); + budget_room_is_given_back(); + budget_graphics_and_compute(); + budget_lanes_are_bounded(); check(large_together == 0, "two large pipelines were built at once"); if (failures) return 1; std::printf("replay_pipeline_compiles_test: passed\n");