upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime
diff options
context:
space:
mode:
authorJan Trencansky <jan.trencansky@protonmail.com>2026-11-25 17:11:38 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-25 17:11:38 -0500
commitca9e45dbd136feae14936ffbbe300d18bcda48c7 (patch)
treed6cad81523cd0cbdd774b9d6c1c597584055d1ec /runtime
parentb8c925002c6b4a6bfb5cfad6e7cc60ce2414586e (diff)
parentd3b8251bc390418cdbc1f2d30727b6b31d889cfa (diff)
Merge main into pe-inspect-linux-classes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime')
-rw-r--r--runtime/CMakeLists.txt38
-rw-r--r--runtime/README.md3
-rw-r--r--runtime/shims/d3d12_vulkan_device.cpp96
-rw-r--r--runtime/src/gfx10_descriptors.h10
-rw-r--r--runtime/src/large_module_gate.h293
-rw-r--r--runtime/src/vulkan_backend.h17
-rw-r--r--runtime/src/vulkan_replay.h74
-rw-r--r--runtime/test/big_compile_gate_test.cpp532
-rw-r--r--runtime/test/big_compute_module.h298
-rw-r--r--runtime/test/d3d12_big_compute_test.cpp978
-rw-r--r--runtime/test/gfx10_descriptors_test.cpp19
-rw-r--r--runtime/test/large_module_gate.h181
-rw-r--r--runtime/test/replay_pipeline_compiles_test.cpp306
13 files changed, 2619 insertions, 226 deletions
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index 390529c41..bea9a82d8 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -793,6 +793,12 @@ if(BUILD_TESTING)
793 add_executable(xdxr_build_output_test test/xdxr_build_output_test.cpp) 793 add_executable(xdxr_build_output_test test/xdxr_build_output_test.cpp)
794 add_test(NAME xdxr_build_output COMMAND xdxr_build_output_test) 794 add_test(NAME xdxr_build_output COMMAND xdxr_build_output_test)
795 795
796 # The gate of large_module_gate.h as the runtime uses it for large pipelines (LEONIDA_BIG_COMPILE_BUDGET_MB): pure
797 # stdlib.
798 add_executable(big_compile_gate_test test/big_compile_gate_test.cpp)
799 target_link_libraries(big_compile_gate_test PRIVATE Threads::Threads)
800 add_test(NAME big_compile_gate COMMAND big_compile_gate_test)
801 set_tests_properties(big_compile_gate PROPERTIES TIMEOUT 120)
796 # vk_pipeline_check's memory budget for large modules: pure stdlib, no Vulkan device. 802 # vk_pipeline_check's memory budget for large modules: pure stdlib, no Vulkan device.
797 add_executable(large_module_gate_test test/large_module_gate_test.cpp) 803 add_executable(large_module_gate_test test/large_module_gate_test.cpp)
798 find_package(Threads REQUIRED) 804 find_package(Threads REQUIRED)
@@ -2387,8 +2393,38 @@ if(TARGET Vulkan::Headers)
2387 add_test(NAME d3d12_pipeline_workers_eager COMMAND d3d12_pipeline_workers_test) 2393 add_test(NAME d3d12_pipeline_workers_eager COMMAND d3d12_pipeline_workers_test)
2388 set_tests_properties(d3d12_pipeline_workers d3d12_pipeline_workers_eager PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 180 2394 set_tests_properties(d3d12_pipeline_workers d3d12_pipeline_workers_eager PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 180
2389 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") 2395 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-")
2396 # One large pipeline after another: the jobs of the pool are then known (d3d12_big_compute has the budget).
2397 set_tests_properties(d3d12_pipeline_workers PROPERTIES ENVIRONMENT "LEONIDA_SERIAL_BIG_COMPILES=1")
2390 set_tests_properties(d3d12_pipeline_workers_eager PROPERTIES 2398 set_tests_properties(d3d12_pipeline_workers_eager PROPERTIES
2391 ENVIRONMENT "LEONIDA_LAZY_PIPELINES=0;LEONIDA_LAZY_COMPUTE=0") 2399 ENVIRONMENT "LEONIDA_LAZY_PIPELINES=0;LEONIDA_LAZY_COMPUTE=0;LEONIDA_SERIAL_BIG_COMPILES=1")
2400 # Large pipelines compiled within a memory budget, with real large compute modules: the same values for each setting
2401 # (read once for each process). 260 MiB holds three of the modules, 1 MiB none. The modules' compile runs on the test's
2402 # threads, so they get the loader's stack (docs/pipeline_check.md, "Stack reserve").
2403 add_executable(d3d12_big_compute_test test/d3d12_big_compute_test.cpp)
2404 target_link_libraries(d3d12_big_compute_test PRIVATE gta6rt_d3d12_com)
2405 target_compile_definitions(d3d12_big_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
2406 target_compile_options(d3d12_big_compute_test PRIVATE /W4 /permissive- /utf-8)
2407 target_link_options(d3d12_big_compute_test PRIVATE /STACK:${GTA6RT_STACK})
2408 add_test(NAME d3d12_big_compute COMMAND d3d12_big_compute_test)
2409 add_test(NAME d3d12_big_compute_budget COMMAND d3d12_big_compute_test)
2410 add_test(NAME d3d12_big_compute_tight COMMAND d3d12_big_compute_test)
2411 add_test(NAME d3d12_big_compute_serial COMMAND d3d12_big_compute_test)
2412 add_test(NAME d3d12_big_compute_unlimited COMMAND d3d12_big_compute_test)
2413 add_test(NAME d3d12_big_compute_warmup COMMAND d3d12_big_compute_test warmup)
2414 add_test(NAME d3d12_big_compute_eager COMMAND d3d12_big_compute_test eager)
2415 set_tests_properties(d3d12_big_compute d3d12_big_compute_budget d3d12_big_compute_tight d3d12_big_compute_serial
2416 d3d12_big_compute_unlimited d3d12_big_compute_warmup d3d12_big_compute_eager
2417 PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600
2418 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-")
2419 set_tests_properties(d3d12_big_compute_budget PROPERTIES ENVIRONMENT "LEONIDA_BIG_COMPILE_BUDGET_MB=260")
2420 set_tests_properties(d3d12_big_compute_tight d3d12_big_compute_warmup PROPERTIES
2421 ENVIRONMENT "LEONIDA_BIG_COMPILE_BUDGET_MB=1")
2422 set_tests_properties(d3d12_big_compute_eager PROPERTIES
2423 ENVIRONMENT "LEONIDA_BIG_COMPILE_BUDGET_MB=1;LEONIDA_LAZY_COMPUTE=0")
2424 set_tests_properties(d3d12_big_compute_serial PROPERTIES # neither of these two has a budget
2425 ENVIRONMENT "LEONIDA_SERIAL_BIG_COMPILES=1;LEONIDA_BIG_COMPILE_BUDGET_MB=4096")
2426 set_tests_properties(d3d12_big_compute_unlimited PROPERTIES
2427 ENVIRONMENT "LEONIDA_SERIAL_BIG_COMPILES=0;LEONIDA_BIG_COMPILE_BUDGET_MB=1")
2392 # ExecuteCommandLists refuses a list whose type isn't the queue's (debug-layer message 836). 2428 # ExecuteCommandLists refuses a list whose type isn't the queue's (debug-layer message 836).
2393 add_executable(d3d12_queue_list_type_test test/d3d12_queue_list_type_test.cpp) 2429 add_executable(d3d12_queue_list_type_test test/d3d12_queue_list_type_test.cpp)
2394 target_link_libraries(d3d12_queue_list_type_test PRIVATE gta6rt_d3d12_com) 2430 target_link_libraries(d3d12_queue_list_type_test PRIVATE gta6rt_d3d12_com)
diff --git a/runtime/README.md b/runtime/README.md
index b89a82a71..16cd4f154 100644
--- a/runtime/README.md
+++ b/runtime/README.md
@@ -321,7 +321,8 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w
321| `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. | 321| `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. |
322| `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`. | 322| `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`. |
323| `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. | 323| `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. |
324| `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. | 324| `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. |
325| `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. |
325| `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. | 326| `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. |
326| `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). | 327| `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). |
327| `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. | 328| `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_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp
index a743344c5..e424e1d0f 100644
--- a/runtime/shims/d3d12_vulkan_device.cpp
+++ b/runtime/shims/d3d12_vulkan_device.cpp
@@ -46,6 +46,7 @@
46#include "../src/pipeline_profile.h" 46#include "../src/pipeline_profile.h"
47#include "../src/submit_phases.h" 47#include "../src/submit_phases.h"
48#include "../src/pipeline_cache_store.h" 48#include "../src/pipeline_cache_store.h"
49#include "../src/large_module_gate.h"
49#include "../src/conservative_raster.h" 50#include "../src/conservative_raster.h"
50#include "../src/resource_detile.h" 51#include "../src/resource_detile.h"
51#include "../src/console_texture_layout.h" 52#include "../src/console_texture_layout.h"
@@ -1403,14 +1404,39 @@ bool console_format_stand_ins() {
1403 return on; 1404 return on;
1404} 1405}
1405 1406
1406// A driver's compiler needs hundreds of MiB for a very large module; several at once exhausted host memory. Compute modules 1407// A driver's compiler needs hundreds of MiB for a very large module; several at once exhausted host memory. Large are
1407// over 128 KiB compile one at a time (LEONIDA_SERIAL_BIG_COMPILES=0: as many as are asked for). 1408// compute modules over 128 KiB and graphics pipelines of PipelineCompiles::large_spirv_bytes or more. They compile side by
1408bool serial_big_compile(std::size_t spirv_bytes) { 1409// side while their estimates fit the memory that is free (big_compile_gate). LEONIDA_SERIAL_BIG_COMPILES=1: one at a time,
1409 static const bool serial = [] { 1410// as before there was a budget (graphics: one after another in each submission). 0: as many as are asked for.
1411enum class BigCompiles { budget, serial, unlimited };
1412BigCompiles big_compiles() {
1413 static const BigCompiles mode = [] {
1410 wchar_t v[2]{}; 1414 wchar_t v[2]{};
1411 return !(GetEnvironmentVariableW(L"LEONIDA_SERIAL_BIG_COMPILES", v, 2) == 1 && v[0] == L'0'); 1415 const DWORD n = GetEnvironmentVariableW(L"LEONIDA_SERIAL_BIG_COMPILES", v, 2);
1416 if (n == 0) return BigCompiles::budget;
1417 return n == 1 && v[0] == L'0' ? BigCompiles::unlimited : BigCompiles::serial;
1412 }(); 1418 }();
1413 return serial && spirv_bytes > 128 * 1024; 1419 return mode;
1420}
1421bool big_compute(std::size_t spirv_bytes) { return spirv_bytes > 128 * 1024; }
1422
1423// Where large compiles wait for memory: one for the process, as the memory is the machine's. Never destroyed: static
1424// destruction must not race the compile worker.
1425leonida::LargeModuleGate& big_compile_gate() {
1426 static auto* const gate = [] {
1427 char text[32]{};
1428 std::size_t length = 0;
1429 const bool present = getenv_s(&length, text, "LEONIDA_BIG_COMPILE_BUDGET_MB") == 0 && length > 1;
1430 const auto setting = leonida::large_compile_budget(present ? text : "");
1431 if (!setting.valid)
1432 std::fprintf(stderr, "[rt] d3d12: LEONIDA_BIG_COMPILE_BUDGET_MB=%s is not a number; not used\n", text);
1433 auto budget = [fixed = setting.fixed] { return fixed ? *fixed : leonida::large_compile_budget_bytes(); };
1434 std::fprintf(stderr, "[rt] d3d12: large pipelines compile side by side within %llu MiB (%s)\n",
1435 static_cast<unsigned long long>(budget() >> 20),
1436 setting.fixed ? "LEONIDA_BIG_COMPILE_BUDGET_MB" : "3/4 of the memory free now");
1437 return new leonida::LargeModuleGate(std::move(budget));
1438 }();
1439 return *gate;
1414} 1440}
1415 1441
1416bool startup_cache_checkpoints_enabled() { 1442bool startup_cache_checkpoints_enabled() {
@@ -4696,12 +4722,10 @@ struct DeviceState {
4696 } 4722 }
4697 } 4723 }
4698 view_info.components = g::vulkan_swizzle(swizzle, channels_format); 4724 view_info.components = g::vulkan_swizzle(swizzle, channels_format);
4699 // The cast: MSVC's enums are ints, and it rejects int to VkImageAspectFlags in braces as narrowing. 4725 view_info.subresourceRange = g::vulkan_subresource_range(
4700 view_info.subresourceRange = { 4726 image, stencil ? VK_IMAGE_ASPECT_STENCIL_BIT
4701 VkImageAspectFlags(stencil ? VK_IMAGE_ASPECT_STENCIL_BIT 4727 : (aspects & VK_IMAGE_ASPECT_DEPTH_BIT) ? VK_IMAGE_ASPECT_DEPTH_BIT
4702 : (aspects & VK_IMAGE_ASPECT_DEPTH_BIT) ? VK_IMAGE_ASPECT_DEPTH_BIT 4728 : VK_IMAGE_ASPECT_COLOR_BIT);
4703 : VK_IMAGE_ASPECT_COLOR_BIT),
4704 image.first_mip, image.mip_count, image.first_layer, image.layer_count};
4705 ImageEntry entry{dimension, 0, VK_NULL_HANDLE, VK_NULL_HANDLE, image.address}; 4729 ImageEntry entry{dimension, 0, VK_NULL_HANDLE, VK_NULL_HANDLE, image.address};
4706 if (sampled) { 4730 if (sampled) {
4707 const VkResult result = vk.vkCreateImageView(info.device, &view_info, nullptr, &entry.sampled); 4731 const VkResult result = vk.vkCreateImageView(info.device, &view_info, nullptr, &entry.sampled);
@@ -8983,7 +9007,9 @@ public:
8983 const auto it = variants_.find(unbound); 9007 const auto it = variants_.find(unbound);
8984 return it == variants_.end() ? VkPipeline(VK_NULL_HANDLE) : it->second; 9008 return it == variants_.end() ? VkPipeline(VK_NULL_HANDLE) : it->second;
8985 }; 9009 };
8986 graphics_.large = spirv_bytes >= leonida::PipelineCompiles::large_spirv_bytes; 9010 graphics_.large = spirv_bytes >= leonida::PipelineCompiles::large_spirv_bytes &&
9011 big_compiles() != BigCompiles::unlimited;
9012 graphics_.estimate = leonida::large_module_estimate(spirv_bytes);
8987 9013
8988 if (code_stage) { 9014 if (code_stage) {
8989 VkDeviceSize offset = 0; 9015 VkDeviceSize offset = 0;
@@ -9113,6 +9139,7 @@ public:
9113 if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &pipeline_.layout) != VK_SUCCESS) return E_FAIL; 9139 if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &pipeline_.layout) != VK_SUCCESS) return E_FAIL;
9114 compute_entry_ = entry; 9140 compute_entry_ = entry;
9115 stage_bytes_ = spirv_bytes; 9141 stage_bytes_ = spirv_bytes;
9142 pipeline_.estimate = leonida::large_module_estimate(spirv_bytes);
9116 // The title creates hundreds of compute pipelines from job threads during startup and one of its init tasks 9143 // The title creates hundreds of compute pipelines from job threads during startup and one of its init tasks
9117 // waits for all of them; some modules (wave64-emulated ray-tracing resolves, 4 MiB of SPIR-V) take the driver 9144 // waits for all of them; some modules (wave64-emulated ray-tracing resolves, 4 MiB of SPIR-V) take the driver
9118 // minutes each. So the Vulkan pipeline is built on first use (build_compute): at the first dispatch that names 9145 // minutes each. So the Vulkan pipeline is built on first use (build_compute): at the first dispatch that names
@@ -9148,7 +9175,7 @@ public:
9148 std::unique_lock lock(pso->variants_mutex_, std::try_to_lock); // held: another thread is compiling it 9175 std::unique_lock lock(pso->variants_mutex_, std::try_to_lock); // held: another thread is compiling it
9149 return lock.owns_lock() ? pso->pipeline_.pipeline : VkPipeline(VK_NULL_HANDLE); 9176 return lock.owns_lock() ? pso->pipeline_.pipeline : VkPipeline(VK_NULL_HANDLE);
9150 }; 9177 };
9151 pipeline_.large = serial_big_compile(spirv_bytes); 9178 pipeline_.large = big_compute(spirv_bytes) && big_compiles() != BigCompiles::unlimited;
9152 } else if (!build_compute("compute-create")) { 9179 } else if (!build_compute("compute-create")) {
9153 return E_FAIL; 9180 return E_FAIL;
9154 } 9181 }
@@ -9169,12 +9196,32 @@ public:
9169 } 9196 }
9170 9197
9171private: 9198private:
9199 using Work = leonida::LargeModuleGate::Work;
9200
9201 // Locks the PSO (`lock`, on variants_mutex_) for a build and, with an `estimate`, takes the build's place at the gate. A
9202 // thread that waits for its place holds no PSO's lock, and one that has its place waits for none: another thread may be
9203 // building that PSO, with a place of its own. Returns without a place when the PSO is `built` already.
9204 template<typename Built>
9205 leonida::LargeModuleGate::Ticket enter_build(std::unique_lock<std::mutex>& lock, std::uint64_t estimate, Work work,
9206 Built&& built) {
9207 for (;;) {
9208 lock.lock();
9209 if (!estimate || built()) return {};
9210 lock.unlock();
9211 leonida::LargeModuleGate::Ticket place(big_compile_gate(), estimate, work);
9212 if (lock.try_lock()) return place;
9213 }
9214 }
9215
9172 // The compute pipeline, built once: by create_compute (LEONIDA_LAZY_COMPUTE=0), by the first dispatch that names 9216 // The compute pipeline, built once: by create_compute (LEONIDA_LAZY_COMPUTE=0), by the first dispatch that names
9173 // it (the replay layer calls ComputePipeline::build) or by the warm-up thread. Null when it cannot be built; the 9217 // it (the replay layer calls ComputePipeline::build) or by the warm-up thread. Null when it cannot be built; the
9174 // failure is logged and not retried. 9218 // failure is logged and not retried.
9175 VkPipeline build_compute(const char* trigger) { 9219 VkPipeline build_compute(const char* trigger, Work work = Work::demand) {
9176 CompileActivity activity(device_.active_compiles); 9220 CompileActivity activity(device_.active_compiles);
9177 std::lock_guard lock(variants_mutex_); 9221 std::unique_lock lock(variants_mutex_, std::defer_lock);
9222 const bool budgeted = big_compute(stage_bytes_) && big_compiles() == BigCompiles::budget;
9223 auto place = enter_build(lock, budgeted ? pipeline_.estimate : 0, work,
9224 [this] { return pipeline_.pipeline || compute_failed_; });
9178 if (pipeline_.pipeline || compute_failed_) return pipeline_.pipeline; 9225 if (pipeline_.pipeline || compute_failed_) return pipeline_.pipeline;
9179 compute_failed_ = true; // until the pipeline exists 9226 compute_failed_ = true; // until the pipeline exists
9180 auto& vk = device_.context->vk; 9227 auto& vk = device_.context->vk;
@@ -9184,7 +9231,7 @@ private:
9184 if (!library || !entry) return VK_NULL_HANDLE; 9231 if (!library || !entry) return VK_NULL_HANDLE;
9185 static std::mutex big_compile; 9232 static std::mutex big_compile;
9186 std::unique_lock<std::mutex> big_lock(big_compile, std::defer_lock); 9233 std::unique_lock<std::mutex> big_lock(big_compile, std::defer_lock);
9187 if (serial_big_compile(stage_bytes_)) big_lock.lock(); 9234 if (big_compute(stage_bytes_) && big_compiles() == BigCompiles::serial) big_lock.lock();
9188 auto words = library->spirv(*entry); 9235 auto words = library->spirv(*entry);
9189 if (words.empty()) { 9236 if (words.empty()) {
9190 std::fprintf(stderr, "[rt] d3d12: %s.spv is missing or not SPIR-V\n", entry->name.c_str()); 9237 std::fprintf(stderr, "[rt] d3d12: %s.spv is missing or not SPIR-V\n", entry->name.c_str());
@@ -9219,6 +9266,7 @@ private:
9219 profile.finish(int(created)); 9266 profile.finish(int(created));
9220 trace.end(trigger, entry->name.c_str(), 0, bytes, created); 9267 trace.end(trigger, entry->name.c_str(), 0, bytes, created);
9221 if (big_lock.owns_lock()) big_lock.unlock(); 9268 if (big_lock.owns_lock()) big_lock.unlock();
9269 place.release();
9222 vk.vkDestroyShaderModule(dev, module, nullptr); // Vulkan lets a module go once the pipeline exists 9270 vk.vkDestroyShaderModule(dev, module, nullptr); // Vulkan lets a module go once the pipeline exists
9223 const ULONGLONG took = GetTickCount64() - started; 9271 const ULONGLONG took = GetTickCount64() - started;
9224 if (created != VK_SUCCESS || !built) { 9272 if (created != VK_SUCCESS || !built) {
@@ -9283,7 +9331,8 @@ private:
9283 queued = PipelineCompiler::instance().submit(compile_owner(), &device_, warm_bytes, [this, compute, warm, unbound] { 9331 queued = PipelineCompiler::instance().submit(compile_owner(), &device_, warm_bytes, [this, compute, warm, unbound] {
9284 VkPipeline built{}; 9332 VkPipeline built{};
9285 try { 9333 try {
9286 built = compute ? build_compute(warm ? "warmup" : "dispatch-worker") 9334 built = compute ? build_compute(warm ? "warmup" : "dispatch-worker",
9335 warm ? Work::speculative : Work::demand)
9287 : variant(unbound, "draw-worker"); 9336 : variant(unbound, "draw-worker");
9288 if (async_replay_compile()) { 9337 if (async_replay_compile()) {
9289 unsigned long long skipped = 0; 9338 unsigned long long skipped = 0;
@@ -9607,7 +9656,10 @@ private:
9607 9656
9608 // Built on first use and kept until the PSO is released (replay may call this from any queue). 9657 // Built on first use and kept until the PSO is released (replay may call this from any queue).
9609 VkPipeline variant(std::uint32_t unbound, const char* trigger) { 9658 VkPipeline variant(std::uint32_t unbound, const char* trigger) {
9610 std::lock_guard lock(variants_mutex_); 9659 std::unique_lock lock(variants_mutex_, std::defer_lock);
9660 const bool budgeted = graphics_.large && big_compiles() == BigCompiles::budget;
9661 const auto place = enter_build(lock, budgeted ? graphics_.estimate : 0, Work::demand,
9662 [&] { return variants_.contains(unbound); });
9611 if (const auto it = variants_.find(unbound); it != variants_.end()) return it->second; 9663 if (const auto it = variants_.find(unbound); it != variants_.end()) return it->second;
9612 const VkPipeline pipeline = build(unbound, trigger); 9664 const VkPipeline pipeline = build(unbound, trigger);
9613 if (!pipeline) { 9665 if (!pipeline) {
@@ -10323,6 +10375,8 @@ TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWord
10323 std::lock_guard lock(device.descriptor_mutex); 10375 std::lock_guard lock(device.descriptor_mutex);
10324 if (!device.bindless) return refuse("no bindless set"); 10376 if (!device.bindless) return refuse("no bindless set");
10325 if (device.image_entries.count(words)) return TitleImage::known; 10377 if (device.image_entries.count(words)) return TitleImage::known;
10378 if (g::has_hardware_volume_uav_slice_offset(words, image))
10379 return refuse("a title-written 3D UAV with a slice offset is not supported");
10326 auto found = device.images_by_address.find(image.address); 10380 auto found = device.images_by_address.find(image.address);
10327 // Memory of the texture stream pool has two addresses, the CPU view's and the GPU-only alias the title hands 10381 // Memory of the texture stream pool has two addresses, the CPU view's and the GPU-only alias the title hands
10328 // to the GPU (title_gpu_views): a T# naming either finds a texture registered under the other. 10382 // to the GPU (title_gpu_views): a T# naming either finds a texture registered under the other.
@@ -11007,6 +11061,10 @@ public:
11007 threads.count); 11061 threads.count);
11008 if (threads.count) 11062 if (threads.count)
11009 state_.context->set_pipeline_workers(std::make_unique<leonida::PipelineWorkers>(threads.count)); 11063 state_.context->set_pipeline_workers(std::make_unique<leonida::PipelineWorkers>(threads.count));
11064 if (big_compiles() == BigCompiles::budget)
11065 state_.context->set_large_compiles(
11066 [] { return big_compile_gate().budget(); },
11067 [] { return std::make_shared<leonida::LargeModuleGate::Demand>(big_compile_gate()); });
11010 } 11068 }
11011 leonida::title_va_aliases().set_hooks( 11069 leonida::title_va_aliases().set_hooks(
11012 &state_, 11070 &state_,
diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h
index 219e0a8c5..acfa590f8 100644
--- a/runtime/src/gfx10_descriptors.h
+++ b/runtime/src/gfx10_descriptors.h
@@ -236,6 +236,16 @@ inline constexpr VkImageViewType vulkan_view_type(ImageType type) {
236 } 236 }
237} 237}
238 238
239inline constexpr VkImageSubresourceRange vulkan_subresource_range(const Image& image, VkImageAspectFlags aspects) {
240 const bool volume = image.type == ImageType::image_3d;
241 return {aspects, image.first_mip, image.mip_count, volume ? 0u : image.first_layer,
242 volume ? 1u : image.layer_count};
243}
244
245inline constexpr bool has_hardware_volume_uav_slice_offset(const ImageWords& words, const Image& image) {
246 return image.type == ImageType::image_3d && image.first_layer != 0 && detail::get(words[5], 0, 4) == 1;
247}
248
239// ---- formats ---- 249// ---- formats ----
240 250
241// One row for each Vulkan format: its GFX10_FORMAT code, and the DST_SEL that reads its channels as R, G, B, A 251// One row for each Vulkan format: its GFX10_FORMAT code, and the DST_SEL that reads its channels as R, G, B, A
diff --git a/runtime/src/large_module_gate.h b/runtime/src/large_module_gate.h
new file mode 100644
index 000000000..f66420bc2
--- /dev/null
+++ b/runtime/src/large_module_gate.h
@@ -0,0 +1,293 @@
1// How many large SPIR-V modules vk_pipeline_check and the runtime let into the driver at once, by a memory budget.
2//
3// Measured on RADV GFX1201 (Mesa 25.3.6) with the Mesa shader cache off: a 5.7 MB translated ray-tracing compute
4// 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.
5// Compiling the large ones strictly one at a time left the other threads idle: 40 modules (27 over 4 MiB) on 6
6// threads took 308 s exclusively and 75 s in parallel, 7.0 GB and 8.7 GB peak. kBytesPerSpirvByte keeps a margin
7// over the measurement. The NVIDIA 621.24 driver (RTX 3080) took 85 to 131 bytes per SPIR-V byte for synthetic compute
8// modules of 128 KiB to 4 MiB (docs/d3d12_vulkan.md, "Large pipelines").
9//
10// The process grew past one module's peak even one at a time because glibc keeps freed memory in per-thread arenas
11// (6 threads: 6.2 GB; MALLOC_ARENA_MAX=1: 2.1 GB, same modules). release_free_memory() hands it back after each
12// large module.
13#pragma once
14
15#include <algorithm>
16#include <condition_variable>
17#include <cstddef>
18#include <cstdint>
19#include <cstdio>
20#include <functional>
21#include <list>
22#include <mutex>
23#include <optional>
24#include <string>
25#include <utility>
26
27#ifdef _WIN32
28#ifndef NOMINMAX
29#define NOMINMAX
30#endif
31#include <windows.h>
32#endif
33#if defined(__GLIBC__)
34#include <malloc.h>
35#endif
36
37namespace leonida {
38
39inline constexpr uint64_t kBytesPerSpirvByte = 512;
40
41inline uint64_t large_module_estimate(uint64_t spirv_bytes) { return spirv_bytes * kBytesPerSpirvByte; }
42
43#if defined(__linux__)
44// The first unsigned number in a file ("max" and unreadable files give no value).
45inline bool read_u64_file(const std::string& path, uint64_t& value) {
46 std::FILE* f = std::fopen(path.c_str(), "r");
47 if (!f) return false;
48 unsigned long long v = 0;
49 const bool ok = std::fscanf(f, "%llu", &v) == 1;
50 std::fclose(f);
51 value = v;
52 return ok;
53}
54
55// The room left under the cgroup v2 memory.max of this process and of every cgroup above it (a container or
56// systemd-run -p MemoryMax=...), or UINT64_MAX when none sets a limit. cgroup_root is a parameter for the tests.
57inline uint64_t cgroup_memory_room(const std::string& self_cgroup_file = "/proc/self/cgroup",
58 const std::string& cgroup_root = "/sys/fs/cgroup") {
59 std::FILE* f = std::fopen(self_cgroup_file.c_str(), "r");
60 if (!f) return UINT64_MAX;
61 char line[4096];
62 std::string rel;
63 while (std::fgets(line, sizeof(line), f)) {
64 std::string l(line);
65 if (l.rfind("0::", 0) == 0) { // the cgroup v2 line
66 rel = l.substr(3);
67 while (!rel.empty() && (rel.back() == '\n' || rel.back() == '\r')) rel.pop_back();
68 break;
69 }
70 }
71 std::fclose(f);
72 uint64_t room = UINT64_MAX;
73 for (std::string dir = rel; !dir.empty();) {
74 // In a cgroup namespace, "/" can be a constrained cgroup mounted as the visible root.
75 const std::string base = dir == "/" ? cgroup_root : cgroup_root + dir;
76 uint64_t max = 0, current = 0;
77 if (read_u64_file(base + "/memory.max", max) && read_u64_file(base + "/memory.current", current))
78 room = std::min(room, max > current ? max - current : 0);
79 const auto slash = dir.find_last_of('/');
80 if (dir == "/" || slash == std::string::npos) break;
81 dir.resize(slash == 0 ? 1 : slash);
82 }
83 return room;
84}
85#endif
86
87// Memory the OS could give this process now, or 0 when it can't tell (then the caller keeps the old exclusive gate).
88inline uint64_t available_memory_bytes() {
89#ifdef _WIN32
90 MEMORYSTATUSEX status{};
91 status.dwLength = sizeof(status);
92 return GlobalMemoryStatusEx(&status) ? uint64_t(status.ullAvailPhys) : 0;
93#elif defined(__linux__)
94 std::FILE* f = std::fopen("/proc/meminfo", "r");
95 if (!f) return 0;
96 char line[256];
97 unsigned long long kb = 0;
98 bool found = false;
99 while (std::fgets(line, sizeof(line), f))
100 if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) { found = true; break; }
101 std::fclose(f);
102 if (!found) return 0;
103 const uint64_t room = cgroup_memory_room();
104 return std::max<uint64_t>(1, std::min(uint64_t(kb) * 1024, room)); // 0 would mean "unknown"
105#else
106 return 0;
107#endif
108}
109
110// What large compiles may use of the free RAM and of the room under the commit limit: three quarters of the smaller. (On
111// Windows an allocation that the limit has no room for fails, whatever RAM is free.)
112inline uint64_t large_compile_share(uint64_t free_ram, uint64_t commit_room) {
113 return std::min(free_ram, commit_room) / 4 * 3;
114}
115
116// The same of the memory that is free at this moment. 0 when it is unknown: then they compile one at a time.
117inline uint64_t large_compile_budget_bytes() {
118#ifdef _WIN32
119 MEMORYSTATUSEX status{};
120 status.dwLength = sizeof(status);
121 if (!GlobalMemoryStatusEx(&status)) return 0;
122 return large_compile_share(status.ullAvailPhys, status.ullAvailPageFile);
123#else
124 return large_compile_share(available_memory_bytes(), UINT64_MAX);
125#endif
126}
127
128// LEONIDA_BIG_COMPILE_BUDGET_MB: a fixed budget in MiB instead of the share of the free memory (0: one at a time). Unset
129// or empty, and text that is not a number: none. `valid` is false for the latter.
130struct LargeCompileBudget {
131 std::optional<uint64_t> fixed{};
132 bool valid = true;
133};
134
135inline LargeCompileBudget large_compile_budget(const char* text) {
136 if (!text || !*text) return {};
137 uint64_t mib = 0;
138 for (const char* c = text; *c; ++c) {
139 if (*c < '0' || *c > '9') return {std::nullopt, false};
140 mib = std::min<uint64_t>(mib * 10 + uint64_t(*c - '0'), UINT64_MAX >> 20);
141 }
142 return {mib << 20, true};
143}
144
145// Return memory freed by the driver's compiler to the OS (glibc keeps it in the arena of the thread that freed it).
146inline void release_free_memory() {
147#if defined(__GLIBC__)
148 malloc_trim(0);
149#endif
150}
151
152// Lets large modules in while their estimates fit the budget and fewer than max_inflight are in. One always gets in
153// when none is, so a module bigger than the whole budget still compiles (alone among the large ones).
154//
155// The second constructor is the runtime's: the budget is read again whenever a place is given or returned, and the
156// modules get in in the order they came, those a submission waits for (demand) before the others (speculative). While the
157// first in line does not fit, the next behind it that does may pass, as long as all that have passed it would fit the
158// budget together with it. So, with the budget as it is, it waits at most for those that were in when it became the first,
159// however many come after it, and one larger than the budget is not passed. A speculative one gets in only while no demand
160// waits and no submission has a Demand, and only within a quarter of the budget, so that a demand finds the rest free. An
161// estimate counts in full until its module leaves, although the driver has allocated part of it by then and the budget is
162// that much smaller: what is in has not taken all it is going to.
163class LargeModuleGate {
164public:
165 enum class Work { demand, speculative };
166
167 LargeModuleGate(uint64_t budget, unsigned max_inflight)
168 : budget_(budget), max_inflight_(max_inflight ? max_inflight : 1) {}
169 explicit LargeModuleGate(std::function<uint64_t()> budget)
170 : budget_(0), max_inflight_(UINT32_MAX), read_budget_(std::move(budget)) {}
171
172 bool admits(uint64_t estimate) const {
173 std::lock_guard<std::mutex> g(mu_);
174 return admits_locked(estimate, budget());
175 }
176 void enter(uint64_t estimate, Work work = Work::demand) {
177 std::unique_lock<std::mutex> l(mu_);
178 if (!read_budget_) {
179 cv_.wait(l, [&] { return admits_locked(estimate, limit_for(work)); });
180 } else {
181 auto& queue = waiting_[work == Work::demand ? 0 : 1];
182 const auto me = queue.insert(queue.end(), Waiter{estimate});
183 cv_.wait(l, [&] {
184 return (work == Work::demand || (waiting_[0].empty() && !demanded_)) && next_locked(work) == &*me;
185 });
186 if (me != queue.begin()) queue.front().passed += estimate;
187 queue.erase(me);
188 }
189 used_ += estimate;
190 ++inflight_;
191 if (!waiting_[0].empty() || !waiting_[1].empty()) cv_.notify_all(); // the next in the queue may fit as well
192 }
193 void leave(uint64_t estimate) {
194 {
195 std::lock_guard<std::mutex> g(mu_);
196 used_ -= estimate;
197 --inflight_;
198 }
199 cv_.notify_all();
200 }
201 unsigned inflight() const {
202 std::lock_guard<std::mutex> g(mu_);
203 return inflight_;
204 }
205 size_t waiting(Work work) const { // in order: the threads in enter(), with a budget that is read
206 std::lock_guard<std::mutex> g(mu_);
207 return waiting_[work == Work::demand ? 0 : 1].size();
208 }
209 uint64_t budget() const { return read_budget_ ? read_budget_() : budget_; }
210 unsigned max_inflight() const { return max_inflight_; }
211
212 // A submission that has large modules to build: until it ends, the places that its modules leave between one and the
213 // next are not taken by speculative ones.
214 class Demand {
215 public:
216 explicit Demand(LargeModuleGate& gate) : gate_(gate) {
217 std::lock_guard<std::mutex> g(gate_.mu_);
218 ++gate_.demanded_;
219 }
220 ~Demand() {
221 {
222 std::lock_guard<std::mutex> g(gate_.mu_);
223 --gate_.demanded_;
224 }
225 gate_.cv_.notify_all();
226 }
227 Demand(const Demand&) = delete;
228 Demand& operator=(const Demand&) = delete;
229
230 private:
231 LargeModuleGate& gate_;
232 };
233
234 // Holds a place from construction until destruction (or release()), then hands freed memory back.
235 class Ticket {
236 public:
237 Ticket() = default;
238 Ticket(LargeModuleGate& gate, uint64_t estimate, Work work = Work::demand) : gate_(&gate), estimate_(estimate) {
239 gate.enter(estimate, work);
240 }
241 Ticket(Ticket&& o) noexcept : gate_(o.gate_), estimate_(o.estimate_) { o.gate_ = nullptr; }
242 Ticket& operator=(Ticket&& o) noexcept {
243 if (this != &o) { release(); gate_ = o.gate_; estimate_ = o.estimate_; o.gate_ = nullptr; }
244 return *this;
245 }
246 Ticket(const Ticket&) = delete;
247 Ticket& operator=(const Ticket&) = delete;
248 ~Ticket() { release(); }
249 void release() {
250 if (!gate_) return;
251 gate_->leave(estimate_);
252 gate_ = nullptr;
253 release_free_memory();
254 }
255 private:
256 LargeModuleGate* gate_ = nullptr;
257 uint64_t estimate_ = 0;
258 };
259
260private:
261 struct Waiter {
262 uint64_t estimate;
263 uint64_t passed = 0; // the estimates of those that have passed it while it was the first in line
264 };
265
266 uint64_t limit_for(Work work) const { return work == Work::demand ? budget() : budget() / 4; }
267 bool admits_locked(uint64_t estimate, uint64_t limit) const {
268 return inflight_ == 0 || (inflight_ < max_inflight_ && used_ + estimate <= limit);
269 }
270 // The one in line that gets in now, if any: the first, or else the first that fits and may pass it.
271 const Waiter* next_locked(Work work) const {
272 const auto& queue = waiting_[work == Work::demand ? 0 : 1];
273 const uint64_t limit = limit_for(work);
274 for (const Waiter& w : queue) {
275 const Waiter& first = queue.front();
276 if (&w != &first && first.passed + w.estimate + first.estimate > limit) continue;
277 if (admits_locked(w.estimate, limit)) return &w;
278 }
279 return nullptr;
280 }
281
282 const uint64_t budget_;
283 const unsigned max_inflight_;
284 const std::function<uint64_t()> read_budget_;
285 mutable std::mutex mu_;
286 std::condition_variable cv_;
287 std::list<Waiter> waiting_[2]; // demand, speculative: one for each thread in enter(), in the order they came
288 uint64_t used_ = 0;
289 unsigned inflight_ = 0;
290 unsigned demanded_ = 0; // the Demands
291};
292
293} // namespace leonida
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index d0a863421..ecc2eef9c 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -1572,6 +1572,14 @@ public:
1572 std::unique_lock lock(pipeline_mutex_); 1572 std::unique_lock lock(pipeline_mutex_);
1573 pipeline_workers_.swap(workers); 1573 pipeline_workers_.swap(workers);
1574 } 1574 }
1575 // For the large pipelines of a submission: the memory they may use while they compile together
1576 // (PipelineCompiles::build), and what is kept while they do (LargeModuleGate::Demand). None (the default): they compile
1577 // one after another.
1578 void set_large_compiles(std::function<std::uint64_t()> budget, std::function<std::shared_ptr<void>()> demand) {
1579 std::unique_lock lock(pipeline_mutex_);
1580 large_compile_budget_ = std::move(budget);
1581 large_compile_demand_ = std::move(demand);
1582 }
1575 PipelineWorkers::Stats pipeline_worker_stats() { 1583 PipelineWorkers::Stats pipeline_worker_stats() {
1576 std::shared_lock lock(pipeline_mutex_); 1584 std::shared_lock lock(pipeline_mutex_);
1577 return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{}; 1585 return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{};
@@ -2189,6 +2197,8 @@ private:
2189 std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_; 2197 std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_;
2190 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_; 2198 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_;
2191 std::unique_ptr<PipelineWorkers> pipeline_workers_; 2199 std::unique_ptr<PipelineWorkers> pipeline_workers_;
2200 std::function<std::uint64_t()> large_compile_budget_;
2201 std::function<std::shared_ptr<void>()> large_compile_demand_;
2192 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_; 2202 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_;
2193 LayoutTracker tracker_; 2203 LayoutTracker tracker_;
2194 std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only 2204 std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only
@@ -3168,10 +3178,13 @@ private:
3168 recycle_khr_as_queries(khr_guard.as_queries); 3178 recycle_khr_as_queries(khr_guard.as_queries);
3169 geometry.clear(); 3179 geometry.clear();
3170 3180
3181 std::shared_ptr<void> demand;
3182 if (context_.large_compile_demand_ && compiles.any_large()) demand = context_.large_compile_demand_();
3171 if (context_.pipeline_workers_) 3183 if (context_.pipeline_workers_)
3172 compiles.build(run_compiles); 3184 compiles.build(run_compiles, context_.large_compile_budget_);
3173 else 3185 else
3174 compiles.build_serial(); 3186 compiles.build_serial();
3187 demand.reset();
3175 const ReplayResult compile_result = check_compiled_pipelines(compiles, prepare_result); 3188 const ReplayResult compile_result = check_compiled_pipelines(compiles, prepare_result);
3176 if (compile_result != ReplayResult::success) return compile_result; 3189 if (compile_result != ReplayResult::success) return compile_result;
3177 prior_compiles = std::move(compiles); 3190 prior_compiles = std::move(compiles);
@@ -3181,7 +3194,7 @@ private:
3181 const PipelineCompiles* prior = has_prior_compiles ? &prior_compiles : nullptr; 3194 const PipelineCompiles* prior = has_prior_compiles ? &prior_compiles : nullptr;
3182 prepare_result = context_.pipeline_workers_ 3195 prepare_result = context_.pipeline_workers_
3183 ? build_pipelines(compiles, std::span(prepared).first(lists.size()), prepare_result, 3196 ? build_pipelines(compiles, std::span(prepared).first(lists.size()), prepare_result,
3184 run_compiles, prior) 3197 run_compiles, context_.large_compile_budget_, prior)
3185 : build_pipelines_serial(compiles, std::span(prepared).first(lists.size()), 3198 : build_pipelines_serial(compiles, std::span(prepared).first(lists.size()),
3186 prepare_result, prior); 3199 prepare_result, prior);
3187 replay.compiles = nullptr; 3200 replay.compiles = nullptr;
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index b735fbaa6..449f8de5d 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -60,6 +60,7 @@
60#include <limits> 60#include <limits>
61#include <map> 61#include <map>
62#include <memory> 62#include <memory>
63#include <mutex>
63#include <optional> 64#include <optional>
64#include <type_traits> 65#include <type_traits>
65#include <unordered_map> 66#include <unordered_map>
@@ -868,8 +869,9 @@ struct ComputePipeline {
868 // What `build` would return when it is built already and nobody is building it, else null; builds nothing. Null: a 869 // What `build` would return when it is built already and nobody is building it, else null; builds nothing. Null: a
869 // first use is always built where prepare() meets it. Not used with async_build. See PipelineCompiles. 870 // first use is always built where prepare() meets it. Not used with async_build. See PipelineCompiles.
870 VkPipeline (*built)(void*) = nullptr; 871 VkPipeline (*built)(void*) = nullptr;
871 bool large = false; // compiled one after another with the other large ones (PipelineCompiles) 872 bool large = false; // PipelineCompiles limits how many of these compile at once
872 bool skipped = false; // never built on request (LEONIDA_SKIP_COMPUTE): its dispatches are dropped 873 bool skipped = false; // never built on request (LEONIDA_SKIP_COMPUTE): its dispatches are dropped
874 std::uint64_t estimate = 0; // large: the bytes of memory its compile is expected to take
873}; 875};
874 876
875// A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it 877// 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 {
903 std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count 905 std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count
904 bool async_build = false; 906 bool async_build = false;
905 bool nonunit_vertex_divisor = false; // an actual instance divisor > 1, not a zero-stride emulation 907 bool nonunit_vertex_divisor = false; // an actual instance divisor > 1, not a zero-stride emulation
908 std::uint64_t estimate = 0; // as ComputePipeline::estimate
906}; 909};
907 910
908// The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base. 911// The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base.
@@ -1000,7 +1003,7 @@ public:
1000 User user; 1003 User user;
1001 }; 1004 };
1002 // A compile takes the driver some hundred bytes of memory for each byte of SPIR-V (docs/pipeline_check.md): graphics 1005 // A compile takes the driver some hundred bytes of memory for each byte of SPIR-V (docs/pipeline_check.md): graphics
1003 // pipelines of this much or more are `large`. 1006 // pipelines of this much or more are `large`. For compute pipelines the D3D12 layer decides.
1004 static constexpr std::uint64_t large_spirv_bytes = 1u << 20; 1007 static constexpr std::uint64_t large_spirv_bytes = 1u << 20;
1005 1008
1006 Ticket add(const GraphicsPipeline& pipeline, std::uint32_t flags) { 1009 Ticket add(const GraphicsPipeline& pipeline, std::uint32_t flags) {
@@ -1009,6 +1012,9 @@ public:
1009 Ticket add(const ComputePipeline& pipeline, User user) { return add({nullptr, &pipeline, 0}, user); } 1012 Ticket add(const ComputePipeline& pipeline, User user) { return add({nullptr, &pipeline, 0}, user); }
1010 1013
1011 bool empty() const { return jobs_.empty(); } 1014 bool empty() const { return jobs_.empty(); }
1015 bool any_large() const {
1016 return std::any_of(jobs_.begin(), jobs_.end(), [](const Job& job) { return is_large(job); });
1017 }
1012 std::size_t size() const { return jobs_.size(); } 1018 std::size_t size() const { return jobs_.size(); }
1013 VkPipeline built(Ticket ticket) const { return jobs_[ticket - 1].built; } 1019 VkPipeline built(Ticket ticket) const { return jobs_[ticket - 1].built; }
1014 const std::vector<Use>& uses() const { return uses_; } // in the order of the commands 1020 const std::vector<Use>& uses() const { return uses_; } // in the order of the commands
@@ -1030,26 +1036,64 @@ public:
1030 return lookup(job.graphics, job.compute, job.flags, unused); 1036 return lookup(job.graphics, job.compute, job.flags, unused);
1031 } 1037 }
1032 1038
1033 // Compiles all of them through run(count, job) (PipelineWorkers::run): the large ones one after another, as without 1039 // Compiles all of them through run(count, job) (PipelineWorkers::run). The large ones share budget() bytes of memory:
1034 // workers, beside the others. Jobs already attempted in `prior` reuse that outcome without re-invoking build(). 1040 // the largest first, as many at once as their estimates fit, one at least; while the next one does not fit, the
1041 // others are compiled first. No budget, or 0: the large ones one after another, as without workers, beside the others.
1035 template<typename Run> 1042 template<typename Run>
1036 void build(Run&& run, const PipelineCompiles* prior = nullptr) { 1043 void build(Run&& run, const std::function<std::uint64_t()>& read_budget = {},
1044 const PipelineCompiles* prior = nullptr) {
1037 std::vector<std::size_t> single, large; 1045 std::vector<std::size_t> single, large;
1038 for (std::size_t i = 0; i < jobs_.size(); ++i) { 1046 for (std::size_t i = 0; i < jobs_.size(); ++i) {
1039 if (prior && prior->lookup(jobs_[i].graphics, jobs_[i].compute, jobs_[i].flags, jobs_[i].built)) continue; 1047 if (prior && prior->lookup(jobs_[i].graphics, jobs_[i].compute, jobs_[i].flags, jobs_[i].built)) continue;
1040 (is_large(jobs_[i]) ? large : single).push_back(i); 1048 (is_large(jobs_[i]) ? large : single).push_back(i);
1041 } 1049 }
1042 if (single.empty() && large.empty()) return; 1050 if (single.empty() && large.empty()) return;
1051 // The first jobs of the run are lanes, which take large ones until none is left: no more of them than there are
1052 // large ones that fit the budget together (the smallest), so that no thread waits here for room in vain.
1053 std::size_t lanes = large.empty() ? 0 : 1;
1054 const std::uint64_t budget = lanes && read_budget ? read_budget() : 0;
1055 if (budget) {
1056 std::stable_sort(large.begin(), large.end(), [this](std::size_t a, std::size_t b) {
1057 return estimate(jobs_[a]) > estimate(jobs_[b]);
1058 });
1059 std::uint64_t sum = estimate(jobs_[large.back()]);
1060 while (lanes < large.size() && (sum += estimate(jobs_[large[large.size() - 1 - lanes]])) <= budget) ++lanes;
1061 }
1043 const auto compile = [this](std::size_t i) { 1062 const auto compile = [this](std::size_t i) {
1044 Job& job = jobs_[i]; 1063 Job& job = jobs_[i];
1045 job.built = job.graphics ? job.graphics->variant(job.flags) : job.compute->build(job.compute->build_context); 1064 job.built = job.graphics ? job.graphics->variant(job.flags) : job.compute->build(job.compute->build_context);
1046 }; 1065 };
1047 const std::size_t chain = large.empty() ? 0 : 1; // the large ones are one unit, the first 1066 std::mutex mutex; // guards the four below
1048 run(chain + single.size(), [&](std::size_t i) { 1067 std::size_t next_single = 0, next_large = 0, compiling = 0;
1049 if (i >= chain) 1068 std::uint64_t reserved = 0; // the estimates of the large ones compiling
1050 compile(single[i - chain]); 1069 run(lanes + single.size(), [&](std::size_t i) {
1051 else 1070 std::unique_lock lock(mutex);
1052 for (const std::size_t each : large) compile(each); 1071 if (i >= lanes) {
1072 if (next_single == single.size()) return; // a lane has taken it
1073 const std::size_t index = single[next_single++];
1074 lock.unlock();
1075 compile(index);
1076 return;
1077 }
1078 while (next_large < large.size()) {
1079 const std::uint64_t need = estimate(jobs_[large[next_large]]);
1080 const bool fits = !compiling || reserved + need <= budget;
1081 if (!fits && next_single < single.size()) {
1082 const std::size_t index = single[next_single++];
1083 lock.unlock();
1084 compile(index);
1085 lock.lock();
1086 continue;
1087 }
1088 const std::size_t index = large[next_large++];
1089 ++compiling;
1090 reserved += need;
1091 lock.unlock();
1092 compile(index);
1093 lock.lock();
1094 --compiling;
1095 reserved -= need;
1096 }
1053 }); 1097 });
1054 } 1098 }
1055 1099
@@ -1081,6 +1125,9 @@ private:
1081 VkPipeline built = VK_NULL_HANDLE; 1125 VkPipeline built = VK_NULL_HANDLE;
1082 }; 1126 };
1083 static bool is_large(const Job& job) { return job.graphics ? job.graphics->large : job.compute->large; } 1127 static bool is_large(const Job& job) { return job.graphics ? job.graphics->large : job.compute->large; }
1128 static std::uint64_t estimate(const Job& job) {
1129 return job.graphics ? job.graphics->estimate : job.compute->estimate;
1130 }
1084 Ticket add(const Job& job, User user) { 1131 Ticket add(const Job& job, User user) {
1085 const void* const pipeline = job.graphics ? static_cast<const void*>(job.graphics) : job.compute; 1132 const void* const pipeline = job.graphics ? static_cast<const void*>(job.graphics) : job.compute;
1086 const auto [it, added] = tickets_.try_emplace({pipeline, job.flags}, Ticket(jobs_.size() + 1)); 1133 const auto [it, added] = tickets_.try_emplace({pipeline, job.flags}, Ticket(jobs_.size() + 1));
@@ -3014,9 +3061,10 @@ inline ReplayResult finish_compiled_pipelines(const PipelineCompiles& compiles,
3014// have returned had they built each pipeline themselves. 3061// have returned had they built each pipeline themselves.
3015template<typename Run> 3062template<typename Run>
3016ReplayResult build_pipelines(PipelineCompiles& compiles, std::span<PreparedList> lists, ReplayResult result, 3063ReplayResult build_pipelines(PipelineCompiles& compiles, std::span<PreparedList> lists, ReplayResult result,
3017 Run&& run, const PipelineCompiles* prior = nullptr) { 3064 Run&& run, const std::function<std::uint64_t()>& budget = {},
3065 const PipelineCompiles* prior = nullptr) {
3018 if (compiles.empty()) return result; 3066 if (compiles.empty()) return result;
3019 compiles.build(run, prior); 3067 compiles.build(run, budget, prior);
3020 return finish_compiled_pipelines(compiles, lists, result, prior); 3068 return finish_compiled_pipelines(compiles, lists, result, prior);
3021} 3069}
3022 3070
diff --git a/runtime/test/big_compile_gate_test.cpp b/runtime/test/big_compile_gate_test.cpp
new file mode 100644
index 000000000..a012ac9f9
--- /dev/null
+++ b/runtime/test/big_compile_gate_test.cpp
@@ -0,0 +1,532 @@
1// LargeModuleGate with a budget that is read (runtime/src/large_module_gate.h): who gets in, in which order and when, and
2// the settings. The threads that wait for a place are real; every check that waits for one gives up after 10 s, so a
3// missing wake-up fails the test and does not hang it. Fixed budgets (vk_pipeline_check's) are large_module_gate_test.cpp's.
4// No Vulkan.
5#include "../src/large_module_gate.h"
6
7#include <atomic>
8#include <chrono>
9#include <condition_variable>
10#include <cstdint>
11#include <cstdio>
12#include <cstdlib>
13#include <functional>
14#include <memory>
15#include <mutex>
16#include <thread>
17#include <vector>
18
19namespace {
20
21using namespace std::chrono_literals;
22using leonida::LargeModuleGate;
23using Work = LargeModuleGate::Work;
24
25// Ends the process: the threads that the failed check left waiting would keep the rest from ending.
26#define CHECK(condition) do { \
27 if (!(condition)) { \
28 std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); \
29 std::fflush(stderr); \
30 std::_Exit(1); \
31 } \
32} while (0)
33
34bool eventually(const std::function<bool()>& what) {
35 const auto end = std::chrono::steady_clock::now() + 10s;
36 while (!what()) {
37 if (std::chrono::steady_clock::now() > end) return false;
38 std::this_thread::sleep_for(1ms);
39 }
40 return true;
41}
42
43// A thread in enter() for one estimate, which keeps its place until leave() is called.
44class Entrant {
45public:
46 Entrant(LargeModuleGate& gate, std::uint64_t estimate, Work work = Work::demand) {
47 thread_ = std::thread([&gate, estimate, work, this] {
48 LargeModuleGate::Ticket place(gate, estimate, work);
49 in_ = true;
50 std::unique_lock lock(mutex_);
51 go_.wait(lock, [this] { return leave_; });
52 lock.unlock();
53 });
54 }
55 ~Entrant() {
56 if (thread_.joinable()) {
57 leave();
58 join();
59 }
60 }
61 Entrant(const Entrant&) = delete;
62 Entrant& operator=(const Entrant&) = delete;
63 bool in() const { return in_; }
64 void leave() {
65 std::lock_guard lock(mutex_);
66 leave_ = true;
67 go_.notify_all();
68 }
69 void join() { thread_.join(); }
70
71private:
72 std::atomic<bool> in_{false};
73 std::mutex mutex_;
74 std::condition_variable go_;
75 bool leave_ = false;
76 std::thread thread_;
77};
78
79bool waiting(LargeModuleGate& gate, Work work, std::size_t count) {
80 return eventually([&] { return gate.waiting(work) == count; });
81}
82bool in(const Entrant& e) { return eventually([&] { return e.in(); }); }
83// The time a wrong admission would need to happen.
84bool stays_out(const Entrant& e) {
85 std::this_thread::sleep_for(50ms);
86 return !e.in();
87}
88
89LargeModuleGate fixed(std::uint64_t budget) {
90 return LargeModuleGate([budget] { return budget; });
91}
92
93void bound_and_one_always() {
94 auto gate = fixed(10);
95 Entrant big(gate, 25); // more than the whole budget: it compiles alone
96 CHECK(in(big));
97 Entrant first(gate, 6), second(gate, 4);
98 CHECK(stays_out(first) && stays_out(second));
99 big.leave();
100 big.join();
101 CHECK(in(first) && in(second)); // 10 fits exactly
102 Entrant third(gate, 1);
103 CHECK(waiting(gate, Work::demand, 1) && stays_out(third));
104 first.leave();
105 CHECK(in(third));
106 CHECK(gate.inflight() == 2);
107 second.leave();
108 third.leave();
109 second.join();
110 third.join();
111 first.join();
112 CHECK(eventually([&] { return gate.inflight() == 0; }));
113}
114
115// Whatever the sizes, what is in fits, or is one alone; everything gets in, once.
116void many_threads() {
117 for (const std::uint64_t budget : {0u, 1u, 10u, 40u}) {
118 auto gate = fixed(budget);
119 std::atomic<std::uint64_t> used{0};
120 std::atomic<unsigned> inside{0}, most{0};
121 std::atomic<int> over{0}, done{0};
122 std::vector<std::thread> threads;
123 for (unsigned t = 0; t < 8; ++t)
124 threads.emplace_back([&, t] {
125 for (unsigned i = 0; i < 150; ++i) {
126 const std::uint64_t estimate = 1 + (t * 7 + i) % 13;
127 const LargeModuleGate::Ticket place(gate, estimate,
128 (t + i) % 3 ? Work::demand : Work::speculative);
129 const std::uint64_t sum = used += estimate;
130 const unsigned n = ++inside;
131 if (sum > budget && n > 1) ++over;
132 unsigned m = most;
133 while (n > m && !most.compare_exchange_weak(m, n)) {}
134 for (int spin = 0; spin < 20; ++spin) std::this_thread::yield();
135 --inside;
136 used -= estimate;
137 ++done;
138 }
139 });
140 for (auto& t : threads) t.join();
141 CHECK(over == 0);
142 CHECK(done == 8 * 150);
143 CHECK(gate.inflight() == 0);
144 CHECK(budget < 40 || most > 1); // and where there is room, several are in
145 }
146}
147
148// Those that wait get in in the order they came, but for what fits now and also beside the first in line: that one finds
149// its room when those that were in before it leave, whatever passed it.
150void order() {
151 auto gate = fixed(10);
152 Entrant first(gate, 8);
153 CHECK(in(first));
154 Entrant big(gate, 9);
155 CHECK(waiting(gate, Work::demand, 1));
156 Entrant in_the_way(gate, 2); // it fits beside the first, and not beside the big one
157 CHECK(waiting(gate, Work::demand, 2));
158 Entrant little(gate, 1);
159 CHECK(in(little));
160 Entrant next(gate, 1); // beside the big one there is room for one of these
161 CHECK(waiting(gate, Work::demand, 3));
162 CHECK(stays_out(big) && stays_out(in_the_way) && stays_out(next));
163 little.leave();
164 little.join();
165 CHECK(stays_out(big) && stays_out(in_the_way) && stays_out(next)); // nor when the one that passed has left
166 first.leave();
167 CHECK(in(big));
168 CHECK(in(next)); // the first in line is now in_the_way, which it can pass
169 CHECK(stays_out(in_the_way));
170 big.leave();
171 CHECK(in(in_the_way));
172 in_the_way.leave();
173 next.leave();
174}
175
176// What passes the first in line is bounded: a stream of small ones does not keep it out.
177void a_stream_of_small_ones_does_not_keep_out() {
178 auto gate = fixed(100);
179 Entrant first(gate, 50);
180 CHECK(in(first));
181 Entrant big(gate, 70);
182 CHECK(waiting(gate, Work::demand, 1));
183 std::vector<std::unique_ptr<Entrant>> stream;
184 for (int i = 0; i < 3; ++i) { // 30 beside the big one's 70, one after another
185 stream.push_back(std::make_unique<Entrant>(gate, 10));
186 CHECK(in(*stream.back()));
187 if (i < 2) { // one of them stays in
188 stream.back()->leave();
189 stream.back()->join();
190 }
191 }
192 Entrant more(gate, 10);
193 CHECK(waiting(gate, Work::demand, 2));
194 CHECK(stays_out(more)); // it fits (70 of 100 with the rest), but the first in line has been passed enough
195 first.leave();
196 CHECK(in(big)); // 10 of the stream and 70
197 CHECK(in(more));
198 big.leave();
199 more.leave();
200 stream.back()->leave();
201}
202
203// Of those that can pass, the one that came first does.
204void those_that_pass_keep_their_order() {
205 for (int round = 0; round < 10; ++round) {
206 auto gate = fixed(20);
207 Entrant first(gate, 15), other(gate, 5);
208 CHECK(in(first) && in(other));
209 Entrant big(gate, 12);
210 CHECK(waiting(gate, Work::demand, 1));
211 Entrant a(gate, 4);
212 CHECK(waiting(gate, Work::demand, 2));
213 Entrant b(gate, 4);
214 CHECK(waiting(gate, Work::demand, 3));
215 other.leave();
216 CHECK(in(a));
217 CHECK(stays_out(b) && stays_out(big)); // 19 of 20
218 first.leave();
219 CHECK(in(big) && in(b));
220 big.leave();
221 a.leave();
222 b.leave();
223 }
224}
225
226// One that needs the machine for itself is not passed: what got in beside it would keep it out.
227void larger_than_the_budget_is_not_passed() {
228 auto gate = fixed(10);
229 Entrant first(gate, 5);
230 CHECK(in(first));
231 Entrant alone(gate, 25);
232 CHECK(waiting(gate, Work::demand, 1));
233 Entrant little(gate, 1);
234 CHECK(waiting(gate, Work::demand, 2));
235 CHECK(stays_out(little));
236 first.leave();
237 CHECK(in(alone));
238 CHECK(stays_out(little));
239 alone.leave();
240 CHECK(in(little));
241 little.leave();
242}
243
244// The same for the speculative ones, within their quarter.
245void speculative_ones_pass_each_other() {
246 auto gate = fixed(100);
247 Entrant first(gate, 20, Work::speculative);
248 CHECK(in(first));
249 Entrant big(gate, 18, Work::speculative);
250 CHECK(waiting(gate, Work::speculative, 1));
251 Entrant little(gate, 5, Work::speculative);
252 CHECK(in(little)); // 25 of 25, and 23 with the big one
253 Entrant next(gate, 1, Work::speculative);
254 CHECK(waiting(gate, Work::speculative, 2));
255 little.leave();
256 little.join();
257 CHECK(in(next)); // 21 of 25, and 24 of what may pass
258 Entrant over(gate, 2, Work::speculative);
259 CHECK(waiting(gate, Work::speculative, 2));
260 CHECK(stays_out(over) && stays_out(big)); // it would be 26
261 first.leave();
262 CHECK(in(big) && in(over));
263 big.leave();
264 next.leave();
265 over.leave();
266}
267
268// The first in the queue leaves it, and the next one, which fits as well, gets in at once and not when something leaves.
269void one_admission_wakes_the_next() {
270 auto gate = fixed(10);
271 Entrant first(gate, 10);
272 CHECK(in(first));
273 Entrant a(gate, 4), b(gate, 4), c(gate, 2);
274 CHECK(waiting(gate, Work::demand, 3));
275 first.leave();
276 CHECK(in(a) && in(b) && in(c));
277 CHECK(gate.inflight() == 3);
278 a.leave();
279 b.leave();
280 c.leave();
281}
282
283void leaving_wakes_all_that_fit() {
284 auto gate = fixed(10);
285 Entrant a(gate, 5), b(gate, 5);
286 CHECK(in(a) && in(b));
287 Entrant c(gate, 3), d(gate, 2);
288 CHECK(waiting(gate, Work::demand, 2) && stays_out(c));
289 a.leave();
290 CHECK(in(c) && in(d));
291 b.leave();
292 c.leave();
293 d.leave();
294}
295
296// What a submission waits for goes first, whenever it came.
297void demand_before_speculative() {
298 auto gate = fixed(10);
299 Entrant first(gate, 10);
300 CHECK(in(first));
301 Entrant speculative(gate, 1, Work::speculative);
302 CHECK(waiting(gate, Work::speculative, 1));
303 Entrant demand(gate, 9);
304 CHECK(waiting(gate, Work::demand, 1));
305 first.leave();
306 CHECK(in(demand)); // the speculative one came first and would have fitted
307 CHECK(stays_out(speculative));
308 demand.leave();
309 CHECK(in(speculative));
310 speculative.leave();
311}
312
313// Waiting demand keeps out speculative work that fits, also the one that is first in line.
314void waiting_demand_keeps_speculative_out() {
315 auto gate = fixed(100);
316 Entrant first(gate, 40, Work::demand);
317 CHECK(in(first));
318 Entrant blocked(gate, 100); // waits for the first
319 CHECK(waiting(gate, Work::demand, 1));
320 Entrant speculative(gate, 5, Work::speculative); // a quarter holds it
321 CHECK(waiting(gate, Work::speculative, 1));
322 CHECK(stays_out(speculative));
323 first.leave();
324 CHECK(in(blocked));
325 CHECK(stays_out(speculative));
326 blocked.leave();
327 CHECK(in(speculative));
328 speculative.leave();
329}
330
331// While a submission has more to build, the room between two of its modules is not a speculative one's.
332void a_demand_keeps_speculative_out() {
333 auto gate = fixed(100);
334 auto one = std::make_unique<LargeModuleGate::Demand>(gate), other = std::make_unique<LargeModuleGate::Demand>(gate);
335 Entrant speculative(gate, 10, Work::speculative);
336 CHECK(waiting(gate, Work::speculative, 1));
337 CHECK(stays_out(speculative)); // it fits, and nothing is in
338 for (int i = 0; i < 2; ++i) {
339 Entrant built(gate, 10);
340 CHECK(in(built));
341 built.leave();
342 built.join();
343 CHECK(stays_out(speculative)); // between two of the submission's modules
344 }
345 one.reset();
346 CHECK(stays_out(speculative)); // another submission has some
347 other.reset();
348 CHECK(in(speculative)); // the end of the last one wakes it
349 speculative.leave();
350}
351
352// A speculative one gets in within a quarter of the budget, and what is free of it is there for a demand.
353void speculative_share() {
354 auto gate = fixed(100);
355 Entrant demand(gate, 30);
356 CHECK(in(demand));
357 Entrant over(gate, 26, Work::speculative); // 56 of 100, but more than 25 with the rest
358 CHECK(waiting(gate, Work::speculative, 1));
359 CHECK(stays_out(over));
360 demand.leave();
361 CHECK(in(over)); // alone, whatever its size
362 Entrant quick(gate, 70);
363 CHECK(in(quick)); // 96 of 100: the speculative one does not count against it
364 quick.leave();
365 over.leave();
366 quick.join();
367 over.join();
368 CHECK(eventually([&] { return gate.inflight() == 0; }));
369 Entrant share(gate, 25, Work::speculative);
370 CHECK(in(share));
371 Entrant second(gate, 1, Work::speculative);
372 CHECK(waiting(gate, Work::speculative, 1)); // one more byte is past the quarter
373 CHECK(stays_out(second));
374 Entrant next(gate, 75);
375 CHECK(in(next)); // the whole rest
376 CHECK(stays_out(second));
377 next.leave();
378 share.leave();
379 CHECK(in(second));
380 second.leave();
381}
382
383// Speculative ones get in in the order they came, and alone when nothing is in.
384void speculative_order_and_alone() {
385 auto gate = fixed(0); // unknown memory: one at a time
386 Entrant a(gate, 5, Work::speculative);
387 CHECK(in(a));
388 Entrant b(gate, 5, Work::speculative);
389 CHECK(waiting(gate, Work::speculative, 1));
390 Entrant c(gate, 5, Work::demand);
391 CHECK(waiting(gate, Work::demand, 1));
392 CHECK(stays_out(b) && stays_out(c));
393 a.leave();
394 CHECK(in(c));
395 CHECK(stays_out(b));
396 c.leave();
397 CHECK(in(b));
398 b.leave();
399}
400
401// The budget is read when a place is asked for and when one is given back, not once.
402void budget_follows_the_moment() {
403 std::atomic<std::uint64_t> free{100};
404 LargeModuleGate gate([&] { return free.load(); });
405 CHECK(gate.budget() == 100);
406 Entrant a(gate, 30), b(gate, 10);
407 CHECK(in(a) && in(b));
408 free = 35;
409 Entrant c(gate, 20); // 60 of 100 a moment ago
410 CHECK(waiting(gate, Work::demand, 1));
411 CHECK(stays_out(c));
412 free = 100;
413 b.leave();
414 CHECK(in(c)); // 50 of 100 now; it would not be within 35
415 CHECK(gate.inflight() == 2);
416 a.leave();
417 c.leave();
418 a.join();
419 c.join();
420 // A budget that shrinks while a module is in does not throw it out, and holds the next.
421 Entrant d(gate, 100);
422 CHECK(in(d));
423 free = 1;
424 Entrant e(gate, 1);
425 CHECK(waiting(gate, Work::demand, 1));
426 CHECK(stays_out(e));
427 CHECK(gate.inflight() == 1);
428 d.leave();
429 CHECK(in(e));
430}
431
432// An estimate counts for as long as its module is in, whatever the driver has taken of it already.
433void estimates_stay_reserved() {
434 auto gate = fixed(100); // the driver has taken nothing yet: the memory is all there
435 Entrant a(gate, 60);
436 CHECK(in(a));
437 Entrant b(gate, 60);
438 CHECK(waiting(gate, Work::demand, 1));
439 CHECK(stays_out(b));
440 a.leave();
441 CHECK(in(b));
442 b.leave();
443}
444
445// A ticket gives its place back once, however it ends.
446void tickets() {
447 auto gate = fixed(10);
448 {
449 LargeModuleGate::Ticket a(gate, 6, Work::speculative);
450 LargeModuleGate::Ticket moved = std::move(a);
451 CHECK(gate.inflight() == 1);
452 LargeModuleGate::Ticket b;
453 b = LargeModuleGate::Ticket(gate, 3);
454 CHECK(gate.inflight() == 2);
455 b.release();
456 b.release();
457 CHECK(gate.inflight() == 1);
458 }
459 CHECK(gate.inflight() == 0);
460}
461
462// The memory budget's setting: what it says, and nothing else.
463void settings() {
464 using leonida::large_compile_budget;
465 const auto check = [](const char* text, bool valid, bool has, std::uint64_t mib) {
466 const auto s = large_compile_budget(text);
467 CHECK(s.valid == valid);
468 CHECK(s.fixed.has_value() == has);
469 if (has) CHECK(*s.fixed == mib << 20);
470 };
471 check(nullptr, true, false, 0);
472 check("", true, false, 0);
473 check("0", true, true, 0);
474 check("1", true, true, 1);
475 check("512", true, true, 512);
476 check("0512", true, true, 512);
477 check("12a", false, false, 0);
478 check(" 5", false, false, 0);
479 check("-1", false, false, 0);
480 check("1.5", false, false, 0);
481 check("99999999999999999999999", true, true, UINT64_MAX >> 20); // saturates: no limit, not a small number
482 CHECK(*large_compile_budget("99999999999999999999999").fixed >= (UINT64_MAX >> 20) << 20);
483}
484
485// The share of the memory, and what the machine gives now: nothing unknown on Windows and Linux, and no more than three
486// quarters of either limit.
487void machine() {
488 using leonida::large_compile_share;
489 CHECK(large_compile_share(1000, 4000) == 750);
490 CHECK(large_compile_share(4000, 1000) == 750); // the commit limit has less room than the RAM
491 CHECK(large_compile_share(0, 4000) == 0);
492 const std::uint64_t budget = leonida::large_compile_budget_bytes();
493#if defined(_WIN32) || defined(__linux__)
494 CHECK(budget > 0);
495#endif
496 // Read a moment apart on a running machine: the budget may not exceed either limit by more than that moment.
497 const std::uint64_t slack = std::uint64_t(256) << 20;
498 CHECK(budget <= leonida::available_memory_bytes() / 4 * 3 + slack);
499 CHECK(leonida::large_module_estimate(1 << 20) == (std::uint64_t(1) << 20) * leonida::kBytesPerSpirvByte);
500#ifdef _WIN32
501 MEMORYSTATUSEX status{};
502 status.dwLength = sizeof(status);
503 CHECK(GlobalMemoryStatusEx(&status) != 0);
504 CHECK(budget <= status.ullAvailPageFile / 4 * 3 + slack);
505#endif
506}
507
508} // namespace
509
510int main() {
511 bound_and_one_always();
512 many_threads();
513 order();
514 a_stream_of_small_ones_does_not_keep_out();
515 those_that_pass_keep_their_order();
516 larger_than_the_budget_is_not_passed();
517 speculative_ones_pass_each_other();
518 one_admission_wakes_the_next();
519 leaving_wakes_all_that_fit();
520 demand_before_speculative();
521 waiting_demand_keeps_speculative_out();
522 a_demand_keeps_speculative_out();
523 speculative_share();
524 speculative_order_and_alone();
525 budget_follows_the_moment();
526 estimates_stay_reserved();
527 tickets();
528 settings();
529 machine();
530 std::puts("big_compile_gate: ok");
531 return 0;
532}
diff --git a/runtime/test/big_compute_module.h b/runtime/test/big_compute_module.h
new file mode 100644
index 000000000..28dde996f
--- /dev/null
+++ b/runtime/test/big_compute_module.h
@@ -0,0 +1,298 @@
1// Large compute modules that are work for a driver's compiler, not padding: a register file in a Function array that every
2// instruction loads from and stores to (as the translator's modules have it), integer instructions, selections, nested
3// conditionals and loops, and loads from memory the compiler knows nothing about. The same instructions run on the CPU, so
4// the value that a dispatch stores is known. Made from a seed; no game data.
5#pragma once
6
7#include <cstddef>
8#include <cstdint>
9#include <initializer_list>
10#include <random>
11#include <utility>
12#include <vector>
13
14namespace bigmodule {
15
16using Words = std::vector<std::uint32_t>;
17
18inline void op(Words& out, std::uint16_t code, std::initializer_list<std::uint32_t> operands) {
19 out.push_back((std::uint32_t(operands.size() + 1) << 16) | code);
20 out.insert(out.end(), operands.begin(), operands.end());
21}
22
23enum class Kind : std::uint8_t { add, sub, mul, xor_, and_, or_, shl, shr, select, load, if_, end_if, loop, end_loop };
24
25struct Instruction {
26 Kind kind;
27 std::uint8_t d = 0, a = 0, b = 0, c = 0; // registers; c is a shift count or a loop count for those kinds
28};
29
30constexpr unsigned kRegisters = 48, kConstants = 64, kDepth = 3;
31constexpr unsigned kLoadBase = 256, kLoadWords = 64; // the words of the buffer the loads read (the CPU takes them as 0)
32
33struct Program {
34 std::vector<Instruction> code;
35 std::uint32_t constants[kConstants];
36
37 // What the module stores for the dispatch with this root constant.
38 std::uint32_t run(std::uint32_t root_constant) const {
39 std::uint32_t v[kRegisters];
40 for (unsigned i = 0; i < kRegisters; ++i) v[i] = constants[i % kConstants] ^ (root_constant + i);
41 walk(0, v);
42 std::uint32_t out = 0;
43 for (unsigned i = 0; i < kRegisters; ++i) out ^= v[i];
44 return out;
45 }
46
47private:
48 // Runs from `at` to the end marker of its block and returns the index after it.
49 std::size_t walk(std::size_t at, std::uint32_t* v) const {
50 for (; at < code.size();) {
51 const Instruction& i = code[at];
52 const std::uint32_t k = constants[i.c % kConstants];
53 switch (i.kind) {
54 case Kind::add: v[i.d] = v[i.a] + v[i.b] + k; break;
55 case Kind::sub: v[i.d] = v[i.a] - v[i.b] - k; break;
56 case Kind::mul: v[i.d] = v[i.a] * v[i.b] * k; break;
57 case Kind::xor_: v[i.d] = v[i.a] ^ v[i.b] ^ k; break;
58 case Kind::and_: v[i.d] = v[i.a] & (v[i.b] | k); break;
59 case Kind::or_: v[i.d] = v[i.a] | (v[i.b] & k); break;
60 case Kind::shl: v[i.d] = (v[i.a] << (i.c & 31)) ^ v[i.b]; break;
61 case Kind::shr: v[i.d] = (v[i.a] >> (i.c & 31)) ^ v[i.b]; break;
62 case Kind::select: v[i.d] = v[i.a] < v[i.b] ? v[i.c % kRegisters] : v[i.a]; break;
63 case Kind::load: v[i.d] = v[i.b]; break; // + the loaded word, which is 0
64 case Kind::if_: {
65 std::size_t after = at + 1;
66 if (v[i.a] < v[i.b])
67 after = walk(at + 1, v);
68 else
69 after = skip(at + 1);
70 at = after;
71 continue;
72 }
73 case Kind::loop: {
74 std::size_t after = at + 1;
75 for (unsigned n = 0; n < i.c; ++n) after = walk(at + 1, v);
76 at = after;
77 continue;
78 }
79 case Kind::end_if:
80 case Kind::end_loop: return at + 1;
81 }
82 ++at;
83 }
84 return at;
85 }
86 std::size_t skip(std::size_t at) const {
87 for (int depth = 1; at < code.size(); ++at) {
88 const Kind k = code[at].kind;
89 if (k == Kind::if_ || k == Kind::loop) ++depth;
90 if ((k == Kind::end_if || k == Kind::end_loop) && !--depth) return at + 1;
91 }
92 return at;
93 }
94};
95
96// A module of about `bytes` bytes of SPIR-V (a few KiB more), and the program it runs. `seed` decides everything. It has the
97// 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
98// Program::run(s[6]) at the UAV's word s[6], and reads its words kLoadBase to kLoadBase + kLoadWords - 1, which have to
99// be 0.
100inline Words make(std::size_t bytes, std::uint64_t seed, Program* out = nullptr) {
101 std::mt19937_64 random(seed);
102 Program program;
103 for (auto& c : program.constants) c = std::uint32_t(random());
104 // Ids.
105 enum : std::uint32_t {
106 id_void = 1, id_fn, id_main, id_uint, id_ulong, id_bool, id_block, id_sarr, id_c32, id_ptr_push_block,
107 id_push, id_ptr_push_uint, id_ptr_push_ulong, id_data, id_ptr_data, id_ptr_phys_uint, id_regs, id_cregs,
108 id_ptr_regs, id_ptr_fn_uint, id_vregs, id_entry, id_c64_32, id_c64_2, id_mask, id_base,
109 id_index0 = 40, // uint constants 0..127
110 id_const0 = id_index0 + 128, // the program's constants
111 id_counter0 = id_const0 + kConstants, // loop counters by depth
112 id_first = id_counter0 + kDepth + 1,
113 };
114 std::uint32_t next = id_first;
115 Words w = {0x07230203u, 0x00010500u, 0u, 0u, 0u};
116 op(w, 17, {1}); // Shader
117 op(w, 17, {11}); // Int64
118 op(w, 17, {5347}); // PhysicalStorageBufferAddresses
119 op(w, 14, {5348, 1});
120 op(w, 15, {5, id_main, 0x6e69616du, 0u, id_push});
121 op(w, 16, {id_main, 17, 1, 1, 1});
122 op(w, 71, {id_sarr, 6, 4});
123 op(w, 71, {id_block, 2});
124 op(w, 72, {id_block, 0, 35, 0});
125 op(w, 72, {id_block, 1, 35, 128});
126 op(w, 72, {id_block, 2, 35, 136});
127 op(w, 71, {id_data, 2});
128 op(w, 72, {id_data, 0, 35, 0});
129 op(w, 19, {id_void});
130 op(w, 33, {id_fn, id_void});
131 op(w, 21, {id_uint, 32, 0});
132 op(w, 21, {id_ulong, 64, 0});
133 op(w, 20, {id_bool});
134 op(w, 43, {id_uint, id_c32, 32});
135 op(w, 28, {id_sarr, id_uint, id_c32});
136 op(w, 30, {id_block, id_sarr, id_ulong, id_ulong});
137 op(w, 32, {id_ptr_push_block, 9, id_block});
138 op(w, 59, {id_ptr_push_block, id_push, 9});
139 op(w, 32, {id_ptr_push_uint, 9, id_uint});
140 op(w, 32, {id_ptr_push_ulong, 9, id_ulong});
141 op(w, 30, {id_data, id_uint});
142 op(w, 32, {id_ptr_data, 5349, id_data});
143 op(w, 32, {id_ptr_phys_uint, 5349, id_uint});
144 op(w, 43, {id_uint, id_cregs, kRegisters});
145 op(w, 28, {id_regs, id_uint, id_cregs});
146 op(w, 32, {id_ptr_regs, 7, id_regs});
147 op(w, 32, {id_ptr_fn_uint, 7, id_uint});
148 op(w, 43, {id_ulong, id_c64_32, 32, 0});
149 op(w, 43, {id_ulong, id_c64_2, 2, 0});
150 op(w, 43, {id_uint, id_mask, kLoadWords - 1});
151 op(w, 43, {id_uint, id_base, kLoadBase});
152 for (std::uint32_t i = 0; i < 128; ++i) op(w, 43, {id_uint, id_index0 + i, i});
153 for (std::uint32_t i = 0; i < kConstants; ++i) op(w, 43, {id_uint, id_const0 + i, program.constants[i]});
154 op(w, 54, {id_void, id_main, 0, id_fn});
155 op(w, 248, {id_entry});
156 op(w, 59, {id_ptr_regs, id_vregs, 7});
157 for (std::uint32_t i = 0; i <= kDepth; ++i) op(w, 59, {id_ptr_fn_uint, id_counter0 + i, 7});
158 const auto unary = [&](std::uint16_t code, std::uint32_t type, std::uint32_t a) {
159 op(w, code, {type, next, a});
160 return next++;
161 };
162 const auto binary = [&](std::uint16_t code, std::uint32_t type, std::uint32_t a, std::uint32_t b) {
163 op(w, code, {type, next, a, b});
164 return next++;
165 };
166 const auto push_word = [&](std::uint32_t index) {
167 op(w, 65, {id_ptr_push_uint, next, id_push, id_index0, id_index0 + index});
168 return unary(61, id_uint, next++);
169 };
170 const std::uint32_t lo = push_word(4), hi = push_word(5);
171 op(w, 65, {id_ptr_push_ulong, next, id_push, id_index0 + 1});
172 const std::uint32_t heap = unary(61, id_ulong, next++);
173 const std::uint32_t lo64 = unary(113, id_ulong, lo), hi64 = unary(113, id_ulong, hi);
174 const std::uint32_t high = binary(196, id_ulong, hi64, id_c64_32);
175 const std::uint32_t va = binary(197, id_ulong, high, lo64);
176 const std::uint32_t base = binary(128, id_ulong, va, heap);
177 const std::uint32_t root = push_word(6);
178 const auto slot = [&](std::uint32_t r) {
179 op(w, 65, {id_ptr_fn_uint, next, id_vregs, id_index0 + r});
180 return next++;
181 };
182 const auto load_reg = [&](std::uint32_t r) { return unary(61, id_uint, slot(r)); };
183 const auto store_reg = [&](std::uint32_t r, std::uint32_t value) {
184 const std::uint32_t p = slot(r);
185 op(w, 62, {p, value});
186 };
187 for (std::uint32_t i = 0; i < kRegisters; ++i) {
188 const std::uint32_t seeded = binary(128, id_uint, root, id_index0 + i);
189 store_reg(i, binary(198, id_uint, id_const0 + i % kConstants, seeded));
190 }
191 struct Open {
192 Kind kind;
193 std::uint32_t merge, header, cont, counter;
194 unsigned left;
195 };
196 std::vector<Open> open;
197 unsigned loops = 0;
198 const auto pick = [&](std::uint32_t n) { return std::uint8_t(random() % n); };
199 const auto close = [&] {
200 const Open o = open.back();
201 open.pop_back();
202 if (o.kind == Kind::if_) {
203 op(w, 249, {o.merge});
204 op(w, 248, {o.merge});
205 program.code.push_back({Kind::end_if});
206 } else {
207 op(w, 249, {o.cont});
208 op(w, 248, {o.cont});
209 const std::uint32_t n = unary(61, id_uint, o.counter);
210 op(w, 62, {o.counter, binary(128, id_uint, n, id_index0 + 1)});
211 op(w, 249, {o.header});
212 op(w, 248, {o.merge});
213 program.code.push_back({Kind::end_loop});
214 --loops;
215 }
216 };
217 while (w.size() * 4 + 256 < bytes) {
218 const std::uint32_t roll = std::uint32_t(random() % 100);
219 if (roll < 4 && open.size() < kDepth) {
220 const std::uint8_t a = pick(kRegisters), b = pick(kRegisters);
221 const std::uint32_t condition = binary(176, id_bool, load_reg(a), load_reg(b)); // ULessThan
222 const std::uint32_t then = next++, merge = next++;
223 op(w, 247, {merge, 0});
224 op(w, 250, {condition, then, merge});
225 op(w, 248, {then});
226 open.push_back({Kind::if_, merge, 0, 0, 0, 10 + unsigned(random() % 30)});
227 program.code.push_back({Kind::if_, 0, a, b, 0});
228 } else if (roll < 5 && open.size() < kDepth && loops < 1) {
229 const std::uint8_t count = std::uint8_t(2 + random() % 3);
230 const std::uint32_t counter = id_counter0 + loops++;
231 op(w, 62, {counter, id_index0});
232 const std::uint32_t header = next++, check = next++, body = next++, cont = next++, merge = next++;
233 op(w, 249, {header});
234 op(w, 248, {header});
235 op(w, 246, {merge, cont, 0});
236 op(w, 249, {check});
237 op(w, 248, {check});
238 const std::uint32_t n = unary(61, id_uint, counter);
239 const std::uint32_t more = binary(176, id_bool, n, id_index0 + count);
240 op(w, 250, {more, body, merge});
241 op(w, 248, {body});
242 open.push_back({Kind::loop, merge, header, cont, counter, 20 + unsigned(random() % 20)});
243 program.code.push_back({Kind::loop, 0, 0, 0, count});
244 } else {
245 Instruction i{Kind(random() % 10), pick(kRegisters), pick(kRegisters), pick(kRegisters), pick(kConstants)};
246 if (i.kind == Kind::load && random() % 2) i.kind = Kind::add;
247 const std::uint32_t k = id_const0 + i.c % kConstants;
248 std::uint32_t value = 0;
249 const std::uint32_t a = load_reg(i.a), b = load_reg(i.b);
250 switch (i.kind) {
251 case Kind::add: value = binary(128, id_uint, binary(128, id_uint, a, b), k); break;
252 case Kind::sub: value = binary(130, id_uint, binary(130, id_uint, a, b), k); break;
253 case Kind::mul: value = binary(132, id_uint, binary(132, id_uint, a, b), k); break;
254 case Kind::xor_: value = binary(198, id_uint, binary(198, id_uint, a, b), k); break;
255 case Kind::and_: value = binary(199, id_uint, a, binary(197, id_uint, b, k)); break;
256 case Kind::or_: value = binary(197, id_uint, a, binary(199, id_uint, b, k)); break;
257 case Kind::shl: value = binary(198, id_uint, binary(196, id_uint, a, id_index0 + (i.c & 31)), b); break;
258 case Kind::shr: value = binary(198, id_uint, binary(194, id_uint, a, id_index0 + (i.c & 31)), b); break;
259 case Kind::select: {
260 const std::uint32_t c = load_reg(i.c % kRegisters);
261 const std::uint32_t less = binary(176, id_bool, a, b);
262 op(w, 169, {id_uint, next, less, c, a});
263 value = next++;
264 break;
265 }
266 default: { // load
267 const std::uint32_t index = binary(128, id_uint, binary(199, id_uint, a, id_mask), id_base);
268 const std::uint32_t offset = binary(196, id_ulong, unary(113, id_ulong, index), id_c64_2);
269 const std::uint32_t address = binary(128, id_ulong, base, offset);
270 const std::uint32_t data = unary(120, id_ptr_data, address);
271 op(w, 65, {id_ptr_phys_uint, next, data, id_index0});
272 const std::uint32_t pointer = next++;
273 op(w, 61, {id_uint, next, pointer, 2, 4});
274 const std::uint32_t loaded = next++;
275 value = binary(128, id_uint, b, loaded);
276 break;
277 }
278 }
279 store_reg(i.d, value);
280 program.code.push_back(i);
281 }
282 if (!open.empty() && !open.back().left--) close();
283 }
284 while (!open.empty()) close();
285 std::uint32_t result = load_reg(0);
286 for (std::uint32_t i = 1; i < kRegisters; ++i) result = binary(198, id_uint, result, load_reg(i));
287 const std::uint32_t out_offset = binary(196, id_ulong, unary(113, id_ulong, root), id_c64_2);
288 const std::uint32_t out_data = unary(120, id_ptr_data, binary(128, id_ulong, base, out_offset));
289 op(w, 65, {id_ptr_phys_uint, next, out_data, id_index0});
290 op(w, 62, {next++, result, 2, 4});
291 op(w, 253, {});
292 op(w, 56, {});
293 w[3] = next;
294 if (out) *out = std::move(program);
295 return w;
296}
297
298} // 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 000000000..c6469719e
--- /dev/null
+++ b/runtime/test/d3d12_big_compute_test.cpp
@@ -0,0 +1,978 @@
1// Large pipelines that a submission compiles (LEONIDA_SERIAL_BIG_COMPILES, LEONIDA_BIG_COMPILE_BUDGET_MB), through the D3D12
2// layer on a GPU: real compute modules of more than 128 KiB (big_compute_module.h), small ones, and graphics pipelines of more than
3// 1 MiB. Both settings are read once for each process, so the test runs once for each: with a fixed budget, one that holds
4// nothing, the one read from the machine, one at a time and without a limit. Every run
5// - stores what the CPU computes for each dispatch, and draws the graphics pipelines' cells;
6// - compiles as many large ones at once as the setting allows and no more, and the small ones meanwhile;
7// - gives a pipeline the driver refuses the result it has always had, and its place to the next;
8// - compiles each pipeline once when two queues need the same ones;
9// - ends when the device's last references go while its workers compile and wait for memory.
10// `warmup`: a submission's compiles go before those of the warm-up thread, which waits without holding a pipeline state.
11// `eager`: pipeline states compiled when they are created (LEONIDA_LAZY_COMPUTE=0), by several threads, keep the budget too.
12// The calls that create pipelines are watched, and held back, through the device's vkGetDeviceProcAddr.
13// Self-contained: builds its SPIR-V in memory. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation.
14#include "big_compute_module.h"
15#include "vk_test_device.h"
16#include "d3d12_test_shaders.h"
17#include "test_temp_dir.h"
18#include "../shims/d3d12_com.h"
19#include "../shims/d3d12_pipeline_compile.h"
20#include "../src/large_module_gate.h"
21#include "../src/shader_library.h"
22
23#include <algorithm>
24#include <atomic>
25#include <bit>
26#include <chrono>
27#include <condition_variable>
28#include <cstdint>
29#include <cstdio>
30#include <cstdlib>
31#include <cstring>
32#include <fstream>
33#include <map>
34#include <memory>
35#include <mutex>
36#include <set>
37#include <string>
38#include <thread>
39#include <type_traits>
40#include <utility>
41#include <vector>
42
43namespace {
44
45using namespace std::chrono_literals;
46using d3d12test::Ref;
47using leonida::ReplayResult;
48using bigmodule::Words;
49using bigmodule::op;
50
51constexpr unsigned kBig = 6, kSmall = 4, kCompute = kBig + kSmall, kGraphics = 2;
52constexpr std::size_t kBigBytes = 132 * 1024, kSmallBytes = 12 * 1024;
53constexpr unsigned kExtent = 4; // the render target; each graphics pipeline draws one 2x2 cell
54constexpr unsigned kWords = bigmodule::kLoadBase + bigmodule::kLoadWords;
55
56#define CHECK(expr) \
57 do { \
58 if (!(expr)) { \
59 std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #expr); \
60 return false; \
61 } \
62 } while (0)
63
64// ---- What the settings of this process say. ----
65
66std::string setting(const char* name) {
67 char text[64]{};
68 std::size_t length = 0;
69 return getenv_s(&length, text, name) == 0 && length > 1 ? text : "";
70}
71const bool serial = setting("LEONIDA_SERIAL_BIG_COMPILES") == "1";
72const bool unlimited = setting("LEONIDA_SERIAL_BIG_COMPILES") == "0";
73const bool budgeted = !serial && !unlimited;
74const auto fixed_budget = leonida::large_compile_budget(setting("LEONIDA_BIG_COMPILE_BUDGET_MB").c_str()).fixed;
75
76// ---- The driver's pipeline calls, watched. ----
77
78struct Start {
79 std::thread::id thread;
80 int program = -1; // compute: the index of its module
81 bool large = false;
82};
83
84struct Hooks {
85 std::mutex mutex;
86 std::condition_variable changed;
87 std::map<std::uint64_t, int> programs; // the hash of a compute module's words: its index
88 std::map<VkShaderModule, std::pair<std::size_t, int>> modules; // bytes, program
89 bool closed = false; // large creations wait while it is
90 std::chrono::milliseconds linger{0}; // and each takes at least this long, as does what follows it on its thread
91 std::vector<Start> started;
92 int large_in = 0, most_large = 0, small_done = 0, large_compute_in = 0, most_large_compute = 0;
93 std::uint64_t reserved = 0; // the estimates of the large ones in the driver
94 int over = 0; // how often several were in past the budget, or two where one is allowed
95 int fail_large = -1; // the large compute create (counted from 0) the driver refuses
96 int large_compute = 0;
97 bool track = false; // threads that create a pipeline are counted until they end
98 int live = 0, in_flight = 0, cache_reads = 0;
99 bool cache_read_during_create = false, cache_read_with_workers = false;
100
101 void reset() {
102 std::lock_guard lock(mutex);
103 closed = track = cache_read_during_create = cache_read_with_workers = false;
104 started.clear();
105 most_large = small_done = most_large_compute = over = large_compute = cache_reads = 0;
106 fail_large = -1;
107 linger = 0ms;
108 }
109 void open() {
110 std::lock_guard lock(mutex);
111 closed = false;
112 changed.notify_all();
113 }
114 template<typename Until>
115 bool wait(Until&& until) {
116 std::unique_lock lock(mutex);
117 return changed.wait_for(lock, 20s, until);
118 }
119 bool wait_large(int count) {
120 return wait([&] { return large_in >= count; });
121 }
122 std::size_t creates() {
123 std::lock_guard lock(mutex);
124 return started.size();
125 }
126} hooks;
127
128struct Tracked {
129 bool on = false;
130 ~Tracked() {
131 if (!on) return;
132 std::lock_guard lock(hooks.mutex);
133 --hooks.live;
134 }
135};
136thread_local Tracked tracked;
137
138PFN_vkGetInstanceProcAddr real_instance_proc = nullptr;
139PFN_vkGetDeviceProcAddr real_device_proc = nullptr;
140PFN_vkCreateShaderModule real_create_module = nullptr;
141PFN_vkDestroyShaderModule real_destroy_module = nullptr;
142PFN_vkCreateGraphicsPipelines real_create_graphics = nullptr;
143PFN_vkCreateComputePipelines real_create_compute = nullptr;
144PFN_vkGetPipelineCacheData real_cache_data = nullptr;
145
146std::uint64_t hash(const std::uint32_t* words, std::size_t count) {
147 std::uint64_t h = 0xcbf29ce484222325u;
148 for (std::size_t i = 0; i < count; ++i) h = (h ^ words[i]) * 0x100000001b3u;
149 return h;
150}
151
152struct Creation {
153 bool large = false, compute = false, refused = false;
154 std::uint64_t estimate = 0;
155};
156
157Creation enter_create(bool compute, std::initializer_list<VkShaderModule> modules) {
158 std::unique_lock lock(hooks.mutex);
159 Creation c;
160 c.compute = compute;
161 std::size_t bytes = 0;
162 Start start{std::this_thread::get_id(), -1, false};
163 for (const VkShaderModule module : modules) {
164 const auto found = hooks.modules.find(module);
165 if (found == hooks.modules.end()) continue;
166 bytes += found->second.first;
167 if (compute) start.program = found->second.second;
168 }
169 c.large = start.large = bytes > (compute ? 128 * 1024 : leonida::PipelineCompiles::large_spirv_bytes - 1);
170 c.estimate = leonida::large_module_estimate(bytes);
171 ++hooks.in_flight;
172 hooks.started.push_back(start);
173 if (hooks.track && !tracked.on) {
174 tracked.on = true;
175 ++hooks.live;
176 }
177 if (c.large) {
178 ++hooks.large_in;
179 if (compute) ++hooks.large_compute_in;
180 hooks.most_large = std::max(hooks.most_large, hooks.large_in);
181 hooks.most_large_compute = std::max(hooks.most_large_compute, hooks.large_compute_in);
182 hooks.reserved += c.estimate;
183 // One large compute module at a time; with a budget, several only within it.
184 if (serial && hooks.large_compute_in > 1) ++hooks.over;
185 if (budgeted && fixed_budget && hooks.large_in > 1 && hooks.reserved > *fixed_budget) ++hooks.over;
186 if (compute && hooks.large_compute++ == hooks.fail_large) c.refused = true;
187 }
188 hooks.changed.notify_all();
189 if (c.large) hooks.changed.wait(lock, [] { return !hooks.closed; });
190 const auto linger = hooks.linger;
191 lock.unlock();
192 if (c.large && linger > 0ms) std::this_thread::sleep_for(linger);
193 return c;
194}
195
196void leave_create(const Creation& c) {
197 std::lock_guard lock(hooks.mutex);
198 --hooks.in_flight;
199 if (c.large) {
200 --hooks.large_in;
201 if (c.compute) --hooks.large_compute_in;
202 hooks.reserved -= c.estimate;
203 } else {
204 ++hooks.small_done;
205 }
206 hooks.changed.notify_all();
207}
208
209VKAPI_ATTR VkResult VKAPI_CALL create_module(VkDevice device, const VkShaderModuleCreateInfo* info,
210 const VkAllocationCallbacks* allocator, VkShaderModule* out) {
211 const VkResult result = real_create_module(device, info, allocator, out);
212 if (result == VK_SUCCESS) {
213 std::lock_guard lock(hooks.mutex);
214 const auto found = hooks.programs.find(hash(info->pCode, info->codeSize / 4));
215 hooks.modules[*out] = {info->codeSize, found == hooks.programs.end() ? -1 : found->second};
216 }
217 return result;
218}
219
220// Called between the place a compile gives back and the next one its thread asks for: with a linger, time for another
221// thread to take that place.
222VKAPI_ATTR void VKAPI_CALL destroy_module(VkDevice device, VkShaderModule module, const VkAllocationCallbacks* allocator) {
223 std::chrono::milliseconds linger;
224 {
225 std::lock_guard lock(hooks.mutex);
226 linger = hooks.linger;
227 }
228 if (linger > 0ms) std::this_thread::sleep_for(linger);
229 real_destroy_module(device, module, allocator);
230}
231
232VKAPI_ATTR VkResult VKAPI_CALL create_graphics(VkDevice device, VkPipelineCache cache, std::uint32_t count,
233 const VkGraphicsPipelineCreateInfo* infos,
234 const VkAllocationCallbacks* allocator, VkPipeline* out) {
235 VkShaderModule modules[2]{};
236 for (std::uint32_t i = 0; i < std::min(infos->stageCount, 2u); ++i) modules[i] = infos->pStages[i].module;
237 const Creation c = enter_create(false, {modules[0], modules[1]});
238 const VkResult result = real_create_graphics(device, cache, count, infos, allocator, out);
239 leave_create(c);
240 return result;
241}
242
243VKAPI_ATTR VkResult VKAPI_CALL create_compute(VkDevice device, VkPipelineCache cache, std::uint32_t count,
244 const VkComputePipelineCreateInfo* infos,
245 const VkAllocationCallbacks* allocator, VkPipeline* out) {
246 const Creation c = enter_create(true, {infos->stage.module});
247 const VkResult result = c.refused ? VK_ERROR_UNKNOWN
248 : real_create_compute(device, cache, count, infos, allocator, out);
249 leave_create(c);
250 return result;
251}
252
253VKAPI_ATTR VkResult VKAPI_CALL cache_data(VkDevice device, VkPipelineCache cache, std::size_t* size, void* data) {
254 {
255 std::lock_guard lock(hooks.mutex);
256 ++hooks.cache_reads;
257 if (hooks.in_flight) hooks.cache_read_during_create = true;
258 if (hooks.live > (tracked.on ? 1 : 0)) hooks.cache_read_with_workers = true;
259 }
260 return real_cache_data(device, cache, size, data);
261}
262
263VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL device_proc(VkDevice device, const char* name) {
264 const PFN_vkVoidFunction real = real_device_proc(device, name);
265 if (!real) return nullptr;
266 const auto watch = [&](const char* which, auto& kept, auto* mine) -> PFN_vkVoidFunction {
267 if (std::strcmp(name, which)) return nullptr;
268 kept = reinterpret_cast<std::remove_reference_t<decltype(kept)>>(real);
269 return reinterpret_cast<PFN_vkVoidFunction>(mine);
270 };
271 if (const auto f = watch("vkCreateShaderModule", real_create_module, create_module)) return f;
272 if (const auto f = watch("vkDestroyShaderModule", real_destroy_module, destroy_module)) return f;
273 if (const auto f = watch("vkCreateGraphicsPipelines", real_create_graphics, create_graphics)) return f;
274 if (const auto f = watch("vkCreateComputePipelines", real_create_compute, create_compute)) return f;
275 if (const auto f = watch("vkGetPipelineCacheData", real_cache_data, cache_data)) return f;
276 return real;
277}
278
279VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL instance_proc(VkInstance instance, const char* name) {
280 if (!std::strcmp(name, "vkGetDeviceProcAddr")) {
281 real_device_proc = reinterpret_cast<PFN_vkGetDeviceProcAddr>(real_instance_proc(instance, name));
282 return reinterpret_cast<PFN_vkVoidFunction>(device_proc);
283 }
284 return real_instance_proc(instance, name);
285}
286
287// ---- The shaders. ----
288
289std::uint32_t bits(float f) { return std::bit_cast<std::uint32_t>(f); }
290
291// 1.25 MiB of OpString, which compile to nothing: a graphics pipeline that is large.
292void pad(Words& w, std::uint32_t first_id) {
293 for (std::uint32_t i = 0; i < 5; ++i) {
294 const std::size_t at = w.size();
295 w.resize(at + 65535, 0x20202020u);
296 w[at] = 65535u << 16 | 7;
297 w[at + 1] = first_id + i;
298 w.back() = 0;
299 }
300}
301
302// A full-screen triangle from VertexIndex.
303Words vertex_words() {
304 Words w = {0x07230203u, 0x00010500u, 0u, 42u, 0u};
305 op(w, 17, {1}); // Capability Shader
306 op(w, 14, {0, 1}); // MemoryModel Logical GLSL450
307 op(w, 15, {0, 4, 0x6e69616du, 0u, 10, 11}); // EntryPoint Vertex "main"
308 op(w, 71, {10, 11, 0}); // BuiltIn Position
309 op(w, 71, {11, 11, 42}); // BuiltIn VertexIndex
310 op(w, 19, {1});
311 op(w, 33, {2, 1});
312 op(w, 22, {3, 32});
313 op(w, 23, {6, 3, 4});
314 op(w, 21, {15, 32, 1});
315 op(w, 32, {7, 3, 6});
316 op(w, 32, {8, 1, 15});
317 op(w, 59, {7, 10, 3});
318 op(w, 59, {8, 11, 1});
319 op(w, 43, {15, 24, 1});
320 op(w, 43, {15, 25, 2});
321 op(w, 43, {3, 26, bits(2.0f)});
322 op(w, 43, {3, 27, bits(-1.0f)});
323 op(w, 43, {3, 28, bits(0.0f)});
324 op(w, 43, {3, 29, bits(1.0f)});
325 op(w, 54, {1, 4, 0, 2});
326 op(w, 248, {30});
327 op(w, 61, {15, 31, 11});
328 op(w, 196, {15, 32, 31, 24}); // index << 1
329 op(w, 199, {15, 33, 32, 25}); // & 2
330 op(w, 199, {15, 34, 31, 25}); // index & 2
331 op(w, 111, {3, 35, 33});
332 op(w, 111, {3, 36, 34});
333 op(w, 133, {3, 37, 35, 26});
334 op(w, 133, {3, 38, 36, 26});
335 op(w, 129, {3, 39, 37, 27});
336 op(w, 129, {3, 40, 38, 27});
337 op(w, 80, {6, 41, 39, 40, 28, 29});
338 op(w, 62, {10, 41});
339 op(w, 253, {});
340 op(w, 56, {});
341 return w;
342}
343
344// The colour (n / 255, 1 - n / 255, 0, 1).
345Words fragment_words(unsigned n) {
346 Words w = {0x07230203u, 0x00010500u, 0u, 40u, 0u};
347 op(w, 17, {1});
348 op(w, 14, {0, 1});
349 op(w, 15, {4, 4, 0x6e69616du, 0u, 9}); // EntryPoint Fragment "main"
350 op(w, 16, {4, 7}); // OriginUpperLeft
351 pad(w, 30);
352 op(w, 71, {9, 30, 0}); // Location 0
353 op(w, 19, {1});
354 op(w, 33, {2, 1});
355 op(w, 22, {3, 32});
356 op(w, 23, {6, 3, 4});
357 op(w, 32, {10, 3, 6});
358 op(w, 59, {10, 9, 3});
359 op(w, 43, {3, 20, bits(float(n) / 255.0f)});
360 op(w, 43, {3, 21, bits(float(255 - n) / 255.0f)});
361 op(w, 43, {3, 22, bits(0.0f)});
362 op(w, 43, {3, 23, bits(1.0f)});
363 op(w, 44, {6, 24, 20, 21, 22, 23});
364 op(w, 54, {1, 4, 0, 2});
365 op(w, 248, {11});
366 op(w, 62, {9, 24});
367 op(w, 253, {});
368 op(w, 56, {});
369 return w;
370}
371
372std::vector<std::uint8_t> program(unsigned stage, unsigned n) {
373 return d3d12test::fssm_program({0x42434f00u + stage, n, 0xbf810000u});
374}
375
376std::vector<bigmodule::Program> programs(kCompute); // what each compute module runs
377std::vector<std::size_t> module_bytes(kCompute);
378
379bool write_library(const std::filesystem::path& dir) {
380 const auto write = [&](const std::string& name, const Words& words) {
381 std::ofstream f(dir / (name + ".spv"), std::ios::binary | std::ios::trunc);
382 f.write(reinterpret_cast<const char*>(words.data()), std::streamsize(words.size() * 4));
383 return bool(f);
384 };
385 CHECK(write("vs", vertex_words()));
386 std::ofstream index(dir / "index.json", std::ios::binary | std::ios::trunc);
387 index << "{\"vs\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(program(0, 0))
388 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": []}";
389 for (unsigned n = 0; n < kGraphics; ++n) {
390 const std::string name = "ps" + std::to_string(n);
391 CHECK(write(name, fragment_words(n)));
392 index << ",\n\"" << name << "\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(program(1, n))
393 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"inputs\": [], \"outputs\": [0]}";
394 }
395 for (unsigned n = 0; n < kCompute; ++n) {
396 const std::string name = "cs" + std::to_string(n);
397 // Every large one a little larger than the one before, so that the order by size is known.
398 const Words words = bigmodule::make(n < kBig ? kBigBytes + n * 1024 : kSmallBytes, 20251125 + n, &programs[n]);
399 module_bytes[n] = words.size() * 4;
400 CHECK((module_bytes[n] > 128 * 1024) == (n < kBig));
401 hooks.programs[hash(words.data(), words.size())] = int(n);
402 CHECK(write(name, words));
403 index << ",\n\"" << name << "\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(program(2, n))
404 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"local_size\": [1, 1, 1], \"wave64\": false}";
405 }
406 index << "}";
407 return bool(index);
408}
409
410// ---- The device and what it runs. ----
411
412struct Setup {
413 vktest::Device* vk;
414 std::string library;
415
416 bool device(const char* threads, Ref<ID3D12Device>& out) const {
417 _putenv_s("LEONIDA_PIPELINE_THREADS", threads);
418 rt::d3d12::VulkanDeviceInfo info{};
419 info.get_instance_proc = instance_proc;
420 info.instance = vk->instance;
421 info.physical = vk->physical;
422 info.device = vk->device;
423 info.queue = vk->queue;
424 info.queue_family = vk->family;
425 info.buffer_device_address = true;
426 info.subgroup = vk->subgroup;
427 info.features = vk->enabled;
428 info.shader_dir = library;
429 CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&out.p))));
430 return true;
431 }
432};
433
434struct Pipelines {
435 Ref<ID3D12RootSignature> root;
436 std::vector<ID3D12PipelineState*> compute, graphics;
437 ~Pipelines() { release(); }
438 void release() {
439 for (auto* s : compute)
440 if (s) s->Release();
441 for (auto* s : graphics) s->Release();
442 compute.clear();
443 graphics.clear();
444 }
445
446 static ID3D12PipelineState* compute_state(ID3D12Device* dev, ID3D12RootSignature* root, unsigned n) {
447 const auto cs = d3d12test::shader_container(program(2, n));
448 D3D12_COMPUTE_PIPELINE_STATE_DESC pd{};
449 pd.pRootSignature = root;
450 pd.CS = {cs.data(), cs.size()};
451 ID3D12PipelineState* state = nullptr;
452 return SUCCEEDED(dev->CreateComputePipelineState(&pd, IID_PPV_ARGS(&state))) ? state : nullptr;
453 }
454
455 // The compute states on `threads` threads.
456 bool create(ID3D12Device* dev, unsigned threads = 1) {
457 D3D12_ROOT_PARAMETER params[2]{};
458 params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
459 params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
460 params[1].Constants.Num32BitValues = 1;
461 D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc{};
462 desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
463 desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
464 const auto blob = d3d12test::serialize_root_signature(desc);
465 CHECK(SUCCEEDED(dev->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root.p))));
466 compute.assign(kCompute, nullptr);
467 std::vector<std::thread> creating;
468 for (unsigned t = 1; t < threads; ++t)
469 creating.emplace_back([&, t] {
470 for (unsigned n = t; n < kCompute; n += threads) compute[n] = compute_state(dev, root.p, n);
471 });
472 for (unsigned n = 0; n < kCompute; n += threads) compute[n] = compute_state(dev, root.p, n);
473 for (auto& t : creating) t.join();
474 CHECK(std::find(compute.begin(), compute.end(), nullptr) == compute.end());
475 const auto vs = d3d12test::shader_container(program(0, 0));
476 for (unsigned n = 0; n < kGraphics; ++n) {
477 const auto ps = d3d12test::shader_container(program(1, n));
478 D3D12_GRAPHICS_PIPELINE_STATE_DESC pd{};
479 pd.pRootSignature = root.p;
480 pd.VS = {vs.data(), vs.size()};
481 pd.PS = {ps.data(), ps.size()};
482 for (auto& rt : pd.BlendState.RenderTarget) {
483 rt.SrcBlend = rt.SrcBlendAlpha = D3D12_BLEND_ONE;
484 rt.DestBlend = rt.DestBlendAlpha = D3D12_BLEND_ZERO;
485 rt.BlendOp = rt.BlendOpAlpha = D3D12_BLEND_OP_ADD;
486 rt.LogicOp = D3D12_LOGIC_OP_NOOP;
487 rt.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
488 }
489 pd.SampleMask = UINT_MAX;
490 pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
491 pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
492 pd.RasterizerState.DepthClipEnable = TRUE;
493 pd.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS;
494 pd.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
495 pd.NumRenderTargets = 1;
496 pd.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
497 pd.SampleDesc = {1, 0};
498 ID3D12PipelineState* state = nullptr;
499 CHECK(SUCCEEDED(dev->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&state))));
500 graphics.push_back(state);
501 }
502 return true;
503 }
504};
505
506// A queue and a list that dispatches `compute` (and draws the graphics pipelines), then copies what they wrote back.
507struct Frame {
508 std::vector<unsigned> compute;
509 bool graphics = false;
510 Ref<ID3D12Resource> target, buffer, readback;
511 Ref<ID3D12DescriptorHeap> rtvs;
512 Ref<ID3D12CommandQueue> queue;
513 Ref<ID3D12CommandAllocator> allocator;
514 Ref<ID3D12GraphicsCommandList> list;
515 Ref<ID3D12Fence> fence;
516 UINT64 fence_value = 0;
517 D3D12_PLACED_SUBRESOURCE_FOOTPRINT foot{};
518
519 bool create(ID3D12Device* dev, const Pipelines& p, std::vector<unsigned> dispatched, bool draws) {
520 compute = std::move(dispatched);
521 graphics = draws;
522 const D3D12_HEAP_PROPERTIES def{D3D12_HEAP_TYPE_DEFAULT}, back{D3D12_HEAP_TYPE_READBACK};
523 D3D12_RESOURCE_DESC td{};
524 td.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
525 td.Width = td.Height = kExtent;
526 td.DepthOrArraySize = td.MipLevels = 1;
527 td.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
528 td.SampleDesc = {1, 0};
529 td.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
530 CHECK(SUCCEEDED(dev->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &td, D3D12_RESOURCE_STATE_RENDER_TARGET,
531 nullptr, IID_PPV_ARGS(&target.p))));
532 const auto bd = d3d12test::buffer_desc(4 * kWords, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
533 CHECK(SUCCEEDED(dev->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &bd,
534 D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr,
535 IID_PPV_ARGS(&buffer.p))));
536 UINT64 image_bytes = 0;
537 dev->GetCopyableFootprints(&td, 0, 1, 0, &foot, nullptr, nullptr, &image_bytes);
538 CHECK(image_bytes <= 4096);
539 const auto rd = d3d12test::buffer_desc(4096 + 4 * kWords);
540 CHECK(SUCCEEDED(dev->CreateCommittedResource(&back, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COPY_DEST,
541 nullptr, IID_PPV_ARGS(&readback.p))));
542 const D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1};
543 CHECK(SUCCEEDED(dev->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&rtvs.p))));
544 const auto rtv = rtvs->GetCPUDescriptorHandleForHeapStart();
545 dev->CreateRenderTargetView(target.p, nullptr, rtv);
546 const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT};
547 CHECK(SUCCEEDED(dev->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p))));
548 CHECK(SUCCEEDED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
549 CHECK(SUCCEEDED(dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
550 CHECK(SUCCEEDED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
551 IID_PPV_ARGS(&list.p))));
552 const FLOAT clear[4] = {0, 0, 0, 0};
553 list->ClearRenderTargetView(rtv, clear, 0, nullptr);
554 list->SetComputeRootSignature(p.root.p);
555 list->SetComputeRootUnorderedAccessView(0, buffer->GetGPUVirtualAddress());
556 for (const unsigned n : compute) {
557 list->SetPipelineState(p.compute[n]);
558 list->SetComputeRoot32BitConstant(1, n, 0);
559 list->Dispatch(1, 1, 1);
560 }
561 if (graphics) {
562 list->SetGraphicsRootSignature(p.root.p);
563 list->OMSetRenderTargets(1, &rtv, FALSE, nullptr);
564 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
565 const D3D12_VIEWPORT vp{0, 0, float(kExtent), float(kExtent), 0, 1};
566 list->RSSetViewports(1, &vp);
567 for (unsigned n = 0; n < kGraphics; ++n) {
568 const D3D12_RECT cell{LONG(2 * n), 0, LONG(2 * n + 2), 2};
569 list->RSSetScissorRects(1, &cell);
570 list->SetPipelineState(p.graphics[n]);
571 list->DrawInstanced(3, 1, 0, 0);
572 }
573 }
574 const D3D12_RESOURCE_BARRIER to_source[2] = {
575 d3d12test::transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE),
576 d3d12test::transition(buffer.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)};
577 list->ResourceBarrier(2, to_source);
578 D3D12_TEXTURE_COPY_LOCATION src{target.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX};
579 src.SubresourceIndex = 0;
580 D3D12_TEXTURE_COPY_LOCATION dst{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT};
581 dst.PlacedFootprint = foot;
582 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
583 list->CopyBufferRegion(readback.p, 4096, buffer.p, 0, 4 * kWords);
584 const D3D12_RESOURCE_BARRIER back_again[2] = {
585 d3d12test::transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET),
586 d3d12test::transition(buffer.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)};
587 list->ResourceBarrier(2, back_again);
588 CHECK(SUCCEEDED(list->Close()));
589 return true;
590 }
591
592 ReplayResult submit() {
593 ID3D12CommandList* lists[] = {list.p};
594 queue->ExecuteCommandLists(1, lists);
595 const ReplayResult result = rt::d3d12::last_execute_result(queue.p);
596 queue->Signal(fence.p, ++fence_value);
597 fence->SetEventOnCompletion(fence_value, nullptr);
598 return result;
599 }
600
601 // What the shaders stored and drew; `dropped` is the compute program that was not built, whose word stays 0. The
602 // readback buffer is cleared, so stale bytes cannot pass.
603 bool right(int dropped = -1) {
604 void* mapped = nullptr;
605 CHECK(SUCCEEDED(readback->Map(0, nullptr, &mapped)) && mapped);
606 auto* bytes = static_cast<std::uint8_t*>(mapped);
607 bool ok = true;
608 std::uint32_t words[kWords];
609 std::memcpy(words, bytes + 4096, sizeof words);
610 for (const unsigned n : compute) {
611 const std::uint32_t want = int(n) == dropped ? 0 : programs[n].run(n);
612 if (words[n] != want) {
613 std::fprintf(stderr, "compute program %u stored 0x%08x, not 0x%08x\n", n, words[n], want);
614 ok = false;
615 }
616 }
617 for (unsigned n = 0; graphics && n < kGraphics; ++n)
618 for (unsigned y = 0; y < 2; ++y)
619 for (unsigned x = 2 * n; x < 2 * n + 2; ++x) {
620 const auto* pixel = bytes + foot.Offset + y * foot.Footprint.RowPitch + 4 * x;
621 if (pixel[0] != n || pixel[1] != 255 - n || pixel[2] != 0 || pixel[3] != 255) {
622 std::fprintf(stderr, "graphics pipeline %u drew %u %u %u %u\n", n, pixel[0], pixel[1], pixel[2],
623 pixel[3]);
624 ok = false;
625 }
626 }
627 std::memset(bytes, 0xee, 4096 + 4 * kWords);
628 readback->Unmap(0, nullptr);
629 return ok;
630 }
631};
632
633std::vector<unsigned> all_compute() {
634 std::vector<unsigned> out;
635 for (unsigned n = 0; n < kCompute; ++n) out.push_back(n);
636 return out;
637}
638
639std::uint64_t estimate(unsigned n) { return leonida::large_module_estimate(module_bytes[n]); }
640
641// How many of the large compute modules are in the driver at once, with five threads to compile them; 0: not known (the
642// budget is read from the machine).
643int expected_at_once() {
644 if (serial) return 1;
645 if (unlimited) return 5;
646 if (!fixed_budget) return 0;
647 // The first wave is the largest, in order, while they fit.
648 std::uint64_t sum = 0;
649 int count = 0;
650 for (unsigned n = kBig; n-- > 0 && sum + estimate(n) <= *fixed_budget; ++count) sum += estimate(n);
651 return std::clamp(count, 1, 5);
652}
653
654// The large compute modules are held back in the driver until as many as may be are in, and no more come.
655bool side_by_side(const Setup& setup) {
656 Ref<ID3D12Device> dev;
657 CHECK(setup.device("4", dev));
658 Pipelines pipelines;
659 Frame frame;
660 hooks.reset();
661 CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, all_compute(), false));
662 CHECK(hooks.creates() == 0); // nothing is compiled at creation
663 const int at_once = expected_at_once();
664 hooks.closed = true;
665 ReplayResult result = ReplayResult::unsupported;
666 std::thread submitting([&] { result = frame.submit(); });
667 const bool filled = hooks.wait_large(std::max(at_once, 1));
668 // With a thread to spare, the small ones are compiled while the large ones wait (unlimited: every thread has a large one).
669 const bool small_ones = unlimited || !at_once || hooks.wait([] { return hooks.small_done == int(kSmall); });
670 std::this_thread::sleep_for(300ms);
671 int held = 0;
672 {
673 std::lock_guard lock(hooks.mutex);
674 held = hooks.large_in;
675 }
676 hooks.open();
677 submitting.join();
678 CHECK(filled);
679 CHECK(!at_once || held == at_once);
680 CHECK(small_ones);
681 CHECK(result == ReplayResult::success && frame.right());
682 CHECK(hooks.over == 0);
683 CHECK(hooks.creates() == kCompute); // each once
684 CHECK(!at_once || hooks.most_large <= at_once || unlimited);
685 CHECK(frame.submit() == ReplayResult::success && frame.right() && hooks.creates() == kCompute);
686 return true;
687}
688
689// The same values whatever compiles them, without workers (each where prepare() meets it) and with them.
690bool same_values(const Setup& setup) {
691 for (const char* threads : {"0", "16"}) {
692 Ref<ID3D12Device> dev;
693 CHECK(setup.device(threads, dev));
694 Pipelines pipelines;
695 Frame frame;
696 hooks.reset();
697 CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, all_compute(), true));
698 CHECK(frame.submit() == ReplayResult::success && frame.right());
699 CHECK(hooks.over == 0);
700 CHECK(hooks.creates() == kCompute + kGraphics);
701 CHECK(*threads != '0' || hooks.most_large == 1);
702 }
703 return true;
704}
705
706// A graphics pipeline whose estimate is past the budget (or the one at a time of serial) is in alone among the large ones,
707// and the small ones are compiled beside it.
708bool graphics_among_the_large(const Setup& setup) {
709 Ref<ID3D12Device> dev;
710 CHECK(setup.device("4", dev));
711 Pipelines pipelines;
712 Frame frame;
713 hooks.reset();
714 CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, all_compute(), true));
715 hooks.closed = true;
716 ReplayResult result = ReplayResult::unsupported;
717 std::thread submitting([&] { result = frame.submit(); });
718 const bool one = hooks.wait_large(1);
719 const bool small_ones = unlimited || !expected_at_once() ||
720 hooks.wait([] { return hooks.small_done == int(kSmall); });
721 std::this_thread::sleep_for(300ms);
722 int held = 0;
723 bool first_is_graphics = false;
724 {
725 std::lock_guard lock(hooks.mutex);
726 held = hooks.large_in;
727 for (const Start& s : hooks.started)
728 if (s.large) {
729 first_is_graphics = s.program < 0;
730 break;
731 }
732 }
733 hooks.open();
734 submitting.join();
735 CHECK(one && small_ones);
736 if (budgeted && fixed_budget) CHECK(held == 1 && first_is_graphics); // the largest first
737 if (serial) CHECK(held == 1);
738 CHECK(result == ReplayResult::success && frame.right());
739 CHECK(hooks.over == 0);
740 CHECK(hooks.creates() == kCompute + kGraphics);
741 return true;
742}
743
744// Two large graphics pipelines and nothing else: one after the other, or both at once without a limit.
745bool graphics_only(const Setup& setup) {
746 Ref<ID3D12Device> dev;
747 CHECK(setup.device("4", dev));
748 Pipelines pipelines;
749 Frame frame;
750 hooks.reset();
751 CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, {}, true));
752 hooks.closed = true;
753 ReplayResult result = ReplayResult::unsupported;
754 std::thread submitting([&] { result = frame.submit(); });
755 const int at_once = unlimited ? 2 : 1;
756 const bool filled = hooks.wait_large(at_once);
757 std::this_thread::sleep_for(300ms);
758 int held = 0;
759 {
760 std::lock_guard lock(hooks.mutex);
761 held = hooks.large_in;
762 }
763 hooks.open();
764 submitting.join();
765 CHECK(filled);
766 if (!budgeted || fixed_budget) CHECK(held == at_once);
767 CHECK(result == ReplayResult::success && frame.right());
768 CHECK(hooks.over == 0 && hooks.creates() == kGraphics);
769 return true;
770}
771
772// The driver refuses one large compute module: its dispatch is dropped, the rest runs, and it is not tried again. Its place
773// goes to the next.
774bool refused(const Setup& setup) {
775 for (const char* threads : {"0", "4"}) {
776 Ref<ID3D12Device> dev;
777 CHECK(setup.device(threads, dev));
778 Pipelines pipelines;
779 Frame frame;
780 hooks.reset();
781 CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, all_compute(), false));
782 hooks.fail_large = 2;
783 CHECK(frame.submit() == ReplayResult::success);
784 int dropped = -1;
785 {
786 std::lock_guard lock(hooks.mutex);
787 int seen = 0;
788 for (const Start& s : hooks.started)
789 if (s.large && s.program >= 0 && seen++ == 2) dropped = s.program;
790 }
791 CHECK(dropped >= 0);
792 CHECK(frame.right(dropped));
793 CHECK(hooks.creates() == kCompute);
794 CHECK(frame.submit() == ReplayResult::success && frame.right(dropped));
795 CHECK(hooks.creates() == kCompute);
796 }
797 return true;
798}
799
800// Two queues submit the same pipelines at once: each is compiled once, the budget is kept, and nobody waits for ever.
801bool two_queues(const Setup& setup) {
802 Ref<ID3D12Device> dev;
803 CHECK(setup.device("4", dev));
804 Pipelines pipelines;
805 Frame frames[2];
806 CHECK(pipelines.create(dev.p));
807 auto backwards = all_compute();
808 std::reverse(backwards.begin(), backwards.end());
809 CHECK(frames[0].create(dev.p, pipelines, all_compute(), true));
810 CHECK(frames[1].create(dev.p, pipelines, backwards, true));
811 hooks.reset();
812 ReplayResult results[2]{};
813 std::thread threads[2];
814 for (int i = 0; i < 2; ++i) threads[i] = std::thread([&, i] { results[i] = frames[i].submit(); });
815 for (auto& t : threads) t.join();
816 for (int i = 0; i < 2; ++i) CHECK(results[i] == ReplayResult::success && frames[i].right());
817 CHECK(hooks.creates() == kCompute + kGraphics);
818 CHECK(hooks.over == 0);
819 return true;
820}
821
822// The device's last references are released by the thread whose submission compiles, with large ones waiting for room.
823bool device_destroyed(const Setup& setup) {
824 _putenv_s("LEONIDA_PIPELINE_CACHE_BYTES", "1"); // read the cache at teardown, write no file
825 Ref<ID3D12Device> dev;
826 CHECK(setup.device("4", dev));
827 auto pipelines = std::make_unique<Pipelines>();
828 auto frame = std::make_unique<Frame>();
829 hooks.reset();
830 CHECK(pipelines->create(dev.p) && frame->create(dev.p, *pipelines, all_compute(), true));
831 hooks.track = true;
832 hooks.closed = true;
833 ReplayResult result = ReplayResult::unsupported;
834 bool ok = false;
835 std::thread submitting([&] {
836 result = frame->submit();
837 ok = frame->right();
838 frame.reset();
839 pipelines.reset();
840 });
841 const bool compiling = hooks.wait_large(1);
842 std::this_thread::sleep_for(100ms);
843 dev.reset();
844 hooks.open();
845 submitting.join();
846 _putenv_s("LEONIDA_PIPELINE_CACHE_BYTES", "0");
847 CHECK(compiling);
848 CHECK(result == ReplayResult::success && ok);
849 CHECK(hooks.cache_reads > 0);
850 CHECK(!hooks.cache_read_during_create);
851 CHECK(!hooks.cache_read_with_workers);
852 CHECK(hooks.live == 0);
853 return true;
854}
855
856// One place for large compiles. The warm-up thread has it, and wants the next one after it; a submission that needs four
857// others, one of which the warm-up thread waits to build, gets them all first, and builds that one itself.
858bool warmup(const Setup& setup) {
859 Ref<ID3D12Device> dev;
860 CHECK(setup.device("4", dev));
861 Pipelines pipelines;
862 Frame frame;
863 hooks.reset();
864 hooks.closed = true;
865 hooks.linger = 100ms;
866 CHECK(pipelines.create(dev.p));
867 if (!hooks.wait_large(1)) {
868 hooks.open();
869 CHECK(!"the warm-up thread compiles a large one");
870 }
871 std::thread::id warm;
872 int first = -1;
873 {
874 std::lock_guard lock(hooks.mutex);
875 for (const Start& s : hooks.started)
876 if (s.large) warm = s.thread, first = s.program;
877 }
878 CHECK(first == 0); // their sizes rise with their numbers
879 const std::vector<unsigned> wanted = {4, 5, 3, 1}; // 1 is what the warm-up thread builds after 0
880 CHECK(frame.create(dev.p, pipelines, wanted, false));
881 const std::size_t before = hooks.creates();
882 ReplayResult result = ReplayResult::unsupported;
883 std::thread submitting([&] { result = frame.submit(); });
884 std::this_thread::sleep_for(500ms);
885 const bool waits = hooks.creates() == before; // the place is taken
886 hooks.open();
887 submitting.join();
888 const bool done = result == ReplayResult::success && frame.right();
889 rt::d3d12::PipelineCompiler::instance().wait_idle(); // the warm-up thread builds the rest
890 std::vector<Start> started;
891 {
892 std::lock_guard lock(hooks.mutex);
893 started = hooks.started;
894 }
895 CHECK(waits);
896 CHECK(done);
897 CHECK(hooks.over == 0 && hooks.most_large == 1);
898 std::set<int> once;
899 for (const Start& s : started) once.insert(s.program);
900 CHECK(started.size() == kCompute && once.size() == kCompute); // each once
901 std::erase_if(started, [](const Start& s) { return !s.large; });
902 std::set<int> built;
903 for (std::size_t i = 1; i <= wanted.size(); ++i) {
904 CHECK(started[i].thread != warm); // none of the warm-up's between two of the submission's
905 built.insert(started[i].program);
906 }
907 CHECK(built == std::set<int>(wanted.begin(), wanted.end()));
908 for (std::size_t i = wanted.size() + 1; i < started.size(); ++i) CHECK(started[i].thread == warm);
909 return true;
910}
911
912// The large ones that four threads create at once are held back in the driver until as many as may be are in.
913bool eager(const Setup& setup) {
914 Ref<ID3D12Device> dev;
915 CHECK(setup.device("4", dev));
916 Pipelines pipelines;
917 Frame frame;
918 hooks.reset();
919 hooks.closed = true;
920 bool created = false;
921 std::thread creating([&] { created = pipelines.create(dev.p, 4); });
922 const bool one = hooks.wait_large(1);
923 std::this_thread::sleep_for(300ms);
924 int held = 0;
925 {
926 std::lock_guard lock(hooks.mutex);
927 held = hooks.large_in;
928 }
929 hooks.open();
930 creating.join();
931 CHECK(one && created);
932 CHECK(held == expected_at_once());
933 CHECK(hooks.over == 0 && hooks.creates() == kCompute);
934 CHECK(frame.create(dev.p, pipelines, all_compute(), false));
935 CHECK(frame.submit() == ReplayResult::success && frame.right());
936 CHECK(hooks.creates() == kCompute);
937 return true;
938}
939
940bool run(const Setup& setup, const std::string& scenario) {
941 if (scenario == "warmup") return warmup(setup);
942 if (scenario == "eager") return eager(setup);
943 return side_by_side(setup) && same_values(setup) && graphics_among_the_large(setup) && graphics_only(setup) &&
944 refused(setup) && two_queues(setup) && device_destroyed(setup);
945}
946
947} // namespace
948
949int main(int argc, char** argv) {
950 const std::string scenario = argc > 1 ? argv[1] : "";
951 vktest::Device vk;
952 vk.request_buffer_device_address = true;
953 const auto status = vk.initialize();
954 if (status == vktest::DeviceStatus::unavailable) return 77;
955 if (status != vktest::DeviceStatus::ready) return 1;
956 VkPhysicalDeviceProperties properties{};
957 vk.instance_fn<PFN_vkGetPhysicalDeviceProperties>("vkGetPhysicalDeviceProperties")(vk.physical, &properties);
958 if (!vk.buffer_device_address || !vk.enabled.shaderInt64) {
959 std::printf("SKIP: the GPU lacks bufferDeviceAddress or shaderInt64\n");
960 return 77;
961 }
962 if (properties.limits.maxPushConstantsSize < 144) {
963 std::printf("SKIP: maxPushConstantsSize %u, below the 144-byte block\n", properties.limits.maxPushConstantsSize);
964 return 77;
965 }
966 real_instance_proc = vk.instance_proc;
967 _putenv_s("LEONIDA_PIPELINE_CACHE_BYTES", "0"); // no session file in or out
968 if (scenario != "warmup") _putenv_s("LEONIDA_COMPUTE_WARMUP", "0"); // every compile is a submission's
969 const testfiles::ScratchDir library("leonida_big_compute_test");
970 if (!write_library(library.path())) return 1;
971 if (!run({&vk, library.path().string()}, scenario)) return 1;
972 if (vk.validation_errors()) {
973 std::fprintf(stderr, "FAIL: %u validation errors\n", vk.validation_errors());
974 return 1;
975 }
976 std::printf("d3d12_big_compute_test: passed on %s\n", properties.deviceName);
977 return 0;
978}
diff --git a/runtime/test/gfx10_descriptors_test.cpp b/runtime/test/gfx10_descriptors_test.cpp
index efd0ce4ee..f30d7f026 100644
--- a/runtime/test/gfx10_descriptors_test.cpp
+++ b/runtime/test/gfx10_descriptors_test.cpp
@@ -114,6 +114,25 @@ int main() {
114 CHECK(is_image(words) && decode(words, out) && out == in); 114 CHECK(is_image(words) && decode(words, out) && out == in);
115 } 115 }
116 116
117 ImageWords volume_words = encode(Image{.type = ImageType::image_3d, .depth = 16,
118 .first_mip = 1, .mip_count = 2, .resource_mips = 4});
119 volume_words[4] |= 37u << 16;
120 CHECK(decode(volume_words, image) && image.first_layer == 37 && image.depth == 16);
121 CHECK(!has_hardware_volume_uav_slice_offset(volume_words, image));
122 const auto volume_range = vulkan_subresource_range(image, VK_IMAGE_ASPECT_COLOR_BIT);
123 CHECK(volume_range.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT);
124 CHECK(volume_range.baseMipLevel == 1 && volume_range.levelCount == 2);
125 CHECK(volume_range.baseArrayLayer == 0 && volume_range.layerCount == 1);
126 volume_words = encode(Image{.type = ImageType::image_3d, .depth = 7, .first_mip = 1, .resource_mips = 4});
127 volume_words[4] |= 2u << 16;
128 volume_words[5] |= 1u;
129 CHECK(decode(volume_words, image) && has_hardware_volume_uav_slice_offset(volume_words, image));
130 volume_words[4] &= 0xffffu;
131 CHECK(decode(volume_words, image) && !has_hardware_volume_uav_slice_offset(volume_words, image));
132
133 const auto array_range = vulkan_subresource_range(images[2], VK_IMAGE_ASPECT_COLOR_BIT);
134 CHECK(array_range.baseArrayLayer == 3 && array_range.layerCount == 7);
135
117 // Bits this header does not encode are ignored: SW_MODE and BC_SWIZZLE (word 3), PITCH_MSB (word 4), PERF_MOD 136 // Bits this header does not encode are ignored: SW_MODE and BC_SWIZZLE (word 3), PITCH_MSB (word 4), PERF_MOD
118 // and the rest of word 5, the compression and metadata fields of words 6 and 7, RESOURCE_LEVEL (word 2 bit 31). 137 // and the rest of word 5, the compression and metadata fields of words 6 and 7, RESOURCE_LEVEL (word 2 bit 31).
119 ImageWords busy = encode(images[3]); 138 ImageWords busy = encode(images[3]);
diff --git a/runtime/test/large_module_gate.h b/runtime/test/large_module_gate.h
index ea805c926..fcd29ed0e 100644
--- a/runtime/test/large_module_gate.h
+++ b/runtime/test/large_module_gate.h
@@ -1,181 +1,4 @@
1// How many large SPIR-V modules vk_pipeline_check lets into the driver at once, by a memory budget. 1// Moved to runtime/src: the runtime uses it too (large_module_gate.h there).
2//
3// Measured on RADV GFX1201 (Mesa 25.3.6) with the Mesa shader cache off: a 5.7 MB translated ray-tracing compute
4// 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.
5// Compiling the large ones strictly one at a time left the other threads idle: 40 modules (27 over 4 MiB) on 6
6// threads took 308 s exclusively and 75 s in parallel, 7.0 GB and 8.7 GB peak. kBytesPerSpirvByte keeps a margin
7// over the measurement.
8//
9// The process grew past one module's peak even one at a time because glibc keeps freed memory in per-thread arenas
10// (6 threads: 6.2 GB; MALLOC_ARENA_MAX=1: 2.1 GB, same modules). release_free_memory() hands it back after each
11// large module.
12#pragma once 2#pragma once
13 3
14#include <algorithm> 4#include "../src/large_module_gate.h"
15#include <condition_variable>
16#include <cstdint>
17#include <cstdio>
18#include <mutex>
19#include <string>
20
21#ifdef _WIN32
22#ifndef NOMINMAX
23#define NOMINMAX
24#endif
25#include <windows.h>
26#endif
27#if defined(__GLIBC__)
28#include <malloc.h>
29#endif
30
31namespace leonida {
32
33inline constexpr uint64_t kBytesPerSpirvByte = 512;
34
35inline uint64_t large_module_estimate(uint64_t spirv_bytes) { return spirv_bytes * kBytesPerSpirvByte; }
36
37#if defined(__linux__)
38// The first unsigned number in a file ("max" and unreadable files give no value).
39inline bool read_u64_file(const std::string& path, uint64_t& value) {
40 std::FILE* f = std::fopen(path.c_str(), "r");
41 if (!f) return false;
42 unsigned long long v = 0;
43 const bool ok = std::fscanf(f, "%llu", &v) == 1;
44 std::fclose(f);
45 value = v;
46 return ok;
47}
48
49// The room left under the cgroup v2 memory.max of this process and of every cgroup above it (a container or
50// systemd-run -p MemoryMax=...), or UINT64_MAX when none sets a limit. cgroup_root is a parameter for the tests.
51inline uint64_t cgroup_memory_room(const std::string& self_cgroup_file = "/proc/self/cgroup",
52 const std::string& cgroup_root = "/sys/fs/cgroup") {
53 std::FILE* f = std::fopen(self_cgroup_file.c_str(), "r");
54 if (!f) return UINT64_MAX;
55 char line[4096];
56 std::string rel;
57 while (std::fgets(line, sizeof(line), f)) {
58 std::string l(line);
59 if (l.rfind("0::", 0) == 0) { // the cgroup v2 line
60 rel = l.substr(3);
61 while (!rel.empty() && (rel.back() == '\n' || rel.back() == '\r')) rel.pop_back();
62 break;
63 }
64 }
65 std::fclose(f);
66 uint64_t room = UINT64_MAX;
67 for (std::string dir = rel; !dir.empty();) {
68 // In a cgroup namespace, "/" can be a constrained cgroup mounted as the visible root.
69 const std::string base = dir == "/" ? cgroup_root : cgroup_root + dir;
70 uint64_t max = 0, current = 0;
71 if (read_u64_file(base + "/memory.max", max) && read_u64_file(base + "/memory.current", current))
72 room = std::min(room, max > current ? max - current : 0);
73 const auto slash = dir.find_last_of('/');
74 if (dir == "/" || slash == std::string::npos) break;
75 dir.resize(slash == 0 ? 1 : slash);
76 }
77 return room;
78}
79#endif
80
81// Memory the OS could give this process now, or 0 when it can't tell (then the caller keeps the old exclusive gate).
82inline uint64_t available_memory_bytes() {
83#ifdef _WIN32
84 MEMORYSTATUSEX status{};
85 status.dwLength = sizeof(status);
86 return GlobalMemoryStatusEx(&status) ? uint64_t(status.ullAvailPhys) : 0;
87#elif defined(__linux__)
88 std::FILE* f = std::fopen("/proc/meminfo", "r");
89 if (!f) return 0;
90 char line[256];
91 unsigned long long kb = 0;
92 bool found = false;
93 while (std::fgets(line, sizeof(line), f))
94 if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) { found = true; break; }
95 std::fclose(f);
96 if (!found) return 0;
97 const uint64_t room = cgroup_memory_room();
98 return std::max<uint64_t>(1, std::min(uint64_t(kb) * 1024, room)); // 0 would mean "unknown"
99#else
100 return 0;
101#endif
102}
103
104// Return memory freed by the driver's compiler to the OS (glibc keeps it in the arena of the thread that freed it).
105inline void release_free_memory() {
106#if defined(__GLIBC__)
107 malloc_trim(0);
108#endif
109}
110
111// Lets large modules in while their estimates fit the budget and fewer than max_inflight are in. One always gets in
112// when none is, so a module bigger than the whole budget still compiles (alone among the large ones).
113class LargeModuleGate {
114public:
115 LargeModuleGate(uint64_t budget, unsigned max_inflight)
116 : budget_(budget), max_inflight_(max_inflight ? max_inflight : 1) {}
117
118 bool admits(uint64_t estimate) const {
119 std::lock_guard<std::mutex> g(mu_);
120 return admits_locked(estimate);
121 }
122 void enter(uint64_t estimate) {
123 std::unique_lock<std::mutex> l(mu_);
124 cv_.wait(l, [&] { return admits_locked(estimate); });
125 used_ += estimate;
126 ++inflight_;
127 }
128 void leave(uint64_t estimate) {
129 {
130 std::lock_guard<std::mutex> g(mu_);
131 used_ -= estimate;
132 --inflight_;
133 }
134 cv_.notify_all();
135 }
136 unsigned inflight() const {
137 std::lock_guard<std::mutex> g(mu_);
138 return inflight_;
139 }
140 uint64_t budget() const { return budget_; }
141 unsigned max_inflight() const { return max_inflight_; }
142
143 // Holds a place from construction until destruction (or release()), then hands freed memory back.
144 class Ticket {
145 public:
146 Ticket() = default;
147 Ticket(LargeModuleGate& gate, uint64_t estimate) : gate_(&gate), estimate_(estimate) { gate.enter(estimate); }
148 Ticket(Ticket&& o) noexcept : gate_(o.gate_), estimate_(o.estimate_) { o.gate_ = nullptr; }
149 Ticket& operator=(Ticket&& o) noexcept {
150 if (this != &o) { release(); gate_ = o.gate_; estimate_ = o.estimate_; o.gate_ = nullptr; }
151 return *this;
152 }
153 Ticket(const Ticket&) = delete;
154 Ticket& operator=(const Ticket&) = delete;
155 ~Ticket() { release(); }
156 void release() {
157 if (!gate_) return;
158 gate_->leave(estimate_);
159 gate_ = nullptr;
160 release_free_memory();
161 }
162 private:
163 LargeModuleGate* gate_ = nullptr;
164 uint64_t estimate_ = 0;
165 };
166
167private:
168 bool admits_locked(uint64_t estimate) const {
169 if (inflight_ == 0) return true;
170 return inflight_ < max_inflight_ && used_ + estimate <= budget_;
171 }
172
173 const uint64_t budget_;
174 const unsigned max_inflight_;
175 mutable std::mutex mu_;
176 std::condition_variable cv_;
177 uint64_t used_ = 0;
178 unsigned inflight_ = 0;
179};
180
181} // namespace leonida
diff --git a/runtime/test/replay_pipeline_compiles_test.cpp b/runtime/test/replay_pipeline_compiles_test.cpp
index 45a28f7c2..a8983f7ce 100644
--- a/runtime/test/replay_pipeline_compiles_test.cpp
+++ b/runtime/test/replay_pipeline_compiles_test.cpp
@@ -2,13 +2,16 @@
2// prepared twice, once with every pipeline built where prepare() meets it and once with them left to PipelineCompiles 2// prepared twice, once with every pipeline built where prepare() meets it and once with them left to PipelineCompiles
3// and built on PipelineWorkers. Both have to give the same result, the same pipeline to every draw and dispatch, the same 3// and built on PipelineWorkers. Both have to give the same result, the same pipeline to every draw and dispatch, the same
4// commands dropped, and the same pipelines built, each once. Fixed cases, then random ones. Run a second time with 4// commands dropped, and the same pipelines built, each once. Fixed cases, then random ones. Run a second time with
5// LEONIDA_STRICT_REPLAY=1, where a dispatch without a pipeline fails its list. No GPU: pipelines and resources are fakes. 5// LEONIDA_STRICT_REPLAY=1, where a dispatch without a pipeline fails its list. Also which large pipelines compile at once
6// within a budget (PipelineCompiles::build). No GPU: pipelines and resources are fakes.
7#include "../src/large_module_gate.h"
6#include "../src/pipeline_workers.h" 8#include "../src/pipeline_workers.h"
7#include "../src/vulkan_replay.h" 9#include "../src/vulkan_replay.h"
8 10
9#include <algorithm> 11#include <algorithm>
10#include <atomic> 12#include <atomic>
11#include <chrono> 13#include <chrono>
14#include <condition_variable>
12#include <cstdint> 15#include <cstdint>
13#include <cstdio> 16#include <cstdio>
14#include <functional> 17#include <functional>
@@ -39,9 +42,10 @@ T handle(std::uintptr_t n) {
39constexpr ResourceId color_id = 1, depth_id = 2, arguments_id = 3; 42constexpr ResourceId color_id = 1, depth_id = 2, arguments_id = 3;
40constexpr std::uint64_t bad_va = 0xbad0000; 43constexpr std::uint64_t bad_va = 0xbad0000;
41 44
42// The large pipelines being built now, and how often there were two. 45// The large pipelines being built now, and how often there were two, where they are to compile one after another.
43std::atomic<int> large_now = 0; 46std::atomic<int> large_now = 0;
44std::atomic<int> large_together = 0; 47std::atomic<int> large_together = 0;
48std::atomic<bool> large_one_at_a_time = true;
45 49
46// What a pipeline state owns: its variants, built on demand under its own lock, and what was asked of it. 50// What a pipeline state owns: its variants, built on demand under its own lock, and what was asked of it.
47struct Owner { 51struct Owner {
@@ -60,7 +64,7 @@ struct Owner {
60 if (failed && compute) return VK_NULL_HANDLE; // a refused compute pipeline is not tried again 64 if (failed && compute) return VK_NULL_HANDLE; // a refused compute pipeline is not tried again
61 attempts.push_back(flags); 65 attempts.push_back(flags);
62 if (large) { 66 if (large) {
63 if (++large_now > 1) ++large_together; 67 if (++large_now > 1 && large_one_at_a_time) ++large_together;
64 const auto end = std::chrono::steady_clock::now() + std::chrono::microseconds(20); 68 const auto end = std::chrono::steady_clock::now() + std::chrono::microseconds(20);
65 while (std::chrono::steady_clock::now() < end) std::this_thread::yield(); 69 while (std::chrono::steady_clock::now() < end) std::this_thread::yield();
66 --large_now; 70 --large_now;
@@ -84,6 +88,7 @@ struct PipelineSpec {
84 bool fails = false; 88 bool fails = false;
85 bool with_built = true; 89 bool with_built = true;
86 bool large = false; 90 bool large = false;
91 std::uint64_t estimate = 0;
87 bool skipped = false; // compute: never built, its dispatches are dropped 92 bool skipped = false; // compute: never built, its dispatches are dropped
88 bool bindless = false; // compute: needs a set 0, which these functions cannot bind 93 bool bindless = false; // compute: needs a set 0, which these functions cannot bind
89 bool async = false; // its null handle may be waiting for another worker: never left to PipelineCompiles 94 bool async = false; // its null handle may be waiting for another worker: never left to PipelineCompiles
@@ -114,6 +119,7 @@ struct Registry {
114 ComputePipeline p{}; 119 ComputePipeline p{};
115 p.layout = handle<VkPipelineLayout>(7); 120 p.layout = handle<VkPipelineLayout>(7);
116 p.large = spec.large; 121 p.large = spec.large;
122 p.estimate = spec.estimate;
117 p.async_build = spec.async; 123 p.async_build = spec.async;
118 p.skipped = spec.skipped; 124 p.skipped = spec.skipped;
119 if (spec.bindless) p.bindless_set = handle<VkDescriptorSet>(6); 125 if (spec.bindless) p.bindless_set = handle<VkDescriptorSet>(6);
@@ -138,6 +144,7 @@ struct Registry {
138 } 144 }
139 p.mesh = spec.mesh; 145 p.mesh = spec.mesh;
140 p.large = spec.large; 146 p.large = spec.large;
147 p.estimate = spec.estimate;
141 p.vertex_slots = spec.vertices ? 1 : 0; 148 p.vertex_slots = spec.vertices ? 1 : 0;
142 if (spec.rectangle) p.rectangle_variant_topology = 17; 149 if (spec.rectangle) p.rectangle_variant_topology = 17;
143 p.variant = [&owner](std::uint32_t flags) { return owner.build(flags); }; 150 p.variant = [&owner](std::uint32_t flags) { return owner.build(flags); };
@@ -273,12 +280,12 @@ struct Outcome {
273 std::multiset<std::pair<std::uintptr_t, std::uint32_t>> built; 280 std::multiset<std::pair<std::uintptr_t, std::uint32_t>> built;
274 std::size_t jobs = 0; 281 std::size_t jobs = 0;
275 std::size_t runs = 0; 282 std::size_t runs = 0;
276 std::size_t units = 0; // what run() was given: the large pipelines together are one 283 std::size_t units = 0; // what run() was given: the large pipelines together are one (no budget)
277}; 284};
278 285
279// `workers` null: prepare() builds each pipeline itself, as without workers. 286// `workers` null: prepare() builds each pipeline itself, as without workers.
280Outcome prepare_all(const std::vector<CommandList>& lists, const std::vector<PipelineSpec>& specs, 287Outcome prepare_all(const std::vector<CommandList>& lists, const std::vector<PipelineSpec>& specs,
281 PipelineWorkers* workers) { 288 PipelineWorkers* workers, const std::function<std::uint64_t()>& budget = {}) {
282 Registry registry(specs); 289 Registry registry(specs);
283 ReplayFunctions vk = functions(registry); 290 ReplayFunctions vk = functions(registry);
284 PipelineCompiles compiles; 291 PipelineCompiles compiles;
@@ -294,7 +301,8 @@ Outcome prepare_all(const std::vector<CommandList>& lists, const std::vector<Pip
294 ++out.runs; 301 ++out.runs;
295 out.units = count; 302 out.units = count;
296 workers->run(count, job); 303 workers->run(count, job);
297 }); 304 },
305 budget);
298 if (out.result == ReplayResult::success) 306 if (out.result == ReplayResult::success)
299 for (std::size_t i = 0; i < lists.size(); ++i) { 307 for (std::size_t i = 0; i < lists.size(); ++i) {
300 for (std::size_t c = 0; c < prepared[i].commands.size(); ++c) { 308 for (std::size_t c = 0; c < prepared[i].commands.size(); ++c) {
@@ -312,10 +320,13 @@ Outcome prepare_all(const std::vector<CommandList>& lists, const std::vector<Pip
312} 320}
313 321
314Outcome compare(const std::string& name, const std::vector<PipelineSpec>& specs, 322Outcome compare(const std::string& name, const std::vector<PipelineSpec>& specs,
315 const std::vector<std::vector<CommandSpec>>& commands, PipelineWorkers& workers) { 323 const std::vector<std::vector<CommandSpec>>& commands, PipelineWorkers& workers,
324 const std::function<std::uint64_t()>& budget = {}) {
316 const auto lists = record(commands); 325 const auto lists = record(commands);
317 const Outcome serial = prepare_all(lists, specs, nullptr); 326 const Outcome serial = prepare_all(lists, specs, nullptr);
318 const Outcome together = prepare_all(lists, specs, &workers); 327 large_one_at_a_time = !budget;
328 const Outcome together = prepare_all(lists, specs, &workers, budget);
329 large_one_at_a_time = true;
319 check(serial.result == together.result, name + ": another result"); 330 check(serial.result == together.result, name + ": another result");
320 check(serial.pipelines == together.pipelines, name + ": another pipeline for a draw or dispatch"); 331 check(serial.pipelines == together.pipelines, name + ": another pipeline for a draw or dispatch");
321 if (serial.result == ReplayResult::success) 332 if (serial.result == ReplayResult::success)
@@ -516,6 +527,7 @@ void random_submissions(PipelineWorkers& workers) {
516 s.with_built = chance(90); 527 s.with_built = chance(90);
517 s.async = chance(8); 528 s.async = chance(8);
518 s.large = chance(15); 529 s.large = chance(15);
530 s.estimate = rng() % 12;
519 s.bindless = chance(2); 531 s.bindless = chance(2);
520 s.skipped = s.compute && chance(4); 532 s.skipped = s.compute && chance(4);
521 if (s.skipped) s.fails = s.pending = true; 533 if (s.skipped) s.fails = s.pending = true;
@@ -540,8 +552,12 @@ void random_submissions(PipelineWorkers& workers) {
540 c.mesh = c.pipeline <= specs.size() && specs[c.pipeline - 1].mesh; 552 c.mesh = c.pipeline <= specs.size() && specs[c.pipeline - 1].mesh;
541 list.push_back(c); 553 list.push_back(c);
542 } 554 }
543 succeeded += compare("random submission " + std::to_string(round), specs, commands, workers).result == 555 const std::uint64_t memory = rng() % 24; // 0: no budget
544 ReplayResult::success; 556 const auto budget = [memory] { return memory; };
557 const bool limited = chance(50);
558 succeeded += compare("random submission " + std::to_string(round), specs, commands, workers,
559 limited ? std::function<std::uint64_t()>(budget) : std::function<std::uint64_t()>{})
560 .result == ReplayResult::success;
545 } 561 }
546 check(succeeded > 1000 && succeeded < 2900, "the random submissions both succeed and fail: " + 562 check(succeeded > 1000 && succeeded < 2900, "the random submissions both succeed and fail: " +
547 std::to_string(succeeded)); 563 std::to_string(succeeded));
@@ -582,7 +598,7 @@ void prior_compiles_reuse(PipelineWorkers& workers) {
582 const ReplayResult b1 = build_pipelines( 598 const ReplayResult b1 = build_pipelines(
583 second, std::span(prepared), r1, 599 second, std::span(prepared), r1,
584 [&](std::size_t count, const std::function<void(std::size_t)>& job) { workers.run(count, job); }, 600 [&](std::size_t count, const std::function<void(std::size_t)>& job) { workers.run(count, job); },
585 &first); 601 {}, &first);
586 check(b1 == ReplayResult::success, "prior_compiles_reuse: pass 1 succeeded"); 602 check(b1 == ReplayResult::success, "prior_compiles_reuse: pass 1 succeeded");
587 check(registry.owners[0]->attempts.size() == 1 && registry.owners[1]->attempts.size() == 1, 603 check(registry.owners[0]->attempts.size() == 1 && registry.owners[1]->attempts.size() == 1,
588 "prior_compiles_reuse: pass 1 did not re-invoke build() on prior failure"); 604 "prior_compiles_reuse: pass 1 did not re-invoke build() on prior failure");
@@ -621,6 +637,267 @@ void serial_stops_at_refused_draw() {
621 "serial_stops: did not compile draws past the first refused draw"); 637 "serial_stops: did not compile draws past the first refused draw");
622} 638}
623 639
640// ---- Large pipelines within a budget. ----
641
642// Pipelines that note the order they start in. One with `hold` does not end before `release` is called.
643struct Shop {
644 struct Item {
645 Shop* shop = nullptr;
646 ComputePipeline pipeline{};
647 std::string name;
648 bool hold = false;
649 };
650 std::mutex mutex;
651 std::condition_variable changed;
652 std::vector<std::string> started;
653 std::vector<std::unique_ptr<Item>> items;
654 bool released = false;
655 int large_in = 0, most_large_in = 0;
656 LargeModuleGate* gate = nullptr; // set: a large one takes its place there, as in the layer
657
658 ComputePipeline& add(const std::string& name, std::uint64_t estimate, bool large, bool hold = false) {
659 auto& item = *items.emplace_back(std::make_unique<Item>());
660 item.shop = this;
661 item.name = name;
662 item.hold = hold;
663 item.pipeline.large = large;
664 item.pipeline.estimate = estimate;
665 item.pipeline.build_context = &item;
666 item.pipeline.build = [](void* context) {
667 auto& i = *static_cast<Item*>(context);
668 Shop& shop = *i.shop;
669 LargeModuleGate::Ticket place;
670 if (shop.gate && i.pipeline.large) place = LargeModuleGate::Ticket(*shop.gate, i.pipeline.estimate);
671 std::unique_lock lock(shop.mutex);
672 shop.started.push_back(i.name);
673 if (i.pipeline.large) shop.most_large_in = std::max(shop.most_large_in, ++shop.large_in);
674 shop.changed.notify_all();
675 if (i.hold) shop.changed.wait_for(lock, std::chrono::seconds(10), [&] { return shop.released; });
676 if (i.pipeline.large) --shop.large_in;
677 return handle<VkPipeline>(std::uintptr_t(&i) | 1);
678 };
679 return item.pipeline;
680 }
681 void fill(PipelineCompiles& compiles) {
682 for (auto& item : items) compiles.add(item->pipeline, PipelineCompiles::User::dispatch);
683 }
684 // Whether `count` have started, within 10 s.
685 bool wait_started(std::size_t count) {
686 std::unique_lock lock(mutex);
687 return changed.wait_for(lock, std::chrono::seconds(10), [&] { return started.size() >= count; });
688 }
689 void release() {
690 std::lock_guard lock(mutex);
691 released = true;
692 changed.notify_all();
693 }
694};
695
696// On `threads` threads, which take the jobs in order.
697void on_threads(unsigned threads, std::size_t count, const std::function<void(std::size_t)>& job) {
698 std::atomic<std::size_t> next = 0;
699 std::vector<std::thread> workers;
700 for (unsigned t = 0; t < threads; ++t)
701 workers.emplace_back([&] {
702 for (std::size_t i; (i = next++) < count;) job(i);
703 });
704 for (auto& w : workers) w.join();
705}
706
707using Names = std::vector<std::string>;
708
709// The order and the jobs of the run, on one thread: the largest first, then the others, and the budget read once.
710void budget_order() {
711 struct Case {
712 std::vector<std::uint64_t> large;
713 std::uint64_t budget;
714 std::size_t lanes;
715 Names order; // of the large ones
716 };
717 for (const Case& c : {Case{{5, 2, 3, 2, 1}, 5, 3, {"5", "3", "2", "2", "1"}},
718 Case{{5, 2, 3, 2, 1}, 4, 2, {"5", "3", "2", "2", "1"}},
719 Case{{5, 2, 3, 2, 1}, 0, 1, {"5", "2", "3", "2", "1"}}, // no budget: in the order they came
720 Case{{5, 2, 3, 2, 1}, 100, 5, {"5", "3", "2", "2", "1"}},
721 Case{{9}, 5, 1, {"9"}}, // more than the budget: one, alone
722 Case{{9, 9}, 5, 1, {"9", "9"}},
723 Case{{9, 1}, 5, 1, {"9", "1"}},
724 Case{{4, 4}, 8, 2, {"4", "4"}}}) {
725 Shop shop;
726 for (const auto size : c.large) shop.add(std::to_string(size), size, true);
727 for (int i = 0; i < 3; ++i) shop.add("s" + std::to_string(i), 0, false);
728 PipelineCompiles compiles;
729 shop.fill(compiles);
730 std::size_t units = 0;
731 unsigned reads = 0;
732 compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) {
733 units = count;
734 for (std::size_t i = 0; i < count; ++i) job(i);
735 }, [&] { ++reads; return c.budget; });
736 Names want = c.order;
737 for (int i = 0; i < 3; ++i) want.push_back("s" + std::to_string(i));
738 const std::string name = "budget " + std::to_string(c.budget) + " of " + std::to_string(c.large.size());
739 check(shop.started == want, name + ": another order");
740 check(units == c.lanes + 3, name + ": " + std::to_string(units) + " jobs, not " + std::to_string(c.lanes + 3));
741 check(reads == 1, name + ": the budget read " + std::to_string(reads) + " times");
742 for (std::size_t i = 0; i < shop.items.size(); ++i)
743 check(compiles.built(PipelineCompiles::Ticket(i + 1)) != VK_NULL_HANDLE, name + ": not built");
744 }
745 // Without a large pipeline the budget is not read, and the jobs are the pipelines.
746 Shop shop;
747 for (int i = 0; i < 3; ++i) shop.add("s" + std::to_string(i), 0, false);
748 PipelineCompiles compiles;
749 shop.fill(compiles);
750 std::size_t units = 0;
751 unsigned reads = 0;
752 compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) {
753 units = count;
754 for (std::size_t i = 0; i < count; ++i) job(i);
755 }, [&] { ++reads; return 100u; });
756 check(units == 3 && reads == 0, "the budget read for pipelines that are not large");
757}
758
759// A large one that does not fit beside the one in is not waited for while others are left: they come first.
760void budget_others_first() {
761 Shop shop;
762 shop.add("8", 8, true, true);
763 shop.add("4a", 4, true);
764 shop.add("4b", 4, true);
765 for (int i = 0; i < 3; ++i) shop.add("s" + std::to_string(i), 0, false);
766 PipelineCompiles compiles;
767 shop.fill(compiles);
768 std::thread building([&] {
769 compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) {
770 check(count == 2 + 3, "two lanes: the two of 4 fit 8 together");
771 on_threads(2, count, job);
772 }, [] { return 8; });
773 });
774 const bool all = shop.wait_started(6); // "8" is held: the other lane does the rest
775 Names seen;
776 {
777 std::lock_guard lock(shop.mutex);
778 seen = shop.started;
779 }
780 shop.release();
781 building.join();
782 check(all && seen.size() == 6 && seen[0] == "8", "the large one first");
783 check(all && std::set<std::string>(seen.begin() + 1, seen.begin() + 4) == std::set<std::string>{"s0", "s1", "s2"},
784 "the others before the large ones that do not fit");
785 check(all && seen[4] == "4a" && seen[5] == "4b", "then the next large ones");
786}
787
788// Those that fit together start together, before the others.
789void budget_fits_together() {
790 Shop shop;
791 shop.add("3", 3, true, true);
792 shop.add("5", 5, true, true);
793 for (int i = 0; i < 2; ++i) shop.add("s" + std::to_string(i), 0, false);
794 PipelineCompiles compiles;
795 shop.fill(compiles);
796 std::thread building([&] {
797 compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) { on_threads(2, count, job); },
798 [] { return 8; });
799 });
800 const bool both = shop.wait_started(2);
801 Names seen;
802 {
803 std::lock_guard lock(shop.mutex);
804 seen = shop.started;
805 }
806 shop.release();
807 building.join();
808 check(both && std::set<std::string>(seen.begin(), seen.begin() + 2) == std::set<std::string>{"3", "5"},
809 "two that fit the budget are in together");
810 check(shop.most_large_in == 2, "two that fit the budget at once");
811}
812
813// The room that a large one leaves is the next large one's, before the others.
814void budget_room_is_given_back() {
815 Shop shop;
816 shop.add("5", 5, true, true);
817 for (const char* name : {"3a", "3b", "3c"}) shop.add(name, 3, true);
818 for (int i = 0; i < 3; ++i) shop.add("s" + std::to_string(i), 0, false);
819 PipelineCompiles compiles;
820 shop.fill(compiles);
821 std::thread building([&] {
822 compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) {
823 check(count == 2 + 3, "two lanes: two of 3 fit 8, three do not");
824 on_threads(2, count, job);
825 }, [] { return 8; });
826 });
827 const bool all = shop.wait_started(7); // "5" is held: the other lane has room for one of 3 at a time
828 Names seen;
829 {
830 std::lock_guard lock(shop.mutex);
831 seen = shop.started;
832 }
833 shop.release();
834 building.join();
835 check(all && Names(seen.begin(), seen.begin() + 4) == Names{"5", "3a", "3b", "3c"},
836 "a large one does not leave its room");
837}
838
839// Graphics and compute pipelines share the budget: what each is expected to take counts alike.
840void budget_graphics_and_compute() {
841 Shop shop;
842 shop.add("3", 3, true);
843 shop.add("4", 4, true);
844 GraphicsPipeline graphics{};
845 graphics.large = true;
846 graphics.estimate = 5;
847 graphics.variant = [&](std::uint32_t) {
848 std::lock_guard lock(shop.mutex);
849 shop.started.push_back("5");
850 return handle<VkPipeline>(5);
851 };
852 PipelineCompiles compiles;
853 shop.fill(compiles);
854 compiles.add(graphics, 0);
855 std::size_t units = 0;
856 compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) {
857 units = count;
858 for (std::size_t i = 0; i < count; ++i) job(i);
859 }, [] { return 8; });
860 check(shop.started == Names{"5", "4", "3"}, "the largest first, graphics or compute");
861 check(units == 2, "3 and 4 fit 8, and 5 does not beside them");
862}
863
864// The lanes are no more than could be in: a thread is not kept waiting for room there is none of.
865void budget_lanes_are_bounded() {
866 Shop shop;
867 for (int i = 0; i < 3; ++i) shop.add("5" + std::to_string(i), 5, true);
868 for (int i = 0; i < 6; ++i) shop.add("s" + std::to_string(i), 0, false);
869 PipelineCompiles compiles;
870 shop.fill(compiles);
871 compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) {
872 check(count == 2 + 6, "10 bytes hold two of 5");
873 on_threads(4, count, job);
874 }, [] { return 10; });
875 check(shop.started.size() == 9 && shop.most_large_in <= 2, "no more than two large ones at once");
876}
877
878// Every one of them is built once, with the gate of the runtime holding what does not fit, whatever sizes and budget.
879void budget_random(PipelineWorkers& workers) {
880 std::mt19937 rng(20251127);
881 for (int round = 0; round < 300; ++round) {
882 Shop shop;
883 const std::uint64_t budget = rng() % 20;
884 LargeModuleGate gate([budget] { return budget; });
885 shop.gate = &gate;
886 const unsigned large = rng() % 10, others = rng() % 10;
887 for (unsigned i = 0; i < large; ++i) shop.add("l" + std::to_string(i), rng() % 12, true);
888 for (unsigned i = 0; i < others; ++i) shop.add("s" + std::to_string(i), 0, false);
889 PipelineCompiles compiles;
890 shop.fill(compiles);
891 compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) { workers.run(count, job); },
892 [budget] { return budget; });
893 Names names = shop.started;
894 std::sort(names.begin(), names.end());
895 check(std::adjacent_find(names.begin(), names.end()) == names.end() && names.size() == large + others,
896 "random budget " + std::to_string(round) + ": a pipeline built twice or not at all");
897 check(gate.inflight() == 0, "random budget " + std::to_string(round) + ": a place not given back");
898 }
899}
900
624} // namespace 901} // namespace
625 902
626int main() { 903int main() {
@@ -631,8 +908,15 @@ int main() {
631 reused_lists(workers); 908 reused_lists(workers);
632 prior_compiles_reuse(workers); 909 prior_compiles_reuse(workers);
633 random_submissions(workers); 910 random_submissions(workers);
911 budget_random(workers);
634 } 912 }
635 serial_stops_at_refused_draw(); 913 serial_stops_at_refused_draw();
914 budget_order();
915 budget_others_first();
916 budget_fits_together();
917 budget_room_is_given_back();
918 budget_graphics_and_compute();
919 budget_lanes_are_bounded();
636 check(large_together == 0, "two large pipelines were built at once"); 920 check(large_together == 0, "two large pipelines were built at once");
637 if (failures) return 1; 921 if (failures) return 1;
638 std::printf("replay_pipeline_compiles_test: passed\n"); 922 std::printf("replay_pipeline_compiles_test: passed\n");