From 4aa21d1a83f4a7954ca79111fffb0d4aba674bf2 Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:42:21 +0100 Subject: [PATCH 1/3] runtime: large compiles wait for memory in arrival order, demand before speculative (RT-BIG-COMPUTE-BUDGET) LargeModuleGate moves to runtime/src (a forwarding header keeps vk_pipeline_check and its test as they are) and gets a second constructor, whose budget is read whenever a place is given or returned. Its modules get in in the order they came, a speculative one only while no demand waits and within a quarter of the budget. large_compile_budget_bytes() is three quarters of the smaller of the free RAM and the room under the commit limit. CPU test: the bound, one always, order, priority, every wake-up, the budget of the moment and the setting. --- docs/pipeline_check.md | 2 +- runtime/CMakeLists.txt | 6 + runtime/src/large_module_gate.h | 275 ++++++++++++++++ runtime/test/big_compile_gate_test.cpp | 426 +++++++++++++++++++++++++ runtime/test/large_module_gate.h | 181 +---------- 5 files changed, 710 insertions(+), 180 deletions(-) create mode 100644 runtime/src/large_module_gate.h create mode 100644 runtime/test/big_compile_gate_test.cpp diff --git a/docs/pipeline_check.md b/docs/pipeline_check.md index d5d76cb931..47e3a409c5 100644 --- a/docs/pipeline_check.md +++ b/docs/pipeline_check.md @@ -256,7 +256,7 @@ acceptance only. A SPIR-V module larger than 4 MiB is "large". [#884](https://github.com/ItsNotRexed/Leonida/issues/884) showed why that matters: several compiles that each needed gigabytes of host RAM ran at the same time. Large -modules now share a memory budget (`runtime/test/large_module_gate.h`): each one reserves 512 bytes of RAM per +modules now share a memory budget (`runtime/src/large_module_gate.h`): each one reserves 512 bytes of RAM per SPIR-V byte, and they enter the driver while their reservations fit three quarters of the memory available when the run starts, up to `--jobs` of them. One large module always gets in when none is compiling, so a module bigger than the whole budget still compiles, alone among the large ones. Small modules are never held back. On diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 86378dfc86..3a95295f3c 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -783,6 +783,12 @@ if(BUILD_TESTING) add_executable(xdxr_build_output_test test/xdxr_build_output_test.cpp) add_test(NAME xdxr_build_output COMMAND xdxr_build_output_test) + # The gate of large_module_gate.h as the runtime uses it for large pipelines (LEONIDA_BIG_COMPILE_BUDGET_MB): pure + # stdlib. + add_executable(big_compile_gate_test test/big_compile_gate_test.cpp) + target_link_libraries(big_compile_gate_test PRIVATE Threads::Threads) + add_test(NAME big_compile_gate COMMAND big_compile_gate_test) + set_tests_properties(big_compile_gate PROPERTIES TIMEOUT 120) # vk_pipeline_check's memory budget for large modules: pure stdlib, no Vulkan device. add_executable(large_module_gate_test test/large_module_gate_test.cpp) find_package(Threads REQUIRED) diff --git a/runtime/src/large_module_gate.h b/runtime/src/large_module_gate.h new file mode 100644 index 0000000000..2185f20cf0 --- /dev/null +++ b/runtime/src/large_module_gate.h @@ -0,0 +1,275 @@ +// How many large SPIR-V modules vk_pipeline_check and the runtime let into the driver at once, by a memory budget. +// +// Measured on RADV GFX1201 (Mesa 25.3.6) with the Mesa shader cache off: a 5.7 MB translated ray-tracing compute +// module peaks at 1.96 GB of process memory compiling alone (~330 bytes per SPIR-V byte), a 0.36 MB one at 94 MB. +// Compiling the large ones strictly one at a time left the other threads idle: 40 modules (27 over 4 MiB) on 6 +// threads took 308 s exclusively and 75 s in parallel, 7.0 GB and 8.7 GB peak. kBytesPerSpirvByte keeps a margin +// over the measurement. The NVIDIA 621.24 driver (RTX 3080) took 85 to 131 bytes per SPIR-V byte for synthetic compute +// modules of 128 KiB to 4 MiB (docs/d3d12_vulkan.md, "Large pipelines"). +// +// The process grew past one module's peak even one at a time because glibc keeps freed memory in per-thread arenas +// (6 threads: 6.2 GB; MALLOC_ARENA_MAX=1: 2.1 GB, same modules). release_free_memory() hands it back after each +// large module. +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#endif +#if defined(__GLIBC__) +#include +#endif + +namespace leonida { + +inline constexpr uint64_t kBytesPerSpirvByte = 512; + +inline uint64_t large_module_estimate(uint64_t spirv_bytes) { return spirv_bytes * kBytesPerSpirvByte; } + +#if defined(__linux__) +// The first unsigned number in a file ("max" and unreadable files give no value). +inline bool read_u64_file(const std::string& path, uint64_t& value) { + std::FILE* f = std::fopen(path.c_str(), "r"); + if (!f) return false; + unsigned long long v = 0; + const bool ok = std::fscanf(f, "%llu", &v) == 1; + std::fclose(f); + value = v; + return ok; +} + +// The room left under the cgroup v2 memory.max of this process and of every cgroup above it (a container or +// systemd-run -p MemoryMax=...), or UINT64_MAX when none sets a limit. cgroup_root is a parameter for the tests. +inline uint64_t cgroup_memory_room(const std::string& self_cgroup_file = "/proc/self/cgroup", + const std::string& cgroup_root = "/sys/fs/cgroup") { + std::FILE* f = std::fopen(self_cgroup_file.c_str(), "r"); + if (!f) return UINT64_MAX; + char line[4096]; + std::string rel; + while (std::fgets(line, sizeof(line), f)) { + std::string l(line); + if (l.rfind("0::", 0) == 0) { // the cgroup v2 line + rel = l.substr(3); + while (!rel.empty() && (rel.back() == '\n' || rel.back() == '\r')) rel.pop_back(); + break; + } + } + std::fclose(f); + uint64_t room = UINT64_MAX; + for (std::string dir = rel; !dir.empty();) { + // In a cgroup namespace, "/" can be a constrained cgroup mounted as the visible root. + const std::string base = dir == "/" ? cgroup_root : cgroup_root + dir; + uint64_t max = 0, current = 0; + if (read_u64_file(base + "/memory.max", max) && read_u64_file(base + "/memory.current", current)) + room = std::min(room, max > current ? max - current : 0); + const auto slash = dir.find_last_of('/'); + if (dir == "/" || slash == std::string::npos) break; + dir.resize(slash == 0 ? 1 : slash); + } + return room; +} +#endif + +// Memory the OS could give this process now, or 0 when it can't tell (then the caller keeps the old exclusive gate). +inline uint64_t available_memory_bytes() { +#ifdef _WIN32 + MEMORYSTATUSEX status{}; + status.dwLength = sizeof(status); + return GlobalMemoryStatusEx(&status) ? uint64_t(status.ullAvailPhys) : 0; +#elif defined(__linux__) + std::FILE* f = std::fopen("/proc/meminfo", "r"); + if (!f) return 0; + char line[256]; + unsigned long long kb = 0; + bool found = false; + while (std::fgets(line, sizeof(line), f)) + if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) { found = true; break; } + std::fclose(f); + if (!found) return 0; + const uint64_t room = cgroup_memory_room(); + return std::max(1, std::min(uint64_t(kb) * 1024, room)); // 0 would mean "unknown" +#else + return 0; +#endif +} + +// What large compiles may use of the free RAM and of the room under the commit limit: three quarters of the smaller. (On +// Windows an allocation that the limit has no room for fails, whatever RAM is free.) +inline uint64_t large_compile_share(uint64_t free_ram, uint64_t commit_room) { + return std::min(free_ram, commit_room) / 4 * 3; +} + +// The same of the memory that is free at this moment. 0 when it is unknown: then they compile one at a time. +inline uint64_t large_compile_budget_bytes() { +#ifdef _WIN32 + MEMORYSTATUSEX status{}; + status.dwLength = sizeof(status); + if (!GlobalMemoryStatusEx(&status)) return 0; + return large_compile_share(status.ullAvailPhys, status.ullAvailPageFile); +#else + return large_compile_share(available_memory_bytes(), UINT64_MAX); +#endif +} + +// LEONIDA_BIG_COMPILE_BUDGET_MB: a fixed budget in MiB instead of the share of the free memory (0: one at a time). Unset +// or empty, and text that is not a number: none. `valid` is false for the latter. +struct LargeCompileBudget { + std::optional fixed{}; + bool valid = true; +}; + +inline LargeCompileBudget large_compile_budget(const char* text) { + if (!text || !*text) return {}; + uint64_t mib = 0; + for (const char* c = text; *c; ++c) { + if (*c < '0' || *c > '9') return {std::nullopt, false}; + mib = std::min(mib * 10 + uint64_t(*c - '0'), UINT64_MAX >> 20); + } + return {mib << 20, true}; +} + +// Return memory freed by the driver's compiler to the OS (glibc keeps it in the arena of the thread that freed it). +inline void release_free_memory() { +#if defined(__GLIBC__) + malloc_trim(0); +#endif +} + +// Lets large modules in while their estimates fit the budget and fewer than max_inflight are in. One always gets in +// when none is, so a module bigger than the whole budget still compiles (alone among the large ones). +// +// The second constructor is the runtime's: the budget is read again whenever a place is given or returned, and the +// modules get in in the order they came, those a submission waits for (demand) before the others (speculative). A +// speculative one gets in only while no demand waits and no submission has a Demand, and only within a quarter of the +// budget, so that a demand finds the rest free. An estimate counts in full until its module leaves, although the driver +// has allocated part of it by then and the budget is that much smaller: what is in has not taken all it is going to. +class LargeModuleGate { +public: + enum class Work { demand, speculative }; + + LargeModuleGate(uint64_t budget, unsigned max_inflight) + : budget_(budget), max_inflight_(max_inflight ? max_inflight : 1) {} + explicit LargeModuleGate(std::function budget) + : budget_(0), max_inflight_(UINT32_MAX), read_budget_(std::move(budget)) {} + + bool admits(uint64_t estimate) const { + std::lock_guard g(mu_); + return admits_locked(estimate, Work::demand); + } + void enter(uint64_t estimate, Work work = Work::demand) { + std::unique_lock l(mu_); + if (!read_budget_) { + cv_.wait(l, [&] { return admits_locked(estimate, work); }); + } else { + auto& queue = waiting_[work == Work::demand ? 0 : 1]; + const auto me = queue.insert(queue.end(), 0); + cv_.wait(l, [&] { + return queue.begin() == me && (work == Work::demand || (waiting_[0].empty() && !demanded_)) && + admits_locked(estimate, work); + }); + queue.erase(me); + } + used_ += estimate; + ++inflight_; + if (!waiting_[0].empty() || !waiting_[1].empty()) cv_.notify_all(); // the next in the queue may fit as well + } + void leave(uint64_t estimate) { + { + std::lock_guard g(mu_); + used_ -= estimate; + --inflight_; + } + cv_.notify_all(); + } + unsigned inflight() const { + std::lock_guard g(mu_); + return inflight_; + } + size_t waiting(Work work) const { // in order: the threads in enter(), with a budget that is read + std::lock_guard g(mu_); + return waiting_[work == Work::demand ? 0 : 1].size(); + } + uint64_t budget() const { return read_budget_ ? read_budget_() : budget_; } + unsigned max_inflight() const { return max_inflight_; } + + // A submission that has large modules to build: until it ends, the places that its modules leave between one and the + // next are not taken by speculative ones. + class Demand { + public: + explicit Demand(LargeModuleGate& gate) : gate_(gate) { + std::lock_guard g(gate_.mu_); + ++gate_.demanded_; + } + ~Demand() { + { + std::lock_guard g(gate_.mu_); + --gate_.demanded_; + } + gate_.cv_.notify_all(); + } + Demand(const Demand&) = delete; + Demand& operator=(const Demand&) = delete; + + private: + LargeModuleGate& gate_; + }; + + // Holds a place from construction until destruction (or release()), then hands freed memory back. + class Ticket { + public: + Ticket() = default; + Ticket(LargeModuleGate& gate, uint64_t estimate, Work work = Work::demand) : gate_(&gate), estimate_(estimate) { + gate.enter(estimate, work); + } + Ticket(Ticket&& o) noexcept : gate_(o.gate_), estimate_(o.estimate_) { o.gate_ = nullptr; } + Ticket& operator=(Ticket&& o) noexcept { + if (this != &o) { release(); gate_ = o.gate_; estimate_ = o.estimate_; o.gate_ = nullptr; } + return *this; + } + Ticket(const Ticket&) = delete; + Ticket& operator=(const Ticket&) = delete; + ~Ticket() { release(); } + void release() { + if (!gate_) return; + gate_->leave(estimate_); + gate_ = nullptr; + release_free_memory(); + } + private: + LargeModuleGate* gate_ = nullptr; + uint64_t estimate_ = 0; + }; + +private: + bool admits_locked(uint64_t estimate, Work work) const { + if (inflight_ == 0) return true; + const uint64_t limit = work == Work::demand ? budget() : budget() / 4; + return inflight_ < max_inflight_ && used_ + estimate <= limit; + } + + const uint64_t budget_; + const unsigned max_inflight_; + const std::function read_budget_; + mutable std::mutex mu_; + std::condition_variable cv_; + std::list waiting_[2]; // demand, speculative: one entry for each thread in enter(), in the order they came + uint64_t used_ = 0; + unsigned inflight_ = 0; + unsigned demanded_ = 0; // the Demands +}; + +} // namespace leonida diff --git a/runtime/test/big_compile_gate_test.cpp b/runtime/test/big_compile_gate_test.cpp new file mode 100644 index 0000000000..5756f99abd --- /dev/null +++ b/runtime/test/big_compile_gate_test.cpp @@ -0,0 +1,426 @@ +// LargeModuleGate with a budget that is read (runtime/src/large_module_gate.h): who gets in, in which order and when, and +// the settings. The threads that wait for a place are real; every check that waits for one gives up after 10 s, so a +// missing wake-up fails the test and does not hang it. Fixed budgets (vk_pipeline_check's) are large_module_gate_test.cpp's. +// No Vulkan. +#include "../src/large_module_gate.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace std::chrono_literals; +using leonida::LargeModuleGate; +using Work = LargeModuleGate::Work; + +// Ends the process: the threads that the failed check left waiting would keep the rest from ending. +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); \ + std::fflush(stderr); \ + std::_Exit(1); \ + } \ +} while (0) + +bool eventually(const std::function& what) { + const auto end = std::chrono::steady_clock::now() + 10s; + while (!what()) { + if (std::chrono::steady_clock::now() > end) return false; + std::this_thread::sleep_for(1ms); + } + return true; +} + +// A thread in enter() for one estimate, which keeps its place until leave() is called. +class Entrant { +public: + Entrant(LargeModuleGate& gate, std::uint64_t estimate, Work work = Work::demand) { + thread_ = std::thread([&gate, estimate, work, this] { + LargeModuleGate::Ticket place(gate, estimate, work); + in_ = true; + std::unique_lock lock(mutex_); + go_.wait(lock, [this] { return leave_; }); + lock.unlock(); + }); + } + ~Entrant() { + if (thread_.joinable()) { + leave(); + join(); + } + } + Entrant(const Entrant&) = delete; + Entrant& operator=(const Entrant&) = delete; + bool in() const { return in_; } + void leave() { + std::lock_guard lock(mutex_); + leave_ = true; + go_.notify_all(); + } + void join() { thread_.join(); } + +private: + std::atomic in_{false}; + std::mutex mutex_; + std::condition_variable go_; + bool leave_ = false; + std::thread thread_; +}; + +bool waiting(LargeModuleGate& gate, Work work, std::size_t count) { + return eventually([&] { return gate.waiting(work) == count; }); +} +bool in(const Entrant& e) { return eventually([&] { return e.in(); }); } +// The time a wrong admission would need to happen. +bool stays_out(const Entrant& e) { + std::this_thread::sleep_for(50ms); + return !e.in(); +} + +LargeModuleGate fixed(std::uint64_t budget) { + return LargeModuleGate([budget] { return budget; }); +} + +void bound_and_one_always() { + auto gate = fixed(10); + Entrant big(gate, 25); // more than the whole budget: it compiles alone + CHECK(in(big)); + Entrant first(gate, 6), second(gate, 4); + CHECK(stays_out(first) && stays_out(second)); + big.leave(); + big.join(); + CHECK(in(first) && in(second)); // 10 fits exactly + Entrant third(gate, 1); + CHECK(waiting(gate, Work::demand, 1) && stays_out(third)); + first.leave(); + CHECK(in(third)); + CHECK(gate.inflight() == 2); + second.leave(); + third.leave(); + second.join(); + third.join(); + first.join(); + CHECK(eventually([&] { return gate.inflight() == 0; })); +} + +// Whatever the sizes, what is in fits, or is one alone; everything gets in, once. +void many_threads() { + for (const std::uint64_t budget : {0u, 1u, 10u, 40u}) { + auto gate = fixed(budget); + std::atomic used{0}; + std::atomic inside{0}, most{0}; + std::atomic over{0}, done{0}; + std::vector threads; + for (unsigned t = 0; t < 8; ++t) + threads.emplace_back([&, t] { + for (unsigned i = 0; i < 150; ++i) { + const std::uint64_t estimate = 1 + (t * 7 + i) % 13; + const LargeModuleGate::Ticket place(gate, estimate, + (t + i) % 3 ? Work::demand : Work::speculative); + const std::uint64_t sum = used += estimate; + const unsigned n = ++inside; + if (sum > budget && n > 1) ++over; + unsigned m = most; + while (n > m && !most.compare_exchange_weak(m, n)) {} + for (int spin = 0; spin < 20; ++spin) std::this_thread::yield(); + --inside; + used -= estimate; + ++done; + } + }); + for (auto& t : threads) t.join(); + CHECK(over == 0); + CHECK(done == 8 * 150); + CHECK(gate.inflight() == 0); + CHECK(budget < 40 || most > 1); // and where there is room, several are in + } +} + +// Those that wait get in in the order they came: what came later and is small does not overtake the big one before it. +void order() { + auto gate = fixed(10); + Entrant first(gate, 8); + CHECK(in(first)); + Entrant big(gate, 9); + CHECK(waiting(gate, Work::demand, 1)); + Entrant little(gate, 1); + CHECK(waiting(gate, Work::demand, 2)); + CHECK(stays_out(big)); + CHECK(stays_out(little)); // it would fit beside the first + first.leave(); + CHECK(in(big)); + CHECK(in(little)); // the place that the big one leaves free is the next one's + big.leave(); + little.leave(); +} + +// The first in the queue leaves it, and the next one, which fits as well, gets in at once and not when something leaves. +void one_admission_wakes_the_next() { + auto gate = fixed(10); + Entrant first(gate, 10); + CHECK(in(first)); + Entrant a(gate, 4), b(gate, 4), c(gate, 2); + CHECK(waiting(gate, Work::demand, 3)); + first.leave(); + CHECK(in(a) && in(b) && in(c)); + CHECK(gate.inflight() == 3); + a.leave(); + b.leave(); + c.leave(); +} + +void leaving_wakes_all_that_fit() { + auto gate = fixed(10); + Entrant a(gate, 5), b(gate, 5); + CHECK(in(a) && in(b)); + Entrant c(gate, 3), d(gate, 2); + CHECK(waiting(gate, Work::demand, 2) && stays_out(c)); + a.leave(); + CHECK(in(c) && in(d)); + b.leave(); + c.leave(); + d.leave(); +} + +// What a submission waits for goes first, whenever it came. +void demand_before_speculative() { + auto gate = fixed(10); + Entrant first(gate, 10); + CHECK(in(first)); + Entrant speculative(gate, 1, Work::speculative); + CHECK(waiting(gate, Work::speculative, 1)); + Entrant demand(gate, 9); + CHECK(waiting(gate, Work::demand, 1)); + first.leave(); + CHECK(in(demand)); // the speculative one came first and would have fitted + CHECK(stays_out(speculative)); + demand.leave(); + CHECK(in(speculative)); + speculative.leave(); +} + +// Waiting demand keeps out speculative work that fits, also the one that is first in line. +void waiting_demand_keeps_speculative_out() { + auto gate = fixed(100); + Entrant first(gate, 40, Work::demand); + CHECK(in(first)); + Entrant blocked(gate, 100); // waits for the first + CHECK(waiting(gate, Work::demand, 1)); + Entrant speculative(gate, 5, Work::speculative); // a quarter holds it + CHECK(waiting(gate, Work::speculative, 1)); + CHECK(stays_out(speculative)); + first.leave(); + CHECK(in(blocked)); + CHECK(stays_out(speculative)); + blocked.leave(); + CHECK(in(speculative)); + speculative.leave(); +} + +// While a submission has more to build, the room between two of its modules is not a speculative one's. +void a_demand_keeps_speculative_out() { + auto gate = fixed(100); + auto one = std::make_unique(gate), other = std::make_unique(gate); + Entrant speculative(gate, 10, Work::speculative); + CHECK(waiting(gate, Work::speculative, 1)); + CHECK(stays_out(speculative)); // it fits, and nothing is in + for (int i = 0; i < 2; ++i) { + Entrant built(gate, 10); + CHECK(in(built)); + built.leave(); + built.join(); + CHECK(stays_out(speculative)); // between two of the submission's modules + } + one.reset(); + CHECK(stays_out(speculative)); // another submission has some + other.reset(); + CHECK(in(speculative)); // the end of the last one wakes it + speculative.leave(); +} + +// A speculative one gets in within a quarter of the budget, and what is free of it is there for a demand. +void speculative_share() { + auto gate = fixed(100); + Entrant demand(gate, 30); + CHECK(in(demand)); + Entrant over(gate, 26, Work::speculative); // 56 of 100, but more than 25 with the rest + CHECK(waiting(gate, Work::speculative, 1)); + CHECK(stays_out(over)); + demand.leave(); + CHECK(in(over)); // alone, whatever its size + Entrant quick(gate, 70); + CHECK(in(quick)); // 96 of 100: the speculative one does not count against it + quick.leave(); + over.leave(); + quick.join(); + over.join(); + CHECK(eventually([&] { return gate.inflight() == 0; })); + Entrant share(gate, 25, Work::speculative); + CHECK(in(share)); + Entrant second(gate, 1, Work::speculative); + CHECK(waiting(gate, Work::speculative, 1)); // one more byte is past the quarter + CHECK(stays_out(second)); + Entrant next(gate, 75); + CHECK(in(next)); // the whole rest + CHECK(stays_out(second)); + next.leave(); + share.leave(); + CHECK(in(second)); + second.leave(); +} + +// Speculative ones get in in the order they came, and alone when nothing is in. +void speculative_order_and_alone() { + auto gate = fixed(0); // unknown memory: one at a time + Entrant a(gate, 5, Work::speculative); + CHECK(in(a)); + Entrant b(gate, 5, Work::speculative); + CHECK(waiting(gate, Work::speculative, 1)); + Entrant c(gate, 5, Work::demand); + CHECK(waiting(gate, Work::demand, 1)); + CHECK(stays_out(b) && stays_out(c)); + a.leave(); + CHECK(in(c)); + CHECK(stays_out(b)); + c.leave(); + CHECK(in(b)); + b.leave(); +} + +// The budget is read when a place is asked for and when one is given back, not once. +void budget_follows_the_moment() { + std::atomic free{100}; + LargeModuleGate gate([&] { return free.load(); }); + CHECK(gate.budget() == 100); + Entrant a(gate, 30), b(gate, 10); + CHECK(in(a) && in(b)); + free = 35; + Entrant c(gate, 20); // 60 of 100 a moment ago + CHECK(waiting(gate, Work::demand, 1)); + CHECK(stays_out(c)); + free = 100; + b.leave(); + CHECK(in(c)); // 50 of 100 now; it would not be within 35 + CHECK(gate.inflight() == 2); + a.leave(); + c.leave(); + a.join(); + c.join(); + // A budget that shrinks while a module is in does not throw it out, and holds the next. + Entrant d(gate, 100); + CHECK(in(d)); + free = 1; + Entrant e(gate, 1); + CHECK(waiting(gate, Work::demand, 1)); + CHECK(stays_out(e)); + CHECK(gate.inflight() == 1); + d.leave(); + CHECK(in(e)); +} + +// An estimate counts for as long as its module is in, whatever the driver has taken of it already. +void estimates_stay_reserved() { + auto gate = fixed(100); // the driver has taken nothing yet: the memory is all there + Entrant a(gate, 60); + CHECK(in(a)); + Entrant b(gate, 60); + CHECK(waiting(gate, Work::demand, 1)); + CHECK(stays_out(b)); + a.leave(); + CHECK(in(b)); + b.leave(); +} + +// A ticket gives its place back once, however it ends. +void tickets() { + auto gate = fixed(10); + { + LargeModuleGate::Ticket a(gate, 6, Work::speculative); + LargeModuleGate::Ticket moved = std::move(a); + CHECK(gate.inflight() == 1); + LargeModuleGate::Ticket b; + b = LargeModuleGate::Ticket(gate, 3); + CHECK(gate.inflight() == 2); + b.release(); + b.release(); + CHECK(gate.inflight() == 1); + } + CHECK(gate.inflight() == 0); +} + +// The memory budget's setting: what it says, and nothing else. +void settings() { + using leonida::large_compile_budget; + const auto check = [](const char* text, bool valid, bool has, std::uint64_t mib) { + const auto s = large_compile_budget(text); + CHECK(s.valid == valid); + CHECK(s.fixed.has_value() == has); + if (has) CHECK(*s.fixed == mib << 20); + }; + check(nullptr, true, false, 0); + check("", true, false, 0); + check("0", true, true, 0); + check("1", true, true, 1); + check("512", true, true, 512); + check("0512", true, true, 512); + check("12a", false, false, 0); + check(" 5", false, false, 0); + check("-1", false, false, 0); + check("1.5", false, false, 0); + check("99999999999999999999999", true, true, UINT64_MAX >> 20); // saturates: no limit, not a small number + CHECK(*large_compile_budget("99999999999999999999999").fixed >= (UINT64_MAX >> 20) << 20); +} + +// The share of the memory, and what the machine gives now: nothing unknown on Windows and Linux, and no more than three +// quarters of either limit. +void machine() { + using leonida::large_compile_share; + CHECK(large_compile_share(1000, 4000) == 750); + CHECK(large_compile_share(4000, 1000) == 750); // the commit limit has less room than the RAM + CHECK(large_compile_share(0, 4000) == 0); + const std::uint64_t budget = leonida::large_compile_budget_bytes(); +#if defined(_WIN32) || defined(__linux__) + CHECK(budget > 0); +#endif + // Read a moment apart on a running machine: the budget may not exceed either limit by more than that moment. + const std::uint64_t slack = std::uint64_t(256) << 20; + CHECK(budget <= leonida::available_memory_bytes() / 4 * 3 + slack); + CHECK(leonida::large_module_estimate(1 << 20) == (std::uint64_t(1) << 20) * leonida::kBytesPerSpirvByte); +#ifdef _WIN32 + MEMORYSTATUSEX status{}; + status.dwLength = sizeof(status); + CHECK(GlobalMemoryStatusEx(&status) != 0); + CHECK(budget <= status.ullAvailPageFile / 4 * 3 + slack); +#endif +} + +} // namespace + +int main() { + bound_and_one_always(); + many_threads(); + order(); + one_admission_wakes_the_next(); + leaving_wakes_all_that_fit(); + demand_before_speculative(); + waiting_demand_keeps_speculative_out(); + a_demand_keeps_speculative_out(); + speculative_share(); + speculative_order_and_alone(); + budget_follows_the_moment(); + estimates_stay_reserved(); + tickets(); + settings(); + machine(); + std::puts("big_compile_gate: ok"); + return 0; +} diff --git a/runtime/test/large_module_gate.h b/runtime/test/large_module_gate.h index ea805c9268..fcd29ed0ed 100644 --- a/runtime/test/large_module_gate.h +++ b/runtime/test/large_module_gate.h @@ -1,181 +1,4 @@ -// How many large SPIR-V modules vk_pipeline_check lets into the driver at once, by a memory budget. -// -// Measured on RADV GFX1201 (Mesa 25.3.6) with the Mesa shader cache off: a 5.7 MB translated ray-tracing compute -// module peaks at 1.96 GB of process memory compiling alone (~330 bytes per SPIR-V byte), a 0.36 MB one at 94 MB. -// Compiling the large ones strictly one at a time left the other threads idle: 40 modules (27 over 4 MiB) on 6 -// threads took 308 s exclusively and 75 s in parallel, 7.0 GB and 8.7 GB peak. kBytesPerSpirvByte keeps a margin -// over the measurement. -// -// The process grew past one module's peak even one at a time because glibc keeps freed memory in per-thread arenas -// (6 threads: 6.2 GB; MALLOC_ARENA_MAX=1: 2.1 GB, same modules). release_free_memory() hands it back after each -// large module. +// Moved to runtime/src: the runtime uses it too (large_module_gate.h there). #pragma once -#include -#include -#include -#include -#include -#include - -#ifdef _WIN32 -#ifndef NOMINMAX -#define NOMINMAX -#endif -#include -#endif -#if defined(__GLIBC__) -#include -#endif - -namespace leonida { - -inline constexpr uint64_t kBytesPerSpirvByte = 512; - -inline uint64_t large_module_estimate(uint64_t spirv_bytes) { return spirv_bytes * kBytesPerSpirvByte; } - -#if defined(__linux__) -// The first unsigned number in a file ("max" and unreadable files give no value). -inline bool read_u64_file(const std::string& path, uint64_t& value) { - std::FILE* f = std::fopen(path.c_str(), "r"); - if (!f) return false; - unsigned long long v = 0; - const bool ok = std::fscanf(f, "%llu", &v) == 1; - std::fclose(f); - value = v; - return ok; -} - -// The room left under the cgroup v2 memory.max of this process and of every cgroup above it (a container or -// systemd-run -p MemoryMax=...), or UINT64_MAX when none sets a limit. cgroup_root is a parameter for the tests. -inline uint64_t cgroup_memory_room(const std::string& self_cgroup_file = "/proc/self/cgroup", - const std::string& cgroup_root = "/sys/fs/cgroup") { - std::FILE* f = std::fopen(self_cgroup_file.c_str(), "r"); - if (!f) return UINT64_MAX; - char line[4096]; - std::string rel; - while (std::fgets(line, sizeof(line), f)) { - std::string l(line); - if (l.rfind("0::", 0) == 0) { // the cgroup v2 line - rel = l.substr(3); - while (!rel.empty() && (rel.back() == '\n' || rel.back() == '\r')) rel.pop_back(); - break; - } - } - std::fclose(f); - uint64_t room = UINT64_MAX; - for (std::string dir = rel; !dir.empty();) { - // In a cgroup namespace, "/" can be a constrained cgroup mounted as the visible root. - const std::string base = dir == "/" ? cgroup_root : cgroup_root + dir; - uint64_t max = 0, current = 0; - if (read_u64_file(base + "/memory.max", max) && read_u64_file(base + "/memory.current", current)) - room = std::min(room, max > current ? max - current : 0); - const auto slash = dir.find_last_of('/'); - if (dir == "/" || slash == std::string::npos) break; - dir.resize(slash == 0 ? 1 : slash); - } - return room; -} -#endif - -// Memory the OS could give this process now, or 0 when it can't tell (then the caller keeps the old exclusive gate). -inline uint64_t available_memory_bytes() { -#ifdef _WIN32 - MEMORYSTATUSEX status{}; - status.dwLength = sizeof(status); - return GlobalMemoryStatusEx(&status) ? uint64_t(status.ullAvailPhys) : 0; -#elif defined(__linux__) - std::FILE* f = std::fopen("/proc/meminfo", "r"); - if (!f) return 0; - char line[256]; - unsigned long long kb = 0; - bool found = false; - while (std::fgets(line, sizeof(line), f)) - if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) { found = true; break; } - std::fclose(f); - if (!found) return 0; - const uint64_t room = cgroup_memory_room(); - return std::max(1, std::min(uint64_t(kb) * 1024, room)); // 0 would mean "unknown" -#else - return 0; -#endif -} - -// Return memory freed by the driver's compiler to the OS (glibc keeps it in the arena of the thread that freed it). -inline void release_free_memory() { -#if defined(__GLIBC__) - malloc_trim(0); -#endif -} - -// Lets large modules in while their estimates fit the budget and fewer than max_inflight are in. One always gets in -// when none is, so a module bigger than the whole budget still compiles (alone among the large ones). -class LargeModuleGate { -public: - LargeModuleGate(uint64_t budget, unsigned max_inflight) - : budget_(budget), max_inflight_(max_inflight ? max_inflight : 1) {} - - bool admits(uint64_t estimate) const { - std::lock_guard g(mu_); - return admits_locked(estimate); - } - void enter(uint64_t estimate) { - std::unique_lock l(mu_); - cv_.wait(l, [&] { return admits_locked(estimate); }); - used_ += estimate; - ++inflight_; - } - void leave(uint64_t estimate) { - { - std::lock_guard g(mu_); - used_ -= estimate; - --inflight_; - } - cv_.notify_all(); - } - unsigned inflight() const { - std::lock_guard g(mu_); - return inflight_; - } - uint64_t budget() const { return budget_; } - unsigned max_inflight() const { return max_inflight_; } - - // Holds a place from construction until destruction (or release()), then hands freed memory back. - class Ticket { - public: - Ticket() = default; - Ticket(LargeModuleGate& gate, uint64_t estimate) : gate_(&gate), estimate_(estimate) { gate.enter(estimate); } - Ticket(Ticket&& o) noexcept : gate_(o.gate_), estimate_(o.estimate_) { o.gate_ = nullptr; } - Ticket& operator=(Ticket&& o) noexcept { - if (this != &o) { release(); gate_ = o.gate_; estimate_ = o.estimate_; o.gate_ = nullptr; } - return *this; - } - Ticket(const Ticket&) = delete; - Ticket& operator=(const Ticket&) = delete; - ~Ticket() { release(); } - void release() { - if (!gate_) return; - gate_->leave(estimate_); - gate_ = nullptr; - release_free_memory(); - } - private: - LargeModuleGate* gate_ = nullptr; - uint64_t estimate_ = 0; - }; - -private: - bool admits_locked(uint64_t estimate) const { - if (inflight_ == 0) return true; - return inflight_ < max_inflight_ && used_ + estimate <= budget_; - } - - const uint64_t budget_; - const unsigned max_inflight_; - mutable std::mutex mu_; - std::condition_variable cv_; - uint64_t used_ = 0; - unsigned inflight_ = 0; -}; - -} // namespace leonida +#include "../src/large_module_gate.h" From aa8018b7ff164efff848666c3c4205a60adbbed5 Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:42:21 +0100 Subject: [PATCH 2/3] d3d12: large pipelines compile side by side within a memory budget (RT-BIG-COMPUTE-BUDGET) Compute modules over 128 KiB and graphics pipelines of 1 MiB of SPIR-V or more wait at one gate for the process until their estimates fit the memory that is free, instead of one at a time. PipelineCompiles::build gives a submission as many lanes for them as can be in at once, largest first, and fills the rest with small ones. A thread that waits for its place holds no PSO's lock, and one that has a place waits for none. The warm-up's compiles are speculative. LEONIDA_SERIAL_BIG_COMPILES=1 keeps one at a time, 0 has no limit, LEONIDA_BIG_COMPILE_BUDGET_MB fixes the budget. --- docs/d3d12_vulkan.md | 25 +- runtime/CMakeLists.txt | 32 +- runtime/README.md | 3 +- runtime/shims/d3d12_vulkan_device.cpp | 84 +- runtime/src/vulkan_backend.h | 16 +- runtime/src/vulkan_replay.h | 74 +- runtime/test/big_compute_module.h | 298 ++++++ runtime/test/d3d12_big_compute_test.cpp | 978 ++++++++++++++++++ .../test/replay_pipeline_compiles_test.cpp | 304 +++++- 9 files changed, 1771 insertions(+), 43 deletions(-) create mode 100644 runtime/test/big_compute_module.h create mode 100644 runtime/test/d3d12_big_compute_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 53d9747968..e937d6699c 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2415,9 +2415,7 @@ Pipeline creation: is when each is compiled alone, so a PSO released meanwhile waits for the submission. The workers have ended before the session cache is read at device teardown. `LEONIDA_PIPELINE_THREADS=` sets the workers: unset, half the logical processors and at most 8; `0` compiles each pipeline on the submitting thread where `prepare()` meets it. - Graphics pipelines of 1 MiB of SPIR-V or more, and compute pipelines over 128 KiB (`LEONIDA_SERIAL_BIG_COMPILES`), - are compiled one after another beside the smaller ones, because a compile takes the driver some hundred bytes of - memory for each byte of SPIR-V ([pipeline_check.md](pipeline_check.md)); so are the variants of one PSO. + Large pipelines (below) are compiled within a memory budget, and the variants of one PSO one after another. `LEONIDA_ASYNC_PIPELINES=1` is not changed: its builds stay on the compile worker. Measured with synthetic programs never compiled before and the warm-up off (RTX 3080, NVIDIA 621.24, Windows 11, 16 logical processors, 8 workers, three runs each): the first submission of 192 graphics pipelines takes 126 to 143 ms instead of 861 to 882, of 192 @@ -2425,6 +2423,27 @@ Pipeline creation: holds about 50 MiB more (the driver keeps memory for each thread that compiles). One `VkPipelineCache` is enough: one cache per thread, merged, was about as fast. Tested by `pipeline_workers`, `replay_pipeline_compiles` and `d3d12_pipeline_workers`. +- Large pipelines: a compile takes the driver some hundred bytes of memory for each byte of SPIR-V + ([pipeline_check.md](pipeline_check.md), "Limiting concurrent compilation of large modules"), so compute modules over + 128 KiB and graphics pipelines of 1 MiB or more compile side by side only while their estimates (512 bytes for each + byte of SPIR-V) fit a budget: three quarters of the smaller of the free RAM and the room under the commit limit, read + again whenever a place at the gate (`runtime/src/large_module_gate.h`, one for the process) is given or returned. One + always gets in when none is, so a pipeline larger than the budget compiles alone. An estimate counts in full until + the compile ends, although the driver has taken part of it by then. They get in in the order they came, the ones a + submission waits for (and those of `LEONIDA_ASYNC_PIPELINES`) before the warm-up's, which take a quarter of the + budget at most and none while a submission that has large ones is compiling on its workers. A thread that waits for + its place holds no PSO's lock, and one that has a place waits for none. `PipelineCompiles::build` gives a submission + as many jobs for large ones as its smallest could be in at once, largest first; where the next one does not fit, the + job compiles small ones in the meantime. `LEONIDA_SERIAL_BIG_COMPILES=1` compiles them one after another instead, as + before there was a budget, `=0` has no limit, `LEONIDA_BIG_COMPILE_BUDGET_MB` fixes the budget. Measured with + synthetic integer modules never compiled before and the warm-up off (RTX 3080, NVIDIA 621.24, Ryzen 7 5800X3D, 8 + workers and the submitting thread, three alternating runs each): the first submission of 16 modules of 256 KiB takes + 0.8 s instead of 4.0 to 4.8 s, 16 of 512 KiB 2.0 to 2.2 s instead of 10.2 to 11.4, 15 of 1 MiB 5.8 to 6.1 s instead + of 29.2 to 31.2, 12 of 0.5 to 2 MiB 8.0 to 10.5 s instead of 38.9 to 39.9. While the 15 of 1 MiB compile, private + memory peaks 656 to 676 MiB over what it was, instead of 140 to 147 (one compile takes 85 to 131 bytes for each byte + of SPIR-V here, and the driver keeps memory for each thread that compiles). With a budget of 1536 MiB, two at once, + they take 18.5 s and peak 202 MiB over. Not measured: other drivers, and the title. Tested by `big_compile_gate`, + `replay_pipeline_compiles` and `d3d12_big_compute`. **Open:** whether the game uses `D3D12_PIPELINE_STATE_STREAM_DESC` for mesh/RT and which subobject types appear. The trace will enumerate them. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 3a95295f3c..5856f510c9 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2383,8 +2383,38 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_pipeline_workers_eager COMMAND d3d12_pipeline_workers_test) set_tests_properties(d3d12_pipeline_workers d3d12_pipeline_workers_eager PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 180 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + # One large pipeline after another: the jobs of the pool are then known (d3d12_big_compute has the budget). + set_tests_properties(d3d12_pipeline_workers PROPERTIES ENVIRONMENT "LEONIDA_SERIAL_BIG_COMPILES=1") set_tests_properties(d3d12_pipeline_workers_eager PROPERTIES - ENVIRONMENT "LEONIDA_LAZY_PIPELINES=0;LEONIDA_LAZY_COMPUTE=0") + ENVIRONMENT "LEONIDA_LAZY_PIPELINES=0;LEONIDA_LAZY_COMPUTE=0;LEONIDA_SERIAL_BIG_COMPILES=1") + # Large pipelines compiled within a memory budget, with real large compute modules: the same values for each setting + # (read once for each process). 260 MiB holds three of the modules, 1 MiB none. The modules' compile runs on the test's + # threads, so they get the loader's stack (docs/pipeline_check.md, "Stack reserve"). + add_executable(d3d12_big_compute_test test/d3d12_big_compute_test.cpp) + target_link_libraries(d3d12_big_compute_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_big_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_big_compute_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(d3d12_big_compute_test PRIVATE /STACK:${GTA6RT_STACK}) + add_test(NAME d3d12_big_compute COMMAND d3d12_big_compute_test) + add_test(NAME d3d12_big_compute_budget COMMAND d3d12_big_compute_test) + add_test(NAME d3d12_big_compute_tight COMMAND d3d12_big_compute_test) + add_test(NAME d3d12_big_compute_serial COMMAND d3d12_big_compute_test) + add_test(NAME d3d12_big_compute_unlimited COMMAND d3d12_big_compute_test) + add_test(NAME d3d12_big_compute_warmup COMMAND d3d12_big_compute_test warmup) + add_test(NAME d3d12_big_compute_eager COMMAND d3d12_big_compute_test eager) + set_tests_properties(d3d12_big_compute d3d12_big_compute_budget d3d12_big_compute_tight d3d12_big_compute_serial + d3d12_big_compute_unlimited d3d12_big_compute_warmup d3d12_big_compute_eager + PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + set_tests_properties(d3d12_big_compute_budget PROPERTIES ENVIRONMENT "LEONIDA_BIG_COMPILE_BUDGET_MB=260") + set_tests_properties(d3d12_big_compute_tight d3d12_big_compute_warmup PROPERTIES + ENVIRONMENT "LEONIDA_BIG_COMPILE_BUDGET_MB=1") + set_tests_properties(d3d12_big_compute_eager PROPERTIES + ENVIRONMENT "LEONIDA_BIG_COMPILE_BUDGET_MB=1;LEONIDA_LAZY_COMPUTE=0") + set_tests_properties(d3d12_big_compute_serial PROPERTIES # neither of these two has a budget + ENVIRONMENT "LEONIDA_SERIAL_BIG_COMPILES=1;LEONIDA_BIG_COMPILE_BUDGET_MB=4096") + set_tests_properties(d3d12_big_compute_unlimited PROPERTIES + ENVIRONMENT "LEONIDA_SERIAL_BIG_COMPILES=0;LEONIDA_BIG_COMPILE_BUDGET_MB=1") # ExecuteCommandLists refuses a list whose type isn't the queue's (debug-layer message 836). add_executable(d3d12_queue_list_type_test test/d3d12_queue_list_type_test.cpp) target_link_libraries(d3d12_queue_list_type_test PRIVATE gta6rt_d3d12_com) diff --git a/runtime/README.md b/runtime/README.md index 070fa28add..f794e40841 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 | `LEONIDA_LAZY_PIPELINES` | on | Graphics pipelines are built at their first draw. `0` builds each at `CreatePipelineState`, as before; the title creates far more pipelines at startup than it draws with. | | `LEONIDA_LAZY_COMPUTE` | on | Compute pipelines are built at the first dispatch that names them, or earlier by the warm-up thread. `0` builds each at `CreateComputePipelineState`. | | `LEONIDA_COMPUTE_WARMUP_MAX_BYTES` | `1048576` | The largest SPIR-V module, in bytes, the background warm-up thread (`LEONIDA_COMPUTE_WARMUP`) builds ahead of its first dispatch. Larger modules wait for that dispatch. | -| `LEONIDA_SERIAL_BIG_COMPILES` | on | Compute modules over 128 KiB of SPIR-V compile one at a time, because the driver's compiler needs hundreds of MiB for each. `0` lets them compile side by side. | +| `LEONIDA_SERIAL_BIG_COMPILES` | unset | Large pipelines (compute modules over 128 KiB of SPIR-V, graphics pipelines of 1 MiB or more) compile side by side while their estimates, 512 bytes of memory for each byte of SPIR-V, fit a budget (`LEONIDA_BIG_COMPILE_BUDGET_MB`): one always does, what a submission waits for goes before the warm-up, and the warm-up takes a quarter of the budget at most. `1` compiles the compute ones one at a time, and the graphics ones of a submission one after another, as before there was a budget. `0` lets all of them compile side by side. | +| `LEONIDA_BIG_COMPILE_BUDGET_MB` | unset | The budget, in MiB: a fixed number (`0`: one large pipeline at a time) instead of three quarters of the memory that is free at the moment, which is the smaller of the free RAM and the room under the commit limit, read again for each pipeline. Text that is not a number is ignored. | | `LEONIDA_CONSOLE_FORMATS` | on | Texture descriptions the console accepts and a PC GPU may not (an R9G9B9E5 render target, an sRGB RGBA8 or BGRA8 texture with unordered access) get a host format that can do the job. `0` refuses them, as a PC D3D12 runtime does. | | `LEONIDA_CONSOLE_HEAP_SHADOW` | on | A console descriptor heap has a copy in the descriptor arena that the shaders read. `0` keeps its bytes in the title's memory only (the comparison for a run that misbehaves with the copy). | | `LEONIDA_IMPORT_BELOW_ARENA` | unset | `1` keeps a host-memory import that the driver put below the GPU address arena. By default such an import is not used and the shadow buffer in the arena answers, because a V# cannot name an address below the arena. | diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index aeecf05b0d..c7dd22a9c0 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -46,6 +46,7 @@ #include "../src/pipeline_profile.h" #include "../src/submit_phases.h" #include "../src/pipeline_cache_store.h" +#include "../src/large_module_gate.h" #include "../src/conservative_raster.h" #include "../src/resource_detile.h" #include "../src/console_texture_layout.h" @@ -1402,14 +1403,39 @@ bool console_format_stand_ins() { return on; } -// A driver's compiler needs hundreds of MiB for a very large module; several at once exhausted host memory. Compute modules -// over 128 KiB compile one at a time (LEONIDA_SERIAL_BIG_COMPILES=0: as many as are asked for). -bool serial_big_compile(std::size_t spirv_bytes) { - static const bool serial = [] { +// A driver's compiler needs hundreds of MiB for a very large module; several at once exhausted host memory. Large are +// compute modules over 128 KiB and graphics pipelines of PipelineCompiles::large_spirv_bytes or more. They compile side by +// side while their estimates fit the memory that is free (big_compile_gate). LEONIDA_SERIAL_BIG_COMPILES=1: one at a time, +// as before there was a budget (graphics: one after another in each submission). 0: as many as are asked for. +enum class BigCompiles { budget, serial, unlimited }; +BigCompiles big_compiles() { + static const BigCompiles mode = [] { wchar_t v[2]{}; - return !(GetEnvironmentVariableW(L"LEONIDA_SERIAL_BIG_COMPILES", v, 2) == 1 && v[0] == L'0'); + const DWORD n = GetEnvironmentVariableW(L"LEONIDA_SERIAL_BIG_COMPILES", v, 2); + if (n == 0) return BigCompiles::budget; + return n == 1 && v[0] == L'0' ? BigCompiles::unlimited : BigCompiles::serial; }(); - return serial && spirv_bytes > 128 * 1024; + return mode; +} +bool big_compute(std::size_t spirv_bytes) { return spirv_bytes > 128 * 1024; } + +// Where large compiles wait for memory: one for the process, as the memory is the machine's. Never destroyed: static +// destruction must not race the compile worker. +leonida::LargeModuleGate& big_compile_gate() { + static auto* const gate = [] { + char text[32]{}; + std::size_t length = 0; + const bool present = getenv_s(&length, text, "LEONIDA_BIG_COMPILE_BUDGET_MB") == 0 && length > 1; + const auto setting = leonida::large_compile_budget(present ? text : ""); + if (!setting.valid) + std::fprintf(stderr, "[rt] d3d12: LEONIDA_BIG_COMPILE_BUDGET_MB=%s is not a number; not used\n", text); + auto budget = [fixed = setting.fixed] { return fixed ? *fixed : leonida::large_compile_budget_bytes(); }; + std::fprintf(stderr, "[rt] d3d12: large pipelines compile side by side within %llu MiB (%s)\n", + static_cast(budget() >> 20), + setting.fixed ? "LEONIDA_BIG_COMPILE_BUDGET_MB" : "3/4 of the memory free now"); + return new leonida::LargeModuleGate(std::move(budget)); + }(); + return *gate; } bool startup_cache_checkpoints_enabled() { @@ -8913,7 +8939,9 @@ class PipelineState final const auto it = variants_.find(unbound); return it == variants_.end() ? VkPipeline(VK_NULL_HANDLE) : it->second; }; - graphics_.large = spirv_bytes >= leonida::PipelineCompiles::large_spirv_bytes; + graphics_.large = spirv_bytes >= leonida::PipelineCompiles::large_spirv_bytes && + big_compiles() != BigCompiles::unlimited; + graphics_.estimate = leonida::large_module_estimate(spirv_bytes); if (code_stage) { VkDeviceSize offset = 0; @@ -9043,6 +9071,7 @@ class PipelineState final if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &pipeline_.layout) != VK_SUCCESS) return E_FAIL; compute_entry_ = entry; stage_bytes_ = spirv_bytes; + pipeline_.estimate = leonida::large_module_estimate(spirv_bytes); // The title creates hundreds of compute pipelines from job threads during startup and one of its init tasks // waits for all of them; some modules (wave64-emulated ray-tracing resolves, 4 MiB of SPIR-V) take the driver // minutes each. So the Vulkan pipeline is built on first use (build_compute): at the first dispatch that names @@ -9078,7 +9107,7 @@ class PipelineState final std::unique_lock lock(pso->variants_mutex_, std::try_to_lock); // held: another thread is compiling it return lock.owns_lock() ? pso->pipeline_.pipeline : VkPipeline(VK_NULL_HANDLE); }; - pipeline_.large = serial_big_compile(spirv_bytes); + pipeline_.large = big_compute(spirv_bytes) && big_compiles() != BigCompiles::unlimited; } else if (!build_compute("compute-create")) { return E_FAIL; } @@ -9099,12 +9128,32 @@ class PipelineState final } private: + using Work = leonida::LargeModuleGate::Work; + + // Locks the PSO (`lock`, on variants_mutex_) for a build and, with an `estimate`, takes the build's place at the gate. A + // thread that waits for its place holds no PSO's lock, and one that has its place waits for none: another thread may be + // building that PSO, with a place of its own. Returns without a place when the PSO is `built` already. + template + leonida::LargeModuleGate::Ticket enter_build(std::unique_lock& lock, std::uint64_t estimate, Work work, + Built&& built) { + for (;;) { + lock.lock(); + if (!estimate || built()) return {}; + lock.unlock(); + leonida::LargeModuleGate::Ticket place(big_compile_gate(), estimate, work); + if (lock.try_lock()) return place; + } + } + // The compute pipeline, built once: by create_compute (LEONIDA_LAZY_COMPUTE=0), by the first dispatch that names // it (the replay layer calls ComputePipeline::build) or by the warm-up thread. Null when it cannot be built; the // failure is logged and not retried. - VkPipeline build_compute(const char* trigger) { + VkPipeline build_compute(const char* trigger, Work work = Work::demand) { CompileActivity activity(device_.active_compiles); - std::lock_guard lock(variants_mutex_); + std::unique_lock lock(variants_mutex_, std::defer_lock); + const bool budgeted = big_compute(stage_bytes_) && big_compiles() == BigCompiles::budget; + auto place = enter_build(lock, budgeted ? pipeline_.estimate : 0, work, + [this] { return pipeline_.pipeline || compute_failed_; }); if (pipeline_.pipeline || compute_failed_) return pipeline_.pipeline; compute_failed_ = true; // until the pipeline exists auto& vk = device_.context->vk; @@ -9114,7 +9163,7 @@ class PipelineState final if (!library || !entry) return VK_NULL_HANDLE; static std::mutex big_compile; std::unique_lock big_lock(big_compile, std::defer_lock); - if (serial_big_compile(stage_bytes_)) big_lock.lock(); + if (big_compute(stage_bytes_) && big_compiles() == BigCompiles::serial) big_lock.lock(); auto words = library->spirv(*entry); if (words.empty()) { std::fprintf(stderr, "[rt] d3d12: %s.spv is missing or not SPIR-V\n", entry->name.c_str()); @@ -9149,6 +9198,7 @@ class PipelineState final profile.finish(int(created)); trace.end(trigger, entry->name.c_str(), 0, bytes, created); if (big_lock.owns_lock()) big_lock.unlock(); + place.release(); vk.vkDestroyShaderModule(dev, module, nullptr); // Vulkan lets a module go once the pipeline exists const ULONGLONG took = GetTickCount64() - started; if (created != VK_SUCCESS || !built) { @@ -9213,7 +9263,8 @@ class PipelineState final queued = PipelineCompiler::instance().submit(compile_owner(), &device_, warm_bytes, [this, compute, warm, unbound] { VkPipeline built{}; try { - built = compute ? build_compute(warm ? "warmup" : "dispatch-worker") + built = compute ? build_compute(warm ? "warmup" : "dispatch-worker", + warm ? Work::speculative : Work::demand) : variant(unbound, "draw-worker"); if (async_replay_compile()) { unsigned long long skipped = 0; @@ -9537,7 +9588,10 @@ class PipelineState final // Built on first use and kept until the PSO is released (replay may call this from any queue). VkPipeline variant(std::uint32_t unbound, const char* trigger) { - std::lock_guard lock(variants_mutex_); + std::unique_lock lock(variants_mutex_, std::defer_lock); + const bool budgeted = graphics_.large && big_compiles() == BigCompiles::budget; + const auto place = enter_build(lock, budgeted ? graphics_.estimate : 0, Work::demand, + [&] { return variants_.contains(unbound); }); if (const auto it = variants_.find(unbound); it != variants_.end()) return it->second; const VkPipeline pipeline = build(unbound, trigger); if (!pipeline) { @@ -10898,6 +10952,10 @@ class Device final threads.count); if (threads.count) state_.context->set_pipeline_workers(std::make_unique(threads.count)); + if (big_compiles() == BigCompiles::budget) + state_.context->set_large_compiles( + [] { return big_compile_gate().budget(); }, + [] { return std::make_shared(big_compile_gate()); }); } leonida::title_va_aliases().set_hooks( &state_, diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 145fa11ee5..6265ac1b27 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1569,6 +1569,14 @@ class VulkanContext { std::unique_lock lock(resource_mutex_); pipeline_workers_.swap(workers); } + // For the large pipelines of a submission: the memory they may use while they compile together + // (PipelineCompiles::build), and what is kept while they do (LargeModuleGate::Demand). None (the default): they compile + // one after another. + void set_large_compiles(std::function budget, std::function()> demand) { + std::unique_lock lock(resource_mutex_); + large_compile_budget_ = std::move(budget); + large_compile_demand_ = std::move(demand); + } PipelineWorkers::Stats pipeline_worker_stats() { std::shared_lock lock(resource_mutex_); return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{}; @@ -2185,6 +2193,8 @@ class VulkanContext { std::unordered_map pipelines_; std::unordered_map graphics_pipelines_; std::unique_ptr pipeline_workers_; + std::function large_compile_budget_; + std::function()> large_compile_demand_; std::unordered_map acceleration_structures_; LayoutTracker tracker_; std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only @@ -3121,11 +3131,15 @@ class VulkanQueue : private QueueHolds::Holder { statistics_segments += prepared[i].statistics_segment_count; has_queries = has_queries || !prepared[i].queries.empty(); } + std::shared_ptr demand; + if (context_.large_compile_demand_ && compiles.any_large()) demand = context_.large_compile_demand_(); prepare_result = build_pipelines( compiles, std::span(prepared).first(lists.size()), prepare_result, [this](std::size_t count, const std::function& job) { context_.pipeline_workers_->run(count, job); - }); + }, + context_.large_compile_budget_); + demand.reset(); if (prepare_result != ReplayResult::success) return prepare_result; const auto segment_pool = [this](VkQueryType type, std::uint32_t count, std::shared_ptr& out) { diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index e20a291057..2684768ed2 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -60,6 +60,7 @@ #include #include #include +#include #include #include #include @@ -847,8 +848,9 @@ struct ComputePipeline { // What `build` would return when it is built already and nobody is building it, else null; builds nothing. Null: a // first use is always built where prepare() meets it. Not used with async_build. See PipelineCompiles. VkPipeline (*built)(void*) = nullptr; - bool large = false; // compiled one after another with the other large ones (PipelineCompiles) + bool large = false; // PipelineCompiles limits how many of these compile at once bool skipped = false; // never built on request (LEONIDA_SKIP_COMPUTE): its dispatches are dropped + std::uint64_t estimate = 0; // large: the bytes of memory its compile is expected to take }; // A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it @@ -882,6 +884,7 @@ struct GraphicsPipeline { std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count bool async_build = false; bool nonunit_vertex_divisor = false; // an actual instance divisor > 1, not a zero-stride emulation + std::uint64_t estimate = 0; // as ComputePipeline::estimate }; // The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base. @@ -979,7 +982,7 @@ class PipelineCompiles { User user; }; // A compile takes the driver some hundred bytes of memory for each byte of SPIR-V (docs/pipeline_check.md): graphics - // pipelines of this much or more are `large`. + // pipelines of this much or more are `large`. For compute pipelines the D3D12 layer decides. static constexpr std::uint64_t large_spirv_bytes = 1u << 20; Ticket add(const GraphicsPipeline& pipeline, std::uint32_t flags) { @@ -988,26 +991,66 @@ class PipelineCompiles { Ticket add(const ComputePipeline& pipeline, User user) { return add({nullptr, &pipeline, 0}, user); } bool empty() const { return jobs_.empty(); } + bool any_large() const { + return std::any_of(jobs_.begin(), jobs_.end(), [](const Job& job) { return is_large(job); }); + } std::size_t size() const { return jobs_.size(); } VkPipeline built(Ticket ticket) const { return jobs_[ticket - 1].built; } const std::vector& uses() const { return uses_; } // in the order of the commands - // Compiles all of them through run(count, job) (PipelineWorkers::run): the large ones one after another, as without - // workers, beside the others. + // Compiles all of them through run(count, job) (PipelineWorkers::run). The large ones share budget() bytes of memory: + // the largest first, as many at once as their estimates fit, one at least; while the next one does not fit, the + // others are compiled first. No budget, or 0: the large ones one after another, as without workers, beside the others. template - void build(Run&& run) { + void build(Run&& run, const std::function& read_budget = {}) { std::vector single, large; for (std::size_t i = 0; i < jobs_.size(); ++i) (is_large(jobs_[i]) ? large : single).push_back(i); + // The first jobs of the run are lanes, which take large ones until none is left: no more of them than there are + // large ones that fit the budget together (the smallest), so that no thread waits here for room in vain. + std::size_t lanes = large.empty() ? 0 : 1; + const std::uint64_t budget = lanes && read_budget ? read_budget() : 0; + if (budget) { + std::stable_sort(large.begin(), large.end(), [this](std::size_t a, std::size_t b) { + return estimate(jobs_[a]) > estimate(jobs_[b]); + }); + std::uint64_t sum = estimate(jobs_[large.back()]); + while (lanes < large.size() && (sum += estimate(jobs_[large[large.size() - 1 - lanes]])) <= budget) ++lanes; + } const auto compile = [this](std::size_t i) { Job& job = jobs_[i]; job.built = job.graphics ? job.graphics->variant(job.flags) : job.compute->build(job.compute->build_context); }; - const std::size_t chain = large.empty() ? 0 : 1; // the large ones are one unit, the first - run(chain + single.size(), [&](std::size_t i) { - if (i >= chain) - compile(single[i - chain]); - else - for (const std::size_t each : large) compile(each); + std::mutex mutex; // guards the four below + std::size_t next_single = 0, next_large = 0, compiling = 0; + std::uint64_t reserved = 0; // the estimates of the large ones compiling + run(lanes + single.size(), [&](std::size_t i) { + std::unique_lock lock(mutex); + if (i >= lanes) { + if (next_single == single.size()) return; // a lane has taken it + const std::size_t index = single[next_single++]; + lock.unlock(); + compile(index); + return; + } + while (next_large < large.size()) { + const std::uint64_t need = estimate(jobs_[large[next_large]]); + const bool fits = !compiling || reserved + need <= budget; + if (!fits && next_single < single.size()) { + const std::size_t index = single[next_single++]; + lock.unlock(); + compile(index); + lock.lock(); + continue; + } + const std::size_t index = large[next_large++]; + ++compiling; + reserved += need; + lock.unlock(); + compile(index); + lock.lock(); + --compiling; + reserved -= need; + } }); } @@ -1019,6 +1062,9 @@ class PipelineCompiles { VkPipeline built = VK_NULL_HANDLE; }; static bool is_large(const Job& job) { return job.graphics ? job.graphics->large : job.compute->large; } + static std::uint64_t estimate(const Job& job) { + return job.graphics ? job.graphics->estimate : job.compute->estimate; + } Ticket add(const Job& job, User user) { const void* const pipeline = job.graphics ? static_cast(job.graphics) : job.compute; const auto [it, added] = tickets_.try_emplace({pipeline, job.flags}, Ticket(jobs_.size() + 1)); @@ -2906,12 +2952,12 @@ class PreparedList { // failed, if any): builds the pipelines through run(count, job), puts them into `lists`, and returns what the calls would // have returned had they built each pipeline themselves. Every use in `compiles` comes from a command before the one that // failed, so a pipeline that cannot be built counts first, at the earliest command that uses it: it fails the list of a -// draw or an indirect dispatch, and a dispatch is dropped as prepare() drops one. +// draw or an indirect dispatch, and a dispatch is dropped as prepare() drops one. `budget`: PipelineCompiles::build. template ReplayResult build_pipelines(PipelineCompiles& compiles, std::span lists, ReplayResult result, - Run&& run) { + Run&& run, const std::function& budget = {}) { if (compiles.empty()) return result; - compiles.build(run); + compiles.build(run, budget); for (const PipelineCompiles::Use& use : compiles.uses()) { if (compiles.built(use.ticket)) continue; if (use.user == PipelineCompiles::User::draw) return unsupported_at(__LINE__); diff --git a/runtime/test/big_compute_module.h b/runtime/test/big_compute_module.h new file mode 100644 index 0000000000..28dde996f9 --- /dev/null +++ b/runtime/test/big_compute_module.h @@ -0,0 +1,298 @@ +// Large compute modules that are work for a driver's compiler, not padding: a register file in a Function array that every +// instruction loads from and stores to (as the translator's modules have it), integer instructions, selections, nested +// conditionals and loops, and loads from memory the compiler knows nothing about. The same instructions run on the CPU, so +// the value that a dispatch stores is known. Made from a seed; no game data. +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace bigmodule { + +using Words = std::vector; + +inline void op(Words& out, std::uint16_t code, std::initializer_list operands) { + out.push_back((std::uint32_t(operands.size() + 1) << 16) | code); + out.insert(out.end(), operands.begin(), operands.end()); +} + +enum class Kind : std::uint8_t { add, sub, mul, xor_, and_, or_, shl, shr, select, load, if_, end_if, loop, end_loop }; + +struct Instruction { + Kind kind; + std::uint8_t d = 0, a = 0, b = 0, c = 0; // registers; c is a shift count or a loop count for those kinds +}; + +constexpr unsigned kRegisters = 48, kConstants = 64, kDepth = 3; +constexpr unsigned kLoadBase = 256, kLoadWords = 64; // the words of the buffer the loads read (the CPU takes them as 0) + +struct Program { + std::vector code; + std::uint32_t constants[kConstants]; + + // What the module stores for the dispatch with this root constant. + std::uint32_t run(std::uint32_t root_constant) const { + std::uint32_t v[kRegisters]; + for (unsigned i = 0; i < kRegisters; ++i) v[i] = constants[i % kConstants] ^ (root_constant + i); + walk(0, v); + std::uint32_t out = 0; + for (unsigned i = 0; i < kRegisters; ++i) out ^= v[i]; + return out; + } + +private: + // Runs from `at` to the end marker of its block and returns the index after it. + std::size_t walk(std::size_t at, std::uint32_t* v) const { + for (; at < code.size();) { + const Instruction& i = code[at]; + const std::uint32_t k = constants[i.c % kConstants]; + switch (i.kind) { + case Kind::add: v[i.d] = v[i.a] + v[i.b] + k; break; + case Kind::sub: v[i.d] = v[i.a] - v[i.b] - k; break; + case Kind::mul: v[i.d] = v[i.a] * v[i.b] * k; break; + case Kind::xor_: v[i.d] = v[i.a] ^ v[i.b] ^ k; break; + case Kind::and_: v[i.d] = v[i.a] & (v[i.b] | k); break; + case Kind::or_: v[i.d] = v[i.a] | (v[i.b] & k); break; + case Kind::shl: v[i.d] = (v[i.a] << (i.c & 31)) ^ v[i.b]; break; + case Kind::shr: v[i.d] = (v[i.a] >> (i.c & 31)) ^ v[i.b]; break; + case Kind::select: v[i.d] = v[i.a] < v[i.b] ? v[i.c % kRegisters] : v[i.a]; break; + case Kind::load: v[i.d] = v[i.b]; break; // + the loaded word, which is 0 + case Kind::if_: { + std::size_t after = at + 1; + if (v[i.a] < v[i.b]) + after = walk(at + 1, v); + else + after = skip(at + 1); + at = after; + continue; + } + case Kind::loop: { + std::size_t after = at + 1; + for (unsigned n = 0; n < i.c; ++n) after = walk(at + 1, v); + at = after; + continue; + } + case Kind::end_if: + case Kind::end_loop: return at + 1; + } + ++at; + } + return at; + } + std::size_t skip(std::size_t at) const { + for (int depth = 1; at < code.size(); ++at) { + const Kind k = code[at].kind; + if (k == Kind::if_ || k == Kind::loop) ++depth; + if ((k == Kind::end_if || k == Kind::end_loop) && !--depth) return at + 1; + } + return at; + } +}; + +// A module of about `bytes` bytes of SPIR-V (a few KiB more), and the program it runs. `seed` decides everything. It has the +// translator's push-constant block: s[4]:s[5] is the console VA of a root UAV, s[6] a root constant. A dispatch stores +// Program::run(s[6]) at the UAV's word s[6], and reads its words kLoadBase to kLoadBase + kLoadWords - 1, which have to +// be 0. +inline Words make(std::size_t bytes, std::uint64_t seed, Program* out = nullptr) { + std::mt19937_64 random(seed); + Program program; + for (auto& c : program.constants) c = std::uint32_t(random()); + // Ids. + enum : std::uint32_t { + id_void = 1, id_fn, id_main, id_uint, id_ulong, id_bool, id_block, id_sarr, id_c32, id_ptr_push_block, + id_push, id_ptr_push_uint, id_ptr_push_ulong, id_data, id_ptr_data, id_ptr_phys_uint, id_regs, id_cregs, + id_ptr_regs, id_ptr_fn_uint, id_vregs, id_entry, id_c64_32, id_c64_2, id_mask, id_base, + id_index0 = 40, // uint constants 0..127 + id_const0 = id_index0 + 128, // the program's constants + id_counter0 = id_const0 + kConstants, // loop counters by depth + id_first = id_counter0 + kDepth + 1, + }; + std::uint32_t next = id_first; + Words w = {0x07230203u, 0x00010500u, 0u, 0u, 0u}; + op(w, 17, {1}); // Shader + op(w, 17, {11}); // Int64 + op(w, 17, {5347}); // PhysicalStorageBufferAddresses + op(w, 14, {5348, 1}); + op(w, 15, {5, id_main, 0x6e69616du, 0u, id_push}); + op(w, 16, {id_main, 17, 1, 1, 1}); + op(w, 71, {id_sarr, 6, 4}); + op(w, 71, {id_block, 2}); + op(w, 72, {id_block, 0, 35, 0}); + op(w, 72, {id_block, 1, 35, 128}); + op(w, 72, {id_block, 2, 35, 136}); + op(w, 71, {id_data, 2}); + op(w, 72, {id_data, 0, 35, 0}); + op(w, 19, {id_void}); + op(w, 33, {id_fn, id_void}); + op(w, 21, {id_uint, 32, 0}); + op(w, 21, {id_ulong, 64, 0}); + op(w, 20, {id_bool}); + op(w, 43, {id_uint, id_c32, 32}); + op(w, 28, {id_sarr, id_uint, id_c32}); + op(w, 30, {id_block, id_sarr, id_ulong, id_ulong}); + op(w, 32, {id_ptr_push_block, 9, id_block}); + op(w, 59, {id_ptr_push_block, id_push, 9}); + op(w, 32, {id_ptr_push_uint, 9, id_uint}); + op(w, 32, {id_ptr_push_ulong, 9, id_ulong}); + op(w, 30, {id_data, id_uint}); + op(w, 32, {id_ptr_data, 5349, id_data}); + op(w, 32, {id_ptr_phys_uint, 5349, id_uint}); + op(w, 43, {id_uint, id_cregs, kRegisters}); + op(w, 28, {id_regs, id_uint, id_cregs}); + op(w, 32, {id_ptr_regs, 7, id_regs}); + op(w, 32, {id_ptr_fn_uint, 7, id_uint}); + op(w, 43, {id_ulong, id_c64_32, 32, 0}); + op(w, 43, {id_ulong, id_c64_2, 2, 0}); + op(w, 43, {id_uint, id_mask, kLoadWords - 1}); + op(w, 43, {id_uint, id_base, kLoadBase}); + for (std::uint32_t i = 0; i < 128; ++i) op(w, 43, {id_uint, id_index0 + i, i}); + for (std::uint32_t i = 0; i < kConstants; ++i) op(w, 43, {id_uint, id_const0 + i, program.constants[i]}); + op(w, 54, {id_void, id_main, 0, id_fn}); + op(w, 248, {id_entry}); + op(w, 59, {id_ptr_regs, id_vregs, 7}); + for (std::uint32_t i = 0; i <= kDepth; ++i) op(w, 59, {id_ptr_fn_uint, id_counter0 + i, 7}); + const auto unary = [&](std::uint16_t code, std::uint32_t type, std::uint32_t a) { + op(w, code, {type, next, a}); + return next++; + }; + const auto binary = [&](std::uint16_t code, std::uint32_t type, std::uint32_t a, std::uint32_t b) { + op(w, code, {type, next, a, b}); + return next++; + }; + const auto push_word = [&](std::uint32_t index) { + op(w, 65, {id_ptr_push_uint, next, id_push, id_index0, id_index0 + index}); + return unary(61, id_uint, next++); + }; + const std::uint32_t lo = push_word(4), hi = push_word(5); + op(w, 65, {id_ptr_push_ulong, next, id_push, id_index0 + 1}); + const std::uint32_t heap = unary(61, id_ulong, next++); + const std::uint32_t lo64 = unary(113, id_ulong, lo), hi64 = unary(113, id_ulong, hi); + const std::uint32_t high = binary(196, id_ulong, hi64, id_c64_32); + const std::uint32_t va = binary(197, id_ulong, high, lo64); + const std::uint32_t base = binary(128, id_ulong, va, heap); + const std::uint32_t root = push_word(6); + const auto slot = [&](std::uint32_t r) { + op(w, 65, {id_ptr_fn_uint, next, id_vregs, id_index0 + r}); + return next++; + }; + const auto load_reg = [&](std::uint32_t r) { return unary(61, id_uint, slot(r)); }; + const auto store_reg = [&](std::uint32_t r, std::uint32_t value) { + const std::uint32_t p = slot(r); + op(w, 62, {p, value}); + }; + for (std::uint32_t i = 0; i < kRegisters; ++i) { + const std::uint32_t seeded = binary(128, id_uint, root, id_index0 + i); + store_reg(i, binary(198, id_uint, id_const0 + i % kConstants, seeded)); + } + struct Open { + Kind kind; + std::uint32_t merge, header, cont, counter; + unsigned left; + }; + std::vector open; + unsigned loops = 0; + const auto pick = [&](std::uint32_t n) { return std::uint8_t(random() % n); }; + const auto close = [&] { + const Open o = open.back(); + open.pop_back(); + if (o.kind == Kind::if_) { + op(w, 249, {o.merge}); + op(w, 248, {o.merge}); + program.code.push_back({Kind::end_if}); + } else { + op(w, 249, {o.cont}); + op(w, 248, {o.cont}); + const std::uint32_t n = unary(61, id_uint, o.counter); + op(w, 62, {o.counter, binary(128, id_uint, n, id_index0 + 1)}); + op(w, 249, {o.header}); + op(w, 248, {o.merge}); + program.code.push_back({Kind::end_loop}); + --loops; + } + }; + while (w.size() * 4 + 256 < bytes) { + const std::uint32_t roll = std::uint32_t(random() % 100); + if (roll < 4 && open.size() < kDepth) { + const std::uint8_t a = pick(kRegisters), b = pick(kRegisters); + const std::uint32_t condition = binary(176, id_bool, load_reg(a), load_reg(b)); // ULessThan + const std::uint32_t then = next++, merge = next++; + op(w, 247, {merge, 0}); + op(w, 250, {condition, then, merge}); + op(w, 248, {then}); + open.push_back({Kind::if_, merge, 0, 0, 0, 10 + unsigned(random() % 30)}); + program.code.push_back({Kind::if_, 0, a, b, 0}); + } else if (roll < 5 && open.size() < kDepth && loops < 1) { + const std::uint8_t count = std::uint8_t(2 + random() % 3); + const std::uint32_t counter = id_counter0 + loops++; + op(w, 62, {counter, id_index0}); + const std::uint32_t header = next++, check = next++, body = next++, cont = next++, merge = next++; + op(w, 249, {header}); + op(w, 248, {header}); + op(w, 246, {merge, cont, 0}); + op(w, 249, {check}); + op(w, 248, {check}); + const std::uint32_t n = unary(61, id_uint, counter); + const std::uint32_t more = binary(176, id_bool, n, id_index0 + count); + op(w, 250, {more, body, merge}); + op(w, 248, {body}); + open.push_back({Kind::loop, merge, header, cont, counter, 20 + unsigned(random() % 20)}); + program.code.push_back({Kind::loop, 0, 0, 0, count}); + } else { + Instruction i{Kind(random() % 10), pick(kRegisters), pick(kRegisters), pick(kRegisters), pick(kConstants)}; + if (i.kind == Kind::load && random() % 2) i.kind = Kind::add; + const std::uint32_t k = id_const0 + i.c % kConstants; + std::uint32_t value = 0; + const std::uint32_t a = load_reg(i.a), b = load_reg(i.b); + switch (i.kind) { + case Kind::add: value = binary(128, id_uint, binary(128, id_uint, a, b), k); break; + case Kind::sub: value = binary(130, id_uint, binary(130, id_uint, a, b), k); break; + case Kind::mul: value = binary(132, id_uint, binary(132, id_uint, a, b), k); break; + case Kind::xor_: value = binary(198, id_uint, binary(198, id_uint, a, b), k); break; + case Kind::and_: value = binary(199, id_uint, a, binary(197, id_uint, b, k)); break; + case Kind::or_: value = binary(197, id_uint, a, binary(199, id_uint, b, k)); break; + case Kind::shl: value = binary(198, id_uint, binary(196, id_uint, a, id_index0 + (i.c & 31)), b); break; + case Kind::shr: value = binary(198, id_uint, binary(194, id_uint, a, id_index0 + (i.c & 31)), b); break; + case Kind::select: { + const std::uint32_t c = load_reg(i.c % kRegisters); + const std::uint32_t less = binary(176, id_bool, a, b); + op(w, 169, {id_uint, next, less, c, a}); + value = next++; + break; + } + default: { // load + const std::uint32_t index = binary(128, id_uint, binary(199, id_uint, a, id_mask), id_base); + const std::uint32_t offset = binary(196, id_ulong, unary(113, id_ulong, index), id_c64_2); + const std::uint32_t address = binary(128, id_ulong, base, offset); + const std::uint32_t data = unary(120, id_ptr_data, address); + op(w, 65, {id_ptr_phys_uint, next, data, id_index0}); + const std::uint32_t pointer = next++; + op(w, 61, {id_uint, next, pointer, 2, 4}); + const std::uint32_t loaded = next++; + value = binary(128, id_uint, b, loaded); + break; + } + } + store_reg(i.d, value); + program.code.push_back(i); + } + if (!open.empty() && !open.back().left--) close(); + } + while (!open.empty()) close(); + std::uint32_t result = load_reg(0); + for (std::uint32_t i = 1; i < kRegisters; ++i) result = binary(198, id_uint, result, load_reg(i)); + const std::uint32_t out_offset = binary(196, id_ulong, unary(113, id_ulong, root), id_c64_2); + const std::uint32_t out_data = unary(120, id_ptr_data, binary(128, id_ulong, base, out_offset)); + op(w, 65, {id_ptr_phys_uint, next, out_data, id_index0}); + op(w, 62, {next++, result, 2, 4}); + op(w, 253, {}); + op(w, 56, {}); + w[3] = next; + if (out) *out = std::move(program); + return w; +} + +} // namespace bigmodule diff --git a/runtime/test/d3d12_big_compute_test.cpp b/runtime/test/d3d12_big_compute_test.cpp new file mode 100644 index 0000000000..c6469719e3 --- /dev/null +++ b/runtime/test/d3d12_big_compute_test.cpp @@ -0,0 +1,978 @@ +// Large pipelines that a submission compiles (LEONIDA_SERIAL_BIG_COMPILES, LEONIDA_BIG_COMPILE_BUDGET_MB), through the D3D12 +// layer on a GPU: real compute modules of more than 128 KiB (big_compute_module.h), small ones, and graphics pipelines of more than +// 1 MiB. Both settings are read once for each process, so the test runs once for each: with a fixed budget, one that holds +// nothing, the one read from the machine, one at a time and without a limit. Every run +// - stores what the CPU computes for each dispatch, and draws the graphics pipelines' cells; +// - compiles as many large ones at once as the setting allows and no more, and the small ones meanwhile; +// - gives a pipeline the driver refuses the result it has always had, and its place to the next; +// - compiles each pipeline once when two queues need the same ones; +// - ends when the device's last references go while its workers compile and wait for memory. +// `warmup`: a submission's compiles go before those of the warm-up thread, which waits without holding a pipeline state. +// `eager`: pipeline states compiled when they are created (LEONIDA_LAZY_COMPUTE=0), by several threads, keep the budget too. +// The calls that create pipelines are watched, and held back, through the device's vkGetDeviceProcAddr. +// Self-contained: builds its SPIR-V in memory. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. +#include "big_compute_module.h" +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "test_temp_dir.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_pipeline_compile.h" +#include "../src/large_module_gate.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace std::chrono_literals; +using d3d12test::Ref; +using leonida::ReplayResult; +using bigmodule::Words; +using bigmodule::op; + +constexpr unsigned kBig = 6, kSmall = 4, kCompute = kBig + kSmall, kGraphics = 2; +constexpr std::size_t kBigBytes = 132 * 1024, kSmallBytes = 12 * 1024; +constexpr unsigned kExtent = 4; // the render target; each graphics pipeline draws one 2x2 cell +constexpr unsigned kWords = bigmodule::kLoadBase + bigmodule::kLoadWords; + +#define CHECK(expr) \ + do { \ + if (!(expr)) { \ + std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #expr); \ + return false; \ + } \ + } while (0) + +// ---- What the settings of this process say. ---- + +std::string setting(const char* name) { + char text[64]{}; + std::size_t length = 0; + return getenv_s(&length, text, name) == 0 && length > 1 ? text : ""; +} +const bool serial = setting("LEONIDA_SERIAL_BIG_COMPILES") == "1"; +const bool unlimited = setting("LEONIDA_SERIAL_BIG_COMPILES") == "0"; +const bool budgeted = !serial && !unlimited; +const auto fixed_budget = leonida::large_compile_budget(setting("LEONIDA_BIG_COMPILE_BUDGET_MB").c_str()).fixed; + +// ---- The driver's pipeline calls, watched. ---- + +struct Start { + std::thread::id thread; + int program = -1; // compute: the index of its module + bool large = false; +}; + +struct Hooks { + std::mutex mutex; + std::condition_variable changed; + std::map programs; // the hash of a compute module's words: its index + std::map> modules; // bytes, program + bool closed = false; // large creations wait while it is + std::chrono::milliseconds linger{0}; // and each takes at least this long, as does what follows it on its thread + std::vector started; + int large_in = 0, most_large = 0, small_done = 0, large_compute_in = 0, most_large_compute = 0; + std::uint64_t reserved = 0; // the estimates of the large ones in the driver + int over = 0; // how often several were in past the budget, or two where one is allowed + int fail_large = -1; // the large compute create (counted from 0) the driver refuses + int large_compute = 0; + bool track = false; // threads that create a pipeline are counted until they end + int live = 0, in_flight = 0, cache_reads = 0; + bool cache_read_during_create = false, cache_read_with_workers = false; + + void reset() { + std::lock_guard lock(mutex); + closed = track = cache_read_during_create = cache_read_with_workers = false; + started.clear(); + most_large = small_done = most_large_compute = over = large_compute = cache_reads = 0; + fail_large = -1; + linger = 0ms; + } + void open() { + std::lock_guard lock(mutex); + closed = false; + changed.notify_all(); + } + template + bool wait(Until&& until) { + std::unique_lock lock(mutex); + return changed.wait_for(lock, 20s, until); + } + bool wait_large(int count) { + return wait([&] { return large_in >= count; }); + } + std::size_t creates() { + std::lock_guard lock(mutex); + return started.size(); + } +} hooks; + +struct Tracked { + bool on = false; + ~Tracked() { + if (!on) return; + std::lock_guard lock(hooks.mutex); + --hooks.live; + } +}; +thread_local Tracked tracked; + +PFN_vkGetInstanceProcAddr real_instance_proc = nullptr; +PFN_vkGetDeviceProcAddr real_device_proc = nullptr; +PFN_vkCreateShaderModule real_create_module = nullptr; +PFN_vkDestroyShaderModule real_destroy_module = nullptr; +PFN_vkCreateGraphicsPipelines real_create_graphics = nullptr; +PFN_vkCreateComputePipelines real_create_compute = nullptr; +PFN_vkGetPipelineCacheData real_cache_data = nullptr; + +std::uint64_t hash(const std::uint32_t* words, std::size_t count) { + std::uint64_t h = 0xcbf29ce484222325u; + for (std::size_t i = 0; i < count; ++i) h = (h ^ words[i]) * 0x100000001b3u; + return h; +} + +struct Creation { + bool large = false, compute = false, refused = false; + std::uint64_t estimate = 0; +}; + +Creation enter_create(bool compute, std::initializer_list modules) { + std::unique_lock lock(hooks.mutex); + Creation c; + c.compute = compute; + std::size_t bytes = 0; + Start start{std::this_thread::get_id(), -1, false}; + for (const VkShaderModule module : modules) { + const auto found = hooks.modules.find(module); + if (found == hooks.modules.end()) continue; + bytes += found->second.first; + if (compute) start.program = found->second.second; + } + c.large = start.large = bytes > (compute ? 128 * 1024 : leonida::PipelineCompiles::large_spirv_bytes - 1); + c.estimate = leonida::large_module_estimate(bytes); + ++hooks.in_flight; + hooks.started.push_back(start); + if (hooks.track && !tracked.on) { + tracked.on = true; + ++hooks.live; + } + if (c.large) { + ++hooks.large_in; + if (compute) ++hooks.large_compute_in; + hooks.most_large = std::max(hooks.most_large, hooks.large_in); + hooks.most_large_compute = std::max(hooks.most_large_compute, hooks.large_compute_in); + hooks.reserved += c.estimate; + // One large compute module at a time; with a budget, several only within it. + if (serial && hooks.large_compute_in > 1) ++hooks.over; + if (budgeted && fixed_budget && hooks.large_in > 1 && hooks.reserved > *fixed_budget) ++hooks.over; + if (compute && hooks.large_compute++ == hooks.fail_large) c.refused = true; + } + hooks.changed.notify_all(); + if (c.large) hooks.changed.wait(lock, [] { return !hooks.closed; }); + const auto linger = hooks.linger; + lock.unlock(); + if (c.large && linger > 0ms) std::this_thread::sleep_for(linger); + return c; +} + +void leave_create(const Creation& c) { + std::lock_guard lock(hooks.mutex); + --hooks.in_flight; + if (c.large) { + --hooks.large_in; + if (c.compute) --hooks.large_compute_in; + hooks.reserved -= c.estimate; + } else { + ++hooks.small_done; + } + hooks.changed.notify_all(); +} + +VKAPI_ATTR VkResult VKAPI_CALL create_module(VkDevice device, const VkShaderModuleCreateInfo* info, + const VkAllocationCallbacks* allocator, VkShaderModule* out) { + const VkResult result = real_create_module(device, info, allocator, out); + if (result == VK_SUCCESS) { + std::lock_guard lock(hooks.mutex); + const auto found = hooks.programs.find(hash(info->pCode, info->codeSize / 4)); + hooks.modules[*out] = {info->codeSize, found == hooks.programs.end() ? -1 : found->second}; + } + return result; +} + +// Called between the place a compile gives back and the next one its thread asks for: with a linger, time for another +// thread to take that place. +VKAPI_ATTR void VKAPI_CALL destroy_module(VkDevice device, VkShaderModule module, const VkAllocationCallbacks* allocator) { + std::chrono::milliseconds linger; + { + std::lock_guard lock(hooks.mutex); + linger = hooks.linger; + } + if (linger > 0ms) std::this_thread::sleep_for(linger); + real_destroy_module(device, module, allocator); +} + +VKAPI_ATTR VkResult VKAPI_CALL create_graphics(VkDevice device, VkPipelineCache cache, std::uint32_t count, + const VkGraphicsPipelineCreateInfo* infos, + const VkAllocationCallbacks* allocator, VkPipeline* out) { + VkShaderModule modules[2]{}; + for (std::uint32_t i = 0; i < std::min(infos->stageCount, 2u); ++i) modules[i] = infos->pStages[i].module; + const Creation c = enter_create(false, {modules[0], modules[1]}); + const VkResult result = real_create_graphics(device, cache, count, infos, allocator, out); + leave_create(c); + return result; +} + +VKAPI_ATTR VkResult VKAPI_CALL create_compute(VkDevice device, VkPipelineCache cache, std::uint32_t count, + const VkComputePipelineCreateInfo* infos, + const VkAllocationCallbacks* allocator, VkPipeline* out) { + const Creation c = enter_create(true, {infos->stage.module}); + const VkResult result = c.refused ? VK_ERROR_UNKNOWN + : real_create_compute(device, cache, count, infos, allocator, out); + leave_create(c); + return result; +} + +VKAPI_ATTR VkResult VKAPI_CALL cache_data(VkDevice device, VkPipelineCache cache, std::size_t* size, void* data) { + { + std::lock_guard lock(hooks.mutex); + ++hooks.cache_reads; + if (hooks.in_flight) hooks.cache_read_during_create = true; + if (hooks.live > (tracked.on ? 1 : 0)) hooks.cache_read_with_workers = true; + } + return real_cache_data(device, cache, size, data); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL device_proc(VkDevice device, const char* name) { + const PFN_vkVoidFunction real = real_device_proc(device, name); + if (!real) return nullptr; + const auto watch = [&](const char* which, auto& kept, auto* mine) -> PFN_vkVoidFunction { + if (std::strcmp(name, which)) return nullptr; + kept = reinterpret_cast>(real); + return reinterpret_cast(mine); + }; + if (const auto f = watch("vkCreateShaderModule", real_create_module, create_module)) return f; + if (const auto f = watch("vkDestroyShaderModule", real_destroy_module, destroy_module)) return f; + if (const auto f = watch("vkCreateGraphicsPipelines", real_create_graphics, create_graphics)) return f; + if (const auto f = watch("vkCreateComputePipelines", real_create_compute, create_compute)) return f; + if (const auto f = watch("vkGetPipelineCacheData", real_cache_data, cache_data)) return f; + return real; +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL instance_proc(VkInstance instance, const char* name) { + if (!std::strcmp(name, "vkGetDeviceProcAddr")) { + real_device_proc = reinterpret_cast(real_instance_proc(instance, name)); + return reinterpret_cast(device_proc); + } + return real_instance_proc(instance, name); +} + +// ---- The shaders. ---- + +std::uint32_t bits(float f) { return std::bit_cast(f); } + +// 1.25 MiB of OpString, which compile to nothing: a graphics pipeline that is large. +void pad(Words& w, std::uint32_t first_id) { + for (std::uint32_t i = 0; i < 5; ++i) { + const std::size_t at = w.size(); + w.resize(at + 65535, 0x20202020u); + w[at] = 65535u << 16 | 7; + w[at + 1] = first_id + i; + w.back() = 0; + } +} + +// A full-screen triangle from VertexIndex. +Words vertex_words() { + Words w = {0x07230203u, 0x00010500u, 0u, 42u, 0u}; + op(w, 17, {1}); // Capability Shader + op(w, 14, {0, 1}); // MemoryModel Logical GLSL450 + op(w, 15, {0, 4, 0x6e69616du, 0u, 10, 11}); // EntryPoint Vertex "main" + op(w, 71, {10, 11, 0}); // BuiltIn Position + op(w, 71, {11, 11, 42}); // BuiltIn VertexIndex + op(w, 19, {1}); + op(w, 33, {2, 1}); + op(w, 22, {3, 32}); + op(w, 23, {6, 3, 4}); + op(w, 21, {15, 32, 1}); + op(w, 32, {7, 3, 6}); + op(w, 32, {8, 1, 15}); + op(w, 59, {7, 10, 3}); + op(w, 59, {8, 11, 1}); + op(w, 43, {15, 24, 1}); + op(w, 43, {15, 25, 2}); + op(w, 43, {3, 26, bits(2.0f)}); + op(w, 43, {3, 27, bits(-1.0f)}); + op(w, 43, {3, 28, bits(0.0f)}); + op(w, 43, {3, 29, bits(1.0f)}); + op(w, 54, {1, 4, 0, 2}); + op(w, 248, {30}); + op(w, 61, {15, 31, 11}); + op(w, 196, {15, 32, 31, 24}); // index << 1 + op(w, 199, {15, 33, 32, 25}); // & 2 + op(w, 199, {15, 34, 31, 25}); // index & 2 + op(w, 111, {3, 35, 33}); + op(w, 111, {3, 36, 34}); + op(w, 133, {3, 37, 35, 26}); + op(w, 133, {3, 38, 36, 26}); + op(w, 129, {3, 39, 37, 27}); + op(w, 129, {3, 40, 38, 27}); + op(w, 80, {6, 41, 39, 40, 28, 29}); + op(w, 62, {10, 41}); + op(w, 253, {}); + op(w, 56, {}); + return w; +} + +// The colour (n / 255, 1 - n / 255, 0, 1). +Words fragment_words(unsigned n) { + Words w = {0x07230203u, 0x00010500u, 0u, 40u, 0u}; + op(w, 17, {1}); + op(w, 14, {0, 1}); + op(w, 15, {4, 4, 0x6e69616du, 0u, 9}); // EntryPoint Fragment "main" + op(w, 16, {4, 7}); // OriginUpperLeft + pad(w, 30); + op(w, 71, {9, 30, 0}); // Location 0 + op(w, 19, {1}); + op(w, 33, {2, 1}); + op(w, 22, {3, 32}); + op(w, 23, {6, 3, 4}); + op(w, 32, {10, 3, 6}); + op(w, 59, {10, 9, 3}); + op(w, 43, {3, 20, bits(float(n) / 255.0f)}); + op(w, 43, {3, 21, bits(float(255 - n) / 255.0f)}); + op(w, 43, {3, 22, bits(0.0f)}); + op(w, 43, {3, 23, bits(1.0f)}); + op(w, 44, {6, 24, 20, 21, 22, 23}); + op(w, 54, {1, 4, 0, 2}); + op(w, 248, {11}); + op(w, 62, {9, 24}); + op(w, 253, {}); + op(w, 56, {}); + return w; +} + +std::vector program(unsigned stage, unsigned n) { + return d3d12test::fssm_program({0x42434f00u + stage, n, 0xbf810000u}); +} + +std::vector programs(kCompute); // what each compute module runs +std::vector module_bytes(kCompute); + +bool write_library(const std::filesystem::path& dir) { + const auto write = [&](const std::string& name, const Words& words) { + std::ofstream f(dir / (name + ".spv"), std::ios::binary | std::ios::trunc); + f.write(reinterpret_cast(words.data()), std::streamsize(words.size() * 4)); + return bool(f); + }; + CHECK(write("vs", vertex_words())); + std::ofstream index(dir / "index.json", std::ios::binary | std::ios::trunc); + index << "{\"vs\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(program(0, 0)) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": []}"; + for (unsigned n = 0; n < kGraphics; ++n) { + const std::string name = "ps" + std::to_string(n); + CHECK(write(name, fragment_words(n))); + index << ",\n\"" << name << "\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(program(1, n)) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"inputs\": [], \"outputs\": [0]}"; + } + for (unsigned n = 0; n < kCompute; ++n) { + const std::string name = "cs" + std::to_string(n); + // Every large one a little larger than the one before, so that the order by size is known. + const Words words = bigmodule::make(n < kBig ? kBigBytes + n * 1024 : kSmallBytes, 20251125 + n, &programs[n]); + module_bytes[n] = words.size() * 4; + CHECK((module_bytes[n] > 128 * 1024) == (n < kBig)); + hooks.programs[hash(words.data(), words.size())] = int(n); + CHECK(write(name, words)); + index << ",\n\"" << name << "\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(program(2, n)) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"local_size\": [1, 1, 1], \"wave64\": false}"; + } + index << "}"; + return bool(index); +} + +// ---- The device and what it runs. ---- + +struct Setup { + vktest::Device* vk; + std::string library; + + bool device(const char* threads, Ref& out) const { + _putenv_s("LEONIDA_PIPELINE_THREADS", threads); + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = instance_proc; + info.instance = vk->instance; + info.physical = vk->physical; + info.device = vk->device; + info.queue = vk->queue; + info.queue_family = vk->family; + info.buffer_device_address = true; + info.subgroup = vk->subgroup; + info.features = vk->enabled; + info.shader_dir = library; + CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&out.p)))); + return true; + } +}; + +struct Pipelines { + Ref root; + std::vector compute, graphics; + ~Pipelines() { release(); } + void release() { + for (auto* s : compute) + if (s) s->Release(); + for (auto* s : graphics) s->Release(); + compute.clear(); + graphics.clear(); + } + + static ID3D12PipelineState* compute_state(ID3D12Device* dev, ID3D12RootSignature* root, unsigned n) { + const auto cs = d3d12test::shader_container(program(2, n)); + D3D12_COMPUTE_PIPELINE_STATE_DESC pd{}; + pd.pRootSignature = root; + pd.CS = {cs.data(), cs.size()}; + ID3D12PipelineState* state = nullptr; + return SUCCEEDED(dev->CreateComputePipelineState(&pd, IID_PPV_ARGS(&state))) ? state : nullptr; + } + + // The compute states on `threads` threads. + bool create(ID3D12Device* dev, unsigned threads = 1) { + D3D12_ROOT_PARAMETER params[2]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[1].Constants.Num32BitValues = 1; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc{}; + desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto blob = d3d12test::serialize_root_signature(desc); + CHECK(SUCCEEDED(dev->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root.p)))); + compute.assign(kCompute, nullptr); + std::vector creating; + for (unsigned t = 1; t < threads; ++t) + creating.emplace_back([&, t] { + for (unsigned n = t; n < kCompute; n += threads) compute[n] = compute_state(dev, root.p, n); + }); + for (unsigned n = 0; n < kCompute; n += threads) compute[n] = compute_state(dev, root.p, n); + for (auto& t : creating) t.join(); + CHECK(std::find(compute.begin(), compute.end(), nullptr) == compute.end()); + const auto vs = d3d12test::shader_container(program(0, 0)); + for (unsigned n = 0; n < kGraphics; ++n) { + const auto ps = d3d12test::shader_container(program(1, n)); + D3D12_GRAPHICS_PIPELINE_STATE_DESC pd{}; + pd.pRootSignature = root.p; + pd.VS = {vs.data(), vs.size()}; + pd.PS = {ps.data(), ps.size()}; + for (auto& rt : pd.BlendState.RenderTarget) { + rt.SrcBlend = rt.SrcBlendAlpha = D3D12_BLEND_ONE; + rt.DestBlend = rt.DestBlendAlpha = D3D12_BLEND_ZERO; + rt.BlendOp = rt.BlendOpAlpha = D3D12_BLEND_OP_ADD; + rt.LogicOp = D3D12_LOGIC_OP_NOOP; + rt.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + } + pd.SampleMask = UINT_MAX; + pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pd.RasterizerState.DepthClipEnable = TRUE; + pd.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + pd.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + pd.NumRenderTargets = 1; + pd.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + pd.SampleDesc = {1, 0}; + ID3D12PipelineState* state = nullptr; + CHECK(SUCCEEDED(dev->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&state)))); + graphics.push_back(state); + } + return true; + } +}; + +// A queue and a list that dispatches `compute` (and draws the graphics pipelines), then copies what they wrote back. +struct Frame { + std::vector compute; + bool graphics = false; + Ref target, buffer, readback; + Ref rtvs; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + UINT64 fence_value = 0; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT foot{}; + + bool create(ID3D12Device* dev, const Pipelines& p, std::vector dispatched, bool draws) { + compute = std::move(dispatched); + graphics = draws; + const D3D12_HEAP_PROPERTIES def{D3D12_HEAP_TYPE_DEFAULT}, back{D3D12_HEAP_TYPE_READBACK}; + D3D12_RESOURCE_DESC td{}; + td.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + td.Width = td.Height = kExtent; + td.DepthOrArraySize = td.MipLevels = 1; + td.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + td.SampleDesc = {1, 0}; + td.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + CHECK(SUCCEEDED(dev->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &td, D3D12_RESOURCE_STATE_RENDER_TARGET, + nullptr, IID_PPV_ARGS(&target.p)))); + const auto bd = d3d12test::buffer_desc(4 * kWords, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + CHECK(SUCCEEDED(dev->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &bd, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&buffer.p)))); + UINT64 image_bytes = 0; + dev->GetCopyableFootprints(&td, 0, 1, 0, &foot, nullptr, nullptr, &image_bytes); + CHECK(image_bytes <= 4096); + const auto rd = d3d12test::buffer_desc(4096 + 4 * kWords); + CHECK(SUCCEEDED(dev->CreateCommittedResource(&back, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&readback.p)))); + const D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; + CHECK(SUCCEEDED(dev->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&rtvs.p)))); + const auto rtv = rtvs->GetCPUDescriptorHandleForHeapStart(); + dev->CreateRenderTargetView(target.p, nullptr, rtv); + const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT}; + CHECK(SUCCEEDED(dev->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p)))); + CHECK(SUCCEEDED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + CHECK(SUCCEEDED(dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + CHECK(SUCCEEDED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + const FLOAT clear[4] = {0, 0, 0, 0}; + list->ClearRenderTargetView(rtv, clear, 0, nullptr); + list->SetComputeRootSignature(p.root.p); + list->SetComputeRootUnorderedAccessView(0, buffer->GetGPUVirtualAddress()); + for (const unsigned n : compute) { + list->SetPipelineState(p.compute[n]); + list->SetComputeRoot32BitConstant(1, n, 0); + list->Dispatch(1, 1, 1); + } + if (graphics) { + list->SetGraphicsRootSignature(p.root.p); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + const D3D12_VIEWPORT vp{0, 0, float(kExtent), float(kExtent), 0, 1}; + list->RSSetViewports(1, &vp); + for (unsigned n = 0; n < kGraphics; ++n) { + const D3D12_RECT cell{LONG(2 * n), 0, LONG(2 * n + 2), 2}; + list->RSSetScissorRects(1, &cell); + list->SetPipelineState(p.graphics[n]); + list->DrawInstanced(3, 1, 0, 0); + } + } + const D3D12_RESOURCE_BARRIER to_source[2] = { + d3d12test::transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE), + d3d12test::transition(buffer.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)}; + list->ResourceBarrier(2, to_source); + D3D12_TEXTURE_COPY_LOCATION src{target.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + src.SubresourceIndex = 0; + D3D12_TEXTURE_COPY_LOCATION dst{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + dst.PlacedFootprint = foot; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + list->CopyBufferRegion(readback.p, 4096, buffer.p, 0, 4 * kWords); + const D3D12_RESOURCE_BARRIER back_again[2] = { + d3d12test::transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET), + d3d12test::transition(buffer.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)}; + list->ResourceBarrier(2, back_again); + CHECK(SUCCEEDED(list->Close())); + return true; + } + + ReplayResult submit() { + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + const ReplayResult result = rt::d3d12::last_execute_result(queue.p); + queue->Signal(fence.p, ++fence_value); + fence->SetEventOnCompletion(fence_value, nullptr); + return result; + } + + // What the shaders stored and drew; `dropped` is the compute program that was not built, whose word stays 0. The + // readback buffer is cleared, so stale bytes cannot pass. + bool right(int dropped = -1) { + void* mapped = nullptr; + CHECK(SUCCEEDED(readback->Map(0, nullptr, &mapped)) && mapped); + auto* bytes = static_cast(mapped); + bool ok = true; + std::uint32_t words[kWords]; + std::memcpy(words, bytes + 4096, sizeof words); + for (const unsigned n : compute) { + const std::uint32_t want = int(n) == dropped ? 0 : programs[n].run(n); + if (words[n] != want) { + std::fprintf(stderr, "compute program %u stored 0x%08x, not 0x%08x\n", n, words[n], want); + ok = false; + } + } + for (unsigned n = 0; graphics && n < kGraphics; ++n) + for (unsigned y = 0; y < 2; ++y) + for (unsigned x = 2 * n; x < 2 * n + 2; ++x) { + const auto* pixel = bytes + foot.Offset + y * foot.Footprint.RowPitch + 4 * x; + if (pixel[0] != n || pixel[1] != 255 - n || pixel[2] != 0 || pixel[3] != 255) { + std::fprintf(stderr, "graphics pipeline %u drew %u %u %u %u\n", n, pixel[0], pixel[1], pixel[2], + pixel[3]); + ok = false; + } + } + std::memset(bytes, 0xee, 4096 + 4 * kWords); + readback->Unmap(0, nullptr); + return ok; + } +}; + +std::vector all_compute() { + std::vector out; + for (unsigned n = 0; n < kCompute; ++n) out.push_back(n); + return out; +} + +std::uint64_t estimate(unsigned n) { return leonida::large_module_estimate(module_bytes[n]); } + +// How many of the large compute modules are in the driver at once, with five threads to compile them; 0: not known (the +// budget is read from the machine). +int expected_at_once() { + if (serial) return 1; + if (unlimited) return 5; + if (!fixed_budget) return 0; + // The first wave is the largest, in order, while they fit. + std::uint64_t sum = 0; + int count = 0; + for (unsigned n = kBig; n-- > 0 && sum + estimate(n) <= *fixed_budget; ++count) sum += estimate(n); + return std::clamp(count, 1, 5); +} + +// The large compute modules are held back in the driver until as many as may be are in, and no more come. +bool side_by_side(const Setup& setup) { + Ref dev; + CHECK(setup.device("4", dev)); + Pipelines pipelines; + Frame frame; + hooks.reset(); + CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, all_compute(), false)); + CHECK(hooks.creates() == 0); // nothing is compiled at creation + const int at_once = expected_at_once(); + hooks.closed = true; + ReplayResult result = ReplayResult::unsupported; + std::thread submitting([&] { result = frame.submit(); }); + const bool filled = hooks.wait_large(std::max(at_once, 1)); + // With a thread to spare, the small ones are compiled while the large ones wait (unlimited: every thread has a large one). + const bool small_ones = unlimited || !at_once || hooks.wait([] { return hooks.small_done == int(kSmall); }); + std::this_thread::sleep_for(300ms); + int held = 0; + { + std::lock_guard lock(hooks.mutex); + held = hooks.large_in; + } + hooks.open(); + submitting.join(); + CHECK(filled); + CHECK(!at_once || held == at_once); + CHECK(small_ones); + CHECK(result == ReplayResult::success && frame.right()); + CHECK(hooks.over == 0); + CHECK(hooks.creates() == kCompute); // each once + CHECK(!at_once || hooks.most_large <= at_once || unlimited); + CHECK(frame.submit() == ReplayResult::success && frame.right() && hooks.creates() == kCompute); + return true; +} + +// The same values whatever compiles them, without workers (each where prepare() meets it) and with them. +bool same_values(const Setup& setup) { + for (const char* threads : {"0", "16"}) { + Ref dev; + CHECK(setup.device(threads, dev)); + Pipelines pipelines; + Frame frame; + hooks.reset(); + CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, all_compute(), true)); + CHECK(frame.submit() == ReplayResult::success && frame.right()); + CHECK(hooks.over == 0); + CHECK(hooks.creates() == kCompute + kGraphics); + CHECK(*threads != '0' || hooks.most_large == 1); + } + return true; +} + +// A graphics pipeline whose estimate is past the budget (or the one at a time of serial) is in alone among the large ones, +// and the small ones are compiled beside it. +bool graphics_among_the_large(const Setup& setup) { + Ref dev; + CHECK(setup.device("4", dev)); + Pipelines pipelines; + Frame frame; + hooks.reset(); + CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, all_compute(), true)); + hooks.closed = true; + ReplayResult result = ReplayResult::unsupported; + std::thread submitting([&] { result = frame.submit(); }); + const bool one = hooks.wait_large(1); + const bool small_ones = unlimited || !expected_at_once() || + hooks.wait([] { return hooks.small_done == int(kSmall); }); + std::this_thread::sleep_for(300ms); + int held = 0; + bool first_is_graphics = false; + { + std::lock_guard lock(hooks.mutex); + held = hooks.large_in; + for (const Start& s : hooks.started) + if (s.large) { + first_is_graphics = s.program < 0; + break; + } + } + hooks.open(); + submitting.join(); + CHECK(one && small_ones); + if (budgeted && fixed_budget) CHECK(held == 1 && first_is_graphics); // the largest first + if (serial) CHECK(held == 1); + CHECK(result == ReplayResult::success && frame.right()); + CHECK(hooks.over == 0); + CHECK(hooks.creates() == kCompute + kGraphics); + return true; +} + +// Two large graphics pipelines and nothing else: one after the other, or both at once without a limit. +bool graphics_only(const Setup& setup) { + Ref dev; + CHECK(setup.device("4", dev)); + Pipelines pipelines; + Frame frame; + hooks.reset(); + CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, {}, true)); + hooks.closed = true; + ReplayResult result = ReplayResult::unsupported; + std::thread submitting([&] { result = frame.submit(); }); + const int at_once = unlimited ? 2 : 1; + const bool filled = hooks.wait_large(at_once); + std::this_thread::sleep_for(300ms); + int held = 0; + { + std::lock_guard lock(hooks.mutex); + held = hooks.large_in; + } + hooks.open(); + submitting.join(); + CHECK(filled); + if (!budgeted || fixed_budget) CHECK(held == at_once); + CHECK(result == ReplayResult::success && frame.right()); + CHECK(hooks.over == 0 && hooks.creates() == kGraphics); + return true; +} + +// The driver refuses one large compute module: its dispatch is dropped, the rest runs, and it is not tried again. Its place +// goes to the next. +bool refused(const Setup& setup) { + for (const char* threads : {"0", "4"}) { + Ref dev; + CHECK(setup.device(threads, dev)); + Pipelines pipelines; + Frame frame; + hooks.reset(); + CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, all_compute(), false)); + hooks.fail_large = 2; + CHECK(frame.submit() == ReplayResult::success); + int dropped = -1; + { + std::lock_guard lock(hooks.mutex); + int seen = 0; + for (const Start& s : hooks.started) + if (s.large && s.program >= 0 && seen++ == 2) dropped = s.program; + } + CHECK(dropped >= 0); + CHECK(frame.right(dropped)); + CHECK(hooks.creates() == kCompute); + CHECK(frame.submit() == ReplayResult::success && frame.right(dropped)); + CHECK(hooks.creates() == kCompute); + } + return true; +} + +// Two queues submit the same pipelines at once: each is compiled once, the budget is kept, and nobody waits for ever. +bool two_queues(const Setup& setup) { + Ref dev; + CHECK(setup.device("4", dev)); + Pipelines pipelines; + Frame frames[2]; + CHECK(pipelines.create(dev.p)); + auto backwards = all_compute(); + std::reverse(backwards.begin(), backwards.end()); + CHECK(frames[0].create(dev.p, pipelines, all_compute(), true)); + CHECK(frames[1].create(dev.p, pipelines, backwards, true)); + hooks.reset(); + ReplayResult results[2]{}; + std::thread threads[2]; + for (int i = 0; i < 2; ++i) threads[i] = std::thread([&, i] { results[i] = frames[i].submit(); }); + for (auto& t : threads) t.join(); + for (int i = 0; i < 2; ++i) CHECK(results[i] == ReplayResult::success && frames[i].right()); + CHECK(hooks.creates() == kCompute + kGraphics); + CHECK(hooks.over == 0); + return true; +} + +// The device's last references are released by the thread whose submission compiles, with large ones waiting for room. +bool device_destroyed(const Setup& setup) { + _putenv_s("LEONIDA_PIPELINE_CACHE_BYTES", "1"); // read the cache at teardown, write no file + Ref dev; + CHECK(setup.device("4", dev)); + auto pipelines = std::make_unique(); + auto frame = std::make_unique(); + hooks.reset(); + CHECK(pipelines->create(dev.p) && frame->create(dev.p, *pipelines, all_compute(), true)); + hooks.track = true; + hooks.closed = true; + ReplayResult result = ReplayResult::unsupported; + bool ok = false; + std::thread submitting([&] { + result = frame->submit(); + ok = frame->right(); + frame.reset(); + pipelines.reset(); + }); + const bool compiling = hooks.wait_large(1); + std::this_thread::sleep_for(100ms); + dev.reset(); + hooks.open(); + submitting.join(); + _putenv_s("LEONIDA_PIPELINE_CACHE_BYTES", "0"); + CHECK(compiling); + CHECK(result == ReplayResult::success && ok); + CHECK(hooks.cache_reads > 0); + CHECK(!hooks.cache_read_during_create); + CHECK(!hooks.cache_read_with_workers); + CHECK(hooks.live == 0); + return true; +} + +// One place for large compiles. The warm-up thread has it, and wants the next one after it; a submission that needs four +// others, one of which the warm-up thread waits to build, gets them all first, and builds that one itself. +bool warmup(const Setup& setup) { + Ref dev; + CHECK(setup.device("4", dev)); + Pipelines pipelines; + Frame frame; + hooks.reset(); + hooks.closed = true; + hooks.linger = 100ms; + CHECK(pipelines.create(dev.p)); + if (!hooks.wait_large(1)) { + hooks.open(); + CHECK(!"the warm-up thread compiles a large one"); + } + std::thread::id warm; + int first = -1; + { + std::lock_guard lock(hooks.mutex); + for (const Start& s : hooks.started) + if (s.large) warm = s.thread, first = s.program; + } + CHECK(first == 0); // their sizes rise with their numbers + const std::vector wanted = {4, 5, 3, 1}; // 1 is what the warm-up thread builds after 0 + CHECK(frame.create(dev.p, pipelines, wanted, false)); + const std::size_t before = hooks.creates(); + ReplayResult result = ReplayResult::unsupported; + std::thread submitting([&] { result = frame.submit(); }); + std::this_thread::sleep_for(500ms); + const bool waits = hooks.creates() == before; // the place is taken + hooks.open(); + submitting.join(); + const bool done = result == ReplayResult::success && frame.right(); + rt::d3d12::PipelineCompiler::instance().wait_idle(); // the warm-up thread builds the rest + std::vector started; + { + std::lock_guard lock(hooks.mutex); + started = hooks.started; + } + CHECK(waits); + CHECK(done); + CHECK(hooks.over == 0 && hooks.most_large == 1); + std::set once; + for (const Start& s : started) once.insert(s.program); + CHECK(started.size() == kCompute && once.size() == kCompute); // each once + std::erase_if(started, [](const Start& s) { return !s.large; }); + std::set built; + for (std::size_t i = 1; i <= wanted.size(); ++i) { + CHECK(started[i].thread != warm); // none of the warm-up's between two of the submission's + built.insert(started[i].program); + } + CHECK(built == std::set(wanted.begin(), wanted.end())); + for (std::size_t i = wanted.size() + 1; i < started.size(); ++i) CHECK(started[i].thread == warm); + return true; +} + +// The large ones that four threads create at once are held back in the driver until as many as may be are in. +bool eager(const Setup& setup) { + Ref dev; + CHECK(setup.device("4", dev)); + Pipelines pipelines; + Frame frame; + hooks.reset(); + hooks.closed = true; + bool created = false; + std::thread creating([&] { created = pipelines.create(dev.p, 4); }); + const bool one = hooks.wait_large(1); + std::this_thread::sleep_for(300ms); + int held = 0; + { + std::lock_guard lock(hooks.mutex); + held = hooks.large_in; + } + hooks.open(); + creating.join(); + CHECK(one && created); + CHECK(held == expected_at_once()); + CHECK(hooks.over == 0 && hooks.creates() == kCompute); + CHECK(frame.create(dev.p, pipelines, all_compute(), false)); + CHECK(frame.submit() == ReplayResult::success && frame.right()); + CHECK(hooks.creates() == kCompute); + return true; +} + +bool run(const Setup& setup, const std::string& scenario) { + if (scenario == "warmup") return warmup(setup); + if (scenario == "eager") return eager(setup); + return side_by_side(setup) && same_values(setup) && graphics_among_the_large(setup) && graphics_only(setup) && + refused(setup) && two_queues(setup) && device_destroyed(setup); +} + +} // namespace + +int main(int argc, char** argv) { + const std::string scenario = argc > 1 ? argv[1] : ""; + vktest::Device vk; + vk.request_buffer_device_address = true; + const auto status = vk.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + if (status != vktest::DeviceStatus::ready) return 1; + VkPhysicalDeviceProperties properties{}; + vk.instance_fn("vkGetPhysicalDeviceProperties")(vk.physical, &properties); + if (!vk.buffer_device_address || !vk.enabled.shaderInt64) { + std::printf("SKIP: the GPU lacks bufferDeviceAddress or shaderInt64\n"); + return 77; + } + if (properties.limits.maxPushConstantsSize < 144) { + std::printf("SKIP: maxPushConstantsSize %u, below the 144-byte block\n", properties.limits.maxPushConstantsSize); + return 77; + } + real_instance_proc = vk.instance_proc; + _putenv_s("LEONIDA_PIPELINE_CACHE_BYTES", "0"); // no session file in or out + if (scenario != "warmup") _putenv_s("LEONIDA_COMPUTE_WARMUP", "0"); // every compile is a submission's + const testfiles::ScratchDir library("leonida_big_compute_test"); + if (!write_library(library.path())) return 1; + if (!run({&vk, library.path().string()}, scenario)) return 1; + if (vk.validation_errors()) { + std::fprintf(stderr, "FAIL: %u validation errors\n", vk.validation_errors()); + return 1; + } + std::printf("d3d12_big_compute_test: passed on %s\n", properties.deviceName); + return 0; +} diff --git a/runtime/test/replay_pipeline_compiles_test.cpp b/runtime/test/replay_pipeline_compiles_test.cpp index 35b6057edb..167358f52a 100644 --- a/runtime/test/replay_pipeline_compiles_test.cpp +++ b/runtime/test/replay_pipeline_compiles_test.cpp @@ -2,13 +2,16 @@ // prepared twice, once with every pipeline built where prepare() meets it and once with them left to PipelineCompiles // and built on PipelineWorkers. Both have to give the same result, the same pipeline to every draw and dispatch, the same // commands dropped, and the same pipelines built, each once. Fixed cases, then random ones. Run a second time with -// LEONIDA_STRICT_REPLAY=1, where a dispatch without a pipeline fails its list. No GPU: pipelines and resources are fakes. +// LEONIDA_STRICT_REPLAY=1, where a dispatch without a pipeline fails its list. Also which large pipelines compile at once +// within a budget (PipelineCompiles::build). No GPU: pipelines and resources are fakes. +#include "../src/large_module_gate.h" #include "../src/pipeline_workers.h" #include "../src/vulkan_replay.h" #include #include #include +#include #include #include #include @@ -39,9 +42,10 @@ T handle(std::uintptr_t n) { constexpr ResourceId color_id = 1, depth_id = 2, arguments_id = 3; constexpr std::uint64_t bad_va = 0xbad0000; -// The large pipelines being built now, and how often there were two. +// The large pipelines being built now, and how often there were two, where they are to compile one after another. std::atomic large_now = 0; std::atomic large_together = 0; +std::atomic large_one_at_a_time = true; // What a pipeline state owns: its variants, built on demand under its own lock, and what was asked of it. struct Owner { @@ -60,7 +64,7 @@ struct Owner { if (failed && compute) return VK_NULL_HANDLE; // a refused compute pipeline is not tried again attempts.push_back(flags); if (large) { - if (++large_now > 1) ++large_together; + if (++large_now > 1 && large_one_at_a_time) ++large_together; const auto end = std::chrono::steady_clock::now() + std::chrono::microseconds(20); while (std::chrono::steady_clock::now() < end) std::this_thread::yield(); --large_now; @@ -84,6 +88,7 @@ struct PipelineSpec { bool fails = false; bool with_built = true; bool large = false; + std::uint64_t estimate = 0; bool skipped = false; // compute: never built, its dispatches are dropped bool bindless = false; // compute: needs a set 0, which these functions cannot bind bool async = false; // its null handle may be waiting for another worker: never left to PipelineCompiles @@ -114,6 +119,7 @@ struct Registry { ComputePipeline p{}; p.layout = handle(7); p.large = spec.large; + p.estimate = spec.estimate; p.async_build = spec.async; p.skipped = spec.skipped; if (spec.bindless) p.bindless_set = handle(6); @@ -138,6 +144,7 @@ struct Registry { } p.mesh = spec.mesh; p.large = spec.large; + p.estimate = spec.estimate; p.vertex_slots = spec.vertices ? 1 : 0; if (spec.rectangle) p.rectangle_variant_topology = 17; p.variant = [&owner](std::uint32_t flags) { return owner.build(flags); }; @@ -273,12 +280,12 @@ struct Outcome { std::multiset> built; std::size_t jobs = 0; std::size_t runs = 0; - std::size_t units = 0; // what run() was given: the large pipelines together are one + std::size_t units = 0; // what run() was given: the large pipelines together are one (no budget) }; // `workers` null: prepare() builds each pipeline itself, as without workers. Outcome prepare_all(const std::vector& lists, const std::vector& specs, - PipelineWorkers* workers) { + PipelineWorkers* workers, const std::function& budget = {}) { Registry registry(specs); ReplayFunctions vk = functions(registry); PipelineCompiles compiles; @@ -294,7 +301,8 @@ Outcome prepare_all(const std::vector& lists, const std::vectorrun(count, job); - }); + }, + budget); if (out.result == ReplayResult::success) for (std::size_t i = 0; i < lists.size(); ++i) { for (std::size_t c = 0; c < prepared[i].commands.size(); ++c) { @@ -312,10 +320,13 @@ Outcome prepare_all(const std::vector& lists, const std::vector& specs, - const std::vector>& commands, PipelineWorkers& workers) { + const std::vector>& commands, PipelineWorkers& workers, + const std::function& budget = {}) { const auto lists = record(commands); const Outcome serial = prepare_all(lists, specs, nullptr); - const Outcome together = prepare_all(lists, specs, &workers); + large_one_at_a_time = !budget; + const Outcome together = prepare_all(lists, specs, &workers, budget); + large_one_at_a_time = true; check(serial.result == together.result, name + ": another result"); check(serial.pipelines == together.pipelines, name + ": another pipeline for a draw or dispatch"); if (serial.result == ReplayResult::success) @@ -516,6 +527,7 @@ void random_submissions(PipelineWorkers& workers) { s.with_built = chance(90); s.async = chance(8); s.large = chance(15); + s.estimate = rng() % 12; s.bindless = chance(2); s.skipped = s.compute && chance(4); if (s.skipped) s.fails = s.pending = true; @@ -540,13 +552,278 @@ void random_submissions(PipelineWorkers& workers) { c.mesh = c.pipeline <= specs.size() && specs[c.pipeline - 1].mesh; list.push_back(c); } - succeeded += compare("random submission " + std::to_string(round), specs, commands, workers).result == - ReplayResult::success; + const std::uint64_t memory = rng() % 24; // 0: no budget + const auto budget = [memory] { return memory; }; + const bool limited = chance(50); + succeeded += compare("random submission " + std::to_string(round), specs, commands, workers, + limited ? std::function(budget) : std::function{}) + .result == ReplayResult::success; } check(succeeded > 1000 && succeeded < 2900, "the random submissions both succeed and fail: " + std::to_string(succeeded)); } +// ---- Large pipelines within a budget. ---- + +// Pipelines that note the order they start in. One with `hold` does not end before `release` is called. +struct Shop { + struct Item { + Shop* shop = nullptr; + ComputePipeline pipeline{}; + std::string name; + bool hold = false; + }; + std::mutex mutex; + std::condition_variable changed; + std::vector started; + std::vector> items; + bool released = false; + int large_in = 0, most_large_in = 0; + LargeModuleGate* gate = nullptr; // set: a large one takes its place there, as in the layer + + ComputePipeline& add(const std::string& name, std::uint64_t estimate, bool large, bool hold = false) { + auto& item = *items.emplace_back(std::make_unique()); + item.shop = this; + item.name = name; + item.hold = hold; + item.pipeline.large = large; + item.pipeline.estimate = estimate; + item.pipeline.build_context = &item; + item.pipeline.build = [](void* context) { + auto& i = *static_cast(context); + Shop& shop = *i.shop; + LargeModuleGate::Ticket place; + if (shop.gate && i.pipeline.large) place = LargeModuleGate::Ticket(*shop.gate, i.pipeline.estimate); + std::unique_lock lock(shop.mutex); + shop.started.push_back(i.name); + if (i.pipeline.large) shop.most_large_in = std::max(shop.most_large_in, ++shop.large_in); + shop.changed.notify_all(); + if (i.hold) shop.changed.wait_for(lock, std::chrono::seconds(10), [&] { return shop.released; }); + if (i.pipeline.large) --shop.large_in; + return handle(std::uintptr_t(&i) | 1); + }; + return item.pipeline; + } + void fill(PipelineCompiles& compiles) { + for (auto& item : items) compiles.add(item->pipeline, PipelineCompiles::User::dispatch); + } + // Whether `count` have started, within 10 s. + bool wait_started(std::size_t count) { + std::unique_lock lock(mutex); + return changed.wait_for(lock, std::chrono::seconds(10), [&] { return started.size() >= count; }); + } + void release() { + std::lock_guard lock(mutex); + released = true; + changed.notify_all(); + } +}; + +// On `threads` threads, which take the jobs in order. +void on_threads(unsigned threads, std::size_t count, const std::function& job) { + std::atomic next = 0; + std::vector workers; + for (unsigned t = 0; t < threads; ++t) + workers.emplace_back([&] { + for (std::size_t i; (i = next++) < count;) job(i); + }); + for (auto& w : workers) w.join(); +} + +using Names = std::vector; + +// The order and the jobs of the run, on one thread: the largest first, then the others, and the budget read once. +void budget_order() { + struct Case { + std::vector large; + std::uint64_t budget; + std::size_t lanes; + Names order; // of the large ones + }; + for (const Case& c : {Case{{5, 2, 3, 2, 1}, 5, 3, {"5", "3", "2", "2", "1"}}, + Case{{5, 2, 3, 2, 1}, 4, 2, {"5", "3", "2", "2", "1"}}, + Case{{5, 2, 3, 2, 1}, 0, 1, {"5", "2", "3", "2", "1"}}, // no budget: in the order they came + Case{{5, 2, 3, 2, 1}, 100, 5, {"5", "3", "2", "2", "1"}}, + Case{{9}, 5, 1, {"9"}}, // more than the budget: one, alone + Case{{9, 9}, 5, 1, {"9", "9"}}, + Case{{9, 1}, 5, 1, {"9", "1"}}, + Case{{4, 4}, 8, 2, {"4", "4"}}}) { + Shop shop; + for (const auto size : c.large) shop.add(std::to_string(size), size, true); + for (int i = 0; i < 3; ++i) shop.add("s" + std::to_string(i), 0, false); + PipelineCompiles compiles; + shop.fill(compiles); + std::size_t units = 0; + unsigned reads = 0; + compiles.build([&](std::size_t count, const std::function& job) { + units = count; + for (std::size_t i = 0; i < count; ++i) job(i); + }, [&] { ++reads; return c.budget; }); + Names want = c.order; + for (int i = 0; i < 3; ++i) want.push_back("s" + std::to_string(i)); + const std::string name = "budget " + std::to_string(c.budget) + " of " + std::to_string(c.large.size()); + check(shop.started == want, name + ": another order"); + check(units == c.lanes + 3, name + ": " + std::to_string(units) + " jobs, not " + std::to_string(c.lanes + 3)); + check(reads == 1, name + ": the budget read " + std::to_string(reads) + " times"); + for (std::size_t i = 0; i < shop.items.size(); ++i) + check(compiles.built(PipelineCompiles::Ticket(i + 1)) != VK_NULL_HANDLE, name + ": not built"); + } + // Without a large pipeline the budget is not read, and the jobs are the pipelines. + Shop shop; + for (int i = 0; i < 3; ++i) shop.add("s" + std::to_string(i), 0, false); + PipelineCompiles compiles; + shop.fill(compiles); + std::size_t units = 0; + unsigned reads = 0; + compiles.build([&](std::size_t count, const std::function& job) { + units = count; + for (std::size_t i = 0; i < count; ++i) job(i); + }, [&] { ++reads; return 100u; }); + check(units == 3 && reads == 0, "the budget read for pipelines that are not large"); +} + +// A large one that does not fit beside the one in is not waited for while others are left: they come first. +void budget_others_first() { + Shop shop; + shop.add("8", 8, true, true); + shop.add("4a", 4, true); + shop.add("4b", 4, true); + for (int i = 0; i < 3; ++i) shop.add("s" + std::to_string(i), 0, false); + PipelineCompiles compiles; + shop.fill(compiles); + std::thread building([&] { + compiles.build([&](std::size_t count, const std::function& job) { + check(count == 2 + 3, "two lanes: the two of 4 fit 8 together"); + on_threads(2, count, job); + }, [] { return 8; }); + }); + const bool all = shop.wait_started(6); // "8" is held: the other lane does the rest + Names seen; + { + std::lock_guard lock(shop.mutex); + seen = shop.started; + } + shop.release(); + building.join(); + check(all && seen.size() == 6 && seen[0] == "8", "the large one first"); + check(all && std::set(seen.begin() + 1, seen.begin() + 4) == std::set{"s0", "s1", "s2"}, + "the others before the large ones that do not fit"); + check(all && seen[4] == "4a" && seen[5] == "4b", "then the next large ones"); +} + +// Those that fit together start together, before the others. +void budget_fits_together() { + Shop shop; + shop.add("3", 3, true, true); + shop.add("5", 5, true, true); + for (int i = 0; i < 2; ++i) shop.add("s" + std::to_string(i), 0, false); + PipelineCompiles compiles; + shop.fill(compiles); + std::thread building([&] { + compiles.build([&](std::size_t count, const std::function& job) { on_threads(2, count, job); }, + [] { return 8; }); + }); + const bool both = shop.wait_started(2); + Names seen; + { + std::lock_guard lock(shop.mutex); + seen = shop.started; + } + shop.release(); + building.join(); + check(both && std::set(seen.begin(), seen.begin() + 2) == std::set{"3", "5"}, + "two that fit the budget are in together"); + check(shop.most_large_in == 2, "two that fit the budget at once"); +} + +// The room that a large one leaves is the next large one's, before the others. +void budget_room_is_given_back() { + Shop shop; + shop.add("5", 5, true, true); + for (const char* name : {"3a", "3b", "3c"}) shop.add(name, 3, true); + for (int i = 0; i < 3; ++i) shop.add("s" + std::to_string(i), 0, false); + PipelineCompiles compiles; + shop.fill(compiles); + std::thread building([&] { + compiles.build([&](std::size_t count, const std::function& job) { + check(count == 2 + 3, "two lanes: two of 3 fit 8, three do not"); + on_threads(2, count, job); + }, [] { return 8; }); + }); + const bool all = shop.wait_started(7); // "5" is held: the other lane has room for one of 3 at a time + Names seen; + { + std::lock_guard lock(shop.mutex); + seen = shop.started; + } + shop.release(); + building.join(); + check(all && Names(seen.begin(), seen.begin() + 4) == Names{"5", "3a", "3b", "3c"}, + "a large one does not leave its room"); +} + +// Graphics and compute pipelines share the budget: what each is expected to take counts alike. +void budget_graphics_and_compute() { + Shop shop; + shop.add("3", 3, true); + shop.add("4", 4, true); + GraphicsPipeline graphics{}; + graphics.large = true; + graphics.estimate = 5; + graphics.variant = [&](std::uint32_t) { + std::lock_guard lock(shop.mutex); + shop.started.push_back("5"); + return handle(5); + }; + PipelineCompiles compiles; + shop.fill(compiles); + compiles.add(graphics, 0); + std::size_t units = 0; + compiles.build([&](std::size_t count, const std::function& job) { + units = count; + for (std::size_t i = 0; i < count; ++i) job(i); + }, [] { return 8; }); + check(shop.started == Names{"5", "4", "3"}, "the largest first, graphics or compute"); + check(units == 2, "3 and 4 fit 8, and 5 does not beside them"); +} + +// The lanes are no more than could be in: a thread is not kept waiting for room there is none of. +void budget_lanes_are_bounded() { + Shop shop; + for (int i = 0; i < 3; ++i) shop.add("5" + std::to_string(i), 5, true); + for (int i = 0; i < 6; ++i) shop.add("s" + std::to_string(i), 0, false); + PipelineCompiles compiles; + shop.fill(compiles); + compiles.build([&](std::size_t count, const std::function& job) { + check(count == 2 + 6, "10 bytes hold two of 5"); + on_threads(4, count, job); + }, [] { return 10; }); + check(shop.started.size() == 9 && shop.most_large_in <= 2, "no more than two large ones at once"); +} + +// Every one of them is built once, with the gate of the runtime holding what does not fit, whatever sizes and budget. +void budget_random(PipelineWorkers& workers) { + std::mt19937 rng(20251127); + for (int round = 0; round < 300; ++round) { + Shop shop; + const std::uint64_t budget = rng() % 20; + LargeModuleGate gate([budget] { return budget; }); + shop.gate = &gate; + const unsigned large = rng() % 10, others = rng() % 10; + for (unsigned i = 0; i < large; ++i) shop.add("l" + std::to_string(i), rng() % 12, true); + for (unsigned i = 0; i < others; ++i) shop.add("s" + std::to_string(i), 0, false); + PipelineCompiles compiles; + shop.fill(compiles); + compiles.build([&](std::size_t count, const std::function& job) { workers.run(count, job); }, + [budget] { return budget; }); + Names names = shop.started; + std::sort(names.begin(), names.end()); + check(std::adjacent_find(names.begin(), names.end()) == names.end() && names.size() == large + others, + "random budget " + std::to_string(round) + ": a pipeline built twice or not at all"); + check(gate.inflight() == 0, "random budget " + std::to_string(round) + ": a place not given back"); + } +} + } // namespace int main() { @@ -556,7 +833,14 @@ int main() { if (threads) many(workers); reused_lists(workers); random_submissions(workers); + budget_random(workers); } + budget_order(); + budget_others_first(); + budget_fits_together(); + budget_room_is_given_back(); + budget_graphics_and_compute(); + budget_lanes_are_bounded(); check(large_together == 0, "two large pipelines were built at once"); if (failures) return 1; std::printf("replay_pipeline_compiles_test: passed\n"); From 0bf7ef80667e0d7e62e4b22c78c7a713600f5edc Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:59:36 +0100 Subject: [PATCH 3/3] runtime: a large compile that fits may pass one that does not, within a bound (RT-BIG-COMPUTE-BUDGET) --- docs/d3d12_vulkan.md | 10 ++- runtime/src/large_module_gate.h | 46 +++++++--- runtime/test/big_compile_gate_test.cpp | 116 +++++++++++++++++++++++-- 3 files changed, 149 insertions(+), 23 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index e937d6699c..d80aadabed 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2429,10 +2429,12 @@ Pipeline creation: byte of SPIR-V) fit a budget: three quarters of the smaller of the free RAM and the room under the commit limit, read again whenever a place at the gate (`runtime/src/large_module_gate.h`, one for the process) is given or returned. One always gets in when none is, so a pipeline larger than the budget compiles alone. An estimate counts in full until - the compile ends, although the driver has taken part of it by then. They get in in the order they came, the ones a - submission waits for (and those of `LEONIDA_ASYNC_PIPELINES`) before the warm-up's, which take a quarter of the - budget at most and none while a submission that has large ones is compiling on its workers. A thread that waits for - its place holds no PSO's lock, and one that has a place waits for none. `PipelineCompiles::build` gives a submission + the compile ends, although the driver has taken part of it by then. They get in in the order they came; while the + 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 + budget together with it, so that a stream of small ones does not keep it out. The ones a submission waits for (and + those of `LEONIDA_ASYNC_PIPELINES`) go before the warm-up's, which take a quarter of the budget at most and none while + a submission that has large ones is compiling on its workers. A thread that waits for its place holds no PSO's lock, + and one that has a place waits for none. `PipelineCompiles::build` gives a submission as many jobs for large ones as its smallest could be in at once, largest first; where the next one does not fit, the job compiles small ones in the meantime. `LEONIDA_SERIAL_BIG_COMPILES=1` compiles them one after another instead, as before there was a budget, `=0` has no limit, `LEONIDA_BIG_COMPILE_BUDGET_MB` fixes the budget. Measured with diff --git a/runtime/src/large_module_gate.h b/runtime/src/large_module_gate.h index 2185f20cf0..f66420bc24 100644 --- a/runtime/src/large_module_gate.h +++ b/runtime/src/large_module_gate.h @@ -153,10 +153,13 @@ inline void release_free_memory() { // when none is, so a module bigger than the whole budget still compiles (alone among the large ones). // // The second constructor is the runtime's: the budget is read again whenever a place is given or returned, and the -// modules get in in the order they came, those a submission waits for (demand) before the others (speculative). A -// speculative one gets in only while no demand waits and no submission has a Demand, and only within a quarter of the -// budget, so that a demand finds the rest free. An estimate counts in full until its module leaves, although the driver -// has allocated part of it by then and the budget is that much smaller: what is in has not taken all it is going to. +// modules get in in the order they came, those a submission waits for (demand) before the others (speculative). While the +// 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 +// 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, +// however many come after it, and one larger than the budget is not passed. A speculative one gets in only while no demand +// waits and no submission has a Demand, and only within a quarter of the budget, so that a demand finds the rest free. An +// estimate counts in full until its module leaves, although the driver has allocated part of it by then and the budget is +// that much smaller: what is in has not taken all it is going to. class LargeModuleGate { public: enum class Work { demand, speculative }; @@ -168,19 +171,19 @@ class LargeModuleGate { bool admits(uint64_t estimate) const { std::lock_guard g(mu_); - return admits_locked(estimate, Work::demand); + return admits_locked(estimate, budget()); } void enter(uint64_t estimate, Work work = Work::demand) { std::unique_lock l(mu_); if (!read_budget_) { - cv_.wait(l, [&] { return admits_locked(estimate, work); }); + cv_.wait(l, [&] { return admits_locked(estimate, limit_for(work)); }); } else { auto& queue = waiting_[work == Work::demand ? 0 : 1]; - const auto me = queue.insert(queue.end(), 0); + const auto me = queue.insert(queue.end(), Waiter{estimate}); cv_.wait(l, [&] { - return queue.begin() == me && (work == Work::demand || (waiting_[0].empty() && !demanded_)) && - admits_locked(estimate, work); + return (work == Work::demand || (waiting_[0].empty() && !demanded_)) && next_locked(work) == &*me; }); + if (me != queue.begin()) queue.front().passed += estimate; queue.erase(me); } used_ += estimate; @@ -255,10 +258,25 @@ class LargeModuleGate { }; private: - bool admits_locked(uint64_t estimate, Work work) const { - if (inflight_ == 0) return true; - const uint64_t limit = work == Work::demand ? budget() : budget() / 4; - return inflight_ < max_inflight_ && used_ + estimate <= limit; + struct Waiter { + uint64_t estimate; + uint64_t passed = 0; // the estimates of those that have passed it while it was the first in line + }; + + uint64_t limit_for(Work work) const { return work == Work::demand ? budget() : budget() / 4; } + bool admits_locked(uint64_t estimate, uint64_t limit) const { + return inflight_ == 0 || (inflight_ < max_inflight_ && used_ + estimate <= limit); + } + // The one in line that gets in now, if any: the first, or else the first that fits and may pass it. + const Waiter* next_locked(Work work) const { + const auto& queue = waiting_[work == Work::demand ? 0 : 1]; + const uint64_t limit = limit_for(work); + for (const Waiter& w : queue) { + const Waiter& first = queue.front(); + if (&w != &first && first.passed + w.estimate + first.estimate > limit) continue; + if (admits_locked(w.estimate, limit)) return &w; + } + return nullptr; } const uint64_t budget_; @@ -266,7 +284,7 @@ class LargeModuleGate { const std::function read_budget_; mutable std::mutex mu_; std::condition_variable cv_; - std::list waiting_[2]; // demand, speculative: one entry for each thread in enter(), in the order they came + std::list waiting_[2]; // demand, speculative: one for each thread in enter(), in the order they came uint64_t used_ = 0; unsigned inflight_ = 0; unsigned demanded_ = 0; // the Demands diff --git a/runtime/test/big_compile_gate_test.cpp b/runtime/test/big_compile_gate_test.cpp index 5756f99abd..a012ac9f9d 100644 --- a/runtime/test/big_compile_gate_test.cpp +++ b/runtime/test/big_compile_gate_test.cpp @@ -145,22 +145,124 @@ void many_threads() { } } -// Those that wait get in in the order they came: what came later and is small does not overtake the big one before it. +// 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 +// its room when those that were in before it leave, whatever passed it. void order() { auto gate = fixed(10); Entrant first(gate, 8); CHECK(in(first)); Entrant big(gate, 9); CHECK(waiting(gate, Work::demand, 1)); - Entrant little(gate, 1); + Entrant in_the_way(gate, 2); // it fits beside the first, and not beside the big one CHECK(waiting(gate, Work::demand, 2)); - CHECK(stays_out(big)); - CHECK(stays_out(little)); // it would fit beside the first + Entrant little(gate, 1); + CHECK(in(little)); + Entrant next(gate, 1); // beside the big one there is room for one of these + CHECK(waiting(gate, Work::demand, 3)); + CHECK(stays_out(big) && stays_out(in_the_way) && stays_out(next)); + little.leave(); + little.join(); + CHECK(stays_out(big) && stays_out(in_the_way) && stays_out(next)); // nor when the one that passed has left first.leave(); CHECK(in(big)); - CHECK(in(little)); // the place that the big one leaves free is the next one's + CHECK(in(next)); // the first in line is now in_the_way, which it can pass + CHECK(stays_out(in_the_way)); + big.leave(); + CHECK(in(in_the_way)); + in_the_way.leave(); + next.leave(); +} + +// What passes the first in line is bounded: a stream of small ones does not keep it out. +void a_stream_of_small_ones_does_not_keep_out() { + auto gate = fixed(100); + Entrant first(gate, 50); + CHECK(in(first)); + Entrant big(gate, 70); + CHECK(waiting(gate, Work::demand, 1)); + std::vector> stream; + for (int i = 0; i < 3; ++i) { // 30 beside the big one's 70, one after another + stream.push_back(std::make_unique(gate, 10)); + CHECK(in(*stream.back())); + if (i < 2) { // one of them stays in + stream.back()->leave(); + stream.back()->join(); + } + } + Entrant more(gate, 10); + CHECK(waiting(gate, Work::demand, 2)); + CHECK(stays_out(more)); // it fits (70 of 100 with the rest), but the first in line has been passed enough + first.leave(); + CHECK(in(big)); // 10 of the stream and 70 + CHECK(in(more)); big.leave(); + more.leave(); + stream.back()->leave(); +} + +// Of those that can pass, the one that came first does. +void those_that_pass_keep_their_order() { + for (int round = 0; round < 10; ++round) { + auto gate = fixed(20); + Entrant first(gate, 15), other(gate, 5); + CHECK(in(first) && in(other)); + Entrant big(gate, 12); + CHECK(waiting(gate, Work::demand, 1)); + Entrant a(gate, 4); + CHECK(waiting(gate, Work::demand, 2)); + Entrant b(gate, 4); + CHECK(waiting(gate, Work::demand, 3)); + other.leave(); + CHECK(in(a)); + CHECK(stays_out(b) && stays_out(big)); // 19 of 20 + first.leave(); + CHECK(in(big) && in(b)); + big.leave(); + a.leave(); + b.leave(); + } +} + +// One that needs the machine for itself is not passed: what got in beside it would keep it out. +void larger_than_the_budget_is_not_passed() { + auto gate = fixed(10); + Entrant first(gate, 5); + CHECK(in(first)); + Entrant alone(gate, 25); + CHECK(waiting(gate, Work::demand, 1)); + Entrant little(gate, 1); + CHECK(waiting(gate, Work::demand, 2)); + CHECK(stays_out(little)); + first.leave(); + CHECK(in(alone)); + CHECK(stays_out(little)); + alone.leave(); + CHECK(in(little)); + little.leave(); +} + +// The same for the speculative ones, within their quarter. +void speculative_ones_pass_each_other() { + auto gate = fixed(100); + Entrant first(gate, 20, Work::speculative); + CHECK(in(first)); + Entrant big(gate, 18, Work::speculative); + CHECK(waiting(gate, Work::speculative, 1)); + Entrant little(gate, 5, Work::speculative); + CHECK(in(little)); // 25 of 25, and 23 with the big one + Entrant next(gate, 1, Work::speculative); + CHECK(waiting(gate, Work::speculative, 2)); little.leave(); + little.join(); + CHECK(in(next)); // 21 of 25, and 24 of what may pass + Entrant over(gate, 2, Work::speculative); + CHECK(waiting(gate, Work::speculative, 2)); + CHECK(stays_out(over) && stays_out(big)); // it would be 26 + first.leave(); + CHECK(in(big) && in(over)); + big.leave(); + next.leave(); + over.leave(); } // The first in the queue leaves it, and the next one, which fits as well, gets in at once and not when something leaves. @@ -409,6 +511,10 @@ int main() { bound_and_one_always(); many_threads(); order(); + a_stream_of_small_ones_does_not_keep_out(); + those_that_pass_keep_their_order(); + larger_than_the_budget_is_not_passed(); + speculative_ones_pass_each_other(); one_admission_wakes_the_next(); leaving_wakes_all_that_fit(); demand_before_speculative();