upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src
diff options
context:
space:
mode:
authorTheGeogeo <57634077+TheGeogeo@users.noreply.github.com>2026-11-25 13:42:21 +0100
committerTheGeogeo <57634077+TheGeogeo@users.noreply.github.com>2026-11-25 15:11:10 +0100
commit4aa21d1a83f4a7954ca79111fffb0d4aba674bf2 (patch)
tree054c5713374e505eef12b3ef9a202adae6027dcd /runtime/src
parent71a769d7d85208f86c6e2e50263aca7df1becce9 (diff)
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.
Diffstat (limited to 'runtime/src')
-rw-r--r--runtime/src/large_module_gate.h275
1 files changed, 275 insertions, 0 deletions
diff --git a/runtime/src/large_module_gate.h b/runtime/src/large_module_gate.h
new file mode 100644
index 000000000..2185f20cf
--- /dev/null
+++ b/runtime/src/large_module_gate.h
@@ -0,0 +1,275 @@
1// How many large SPIR-V modules vk_pipeline_check and the runtime let into the driver at once, by a memory budget.
2//
3// Measured on RADV GFX1201 (Mesa 25.3.6) with the Mesa shader cache off: a 5.7 MB translated ray-tracing compute
4// module peaks at 1.96 GB of process memory compiling alone (~330 bytes per SPIR-V byte), a 0.36 MB one at 94 MB.
5// Compiling the large ones strictly one at a time left the other threads idle: 40 modules (27 over 4 MiB) on 6
6// threads took 308 s exclusively and 75 s in parallel, 7.0 GB and 8.7 GB peak. kBytesPerSpirvByte keeps a margin
7// over the measurement. The NVIDIA 621.24 driver (RTX 3080) took 85 to 131 bytes per SPIR-V byte for synthetic compute
8// modules of 128 KiB to 4 MiB (docs/d3d12_vulkan.md, "Large pipelines").
9//
10// The process grew past one module's peak even one at a time because glibc keeps freed memory in per-thread arenas
11// (6 threads: 6.2 GB; MALLOC_ARENA_MAX=1: 2.1 GB, same modules). release_free_memory() hands it back after each
12// large module.
13#pragma once
14
15#include <algorithm>
16#include <condition_variable>
17#include <cstddef>
18#include <cstdint>
19#include <cstdio>
20#include <functional>
21#include <list>
22#include <mutex>
23#include <optional>
24#include <string>
25#include <utility>
26
27#ifdef _WIN32
28#ifndef NOMINMAX
29#define NOMINMAX
30#endif
31#include <windows.h>
32#endif
33#if defined(__GLIBC__)
34#include <malloc.h>
35#endif
36
37namespace leonida {
38
39inline constexpr uint64_t kBytesPerSpirvByte = 512;
40
41inline uint64_t large_module_estimate(uint64_t spirv_bytes) { return spirv_bytes * kBytesPerSpirvByte; }
42
43#if defined(__linux__)
44// The first unsigned number in a file ("max" and unreadable files give no value).
45inline bool read_u64_file(const std::string& path, uint64_t& value) {
46 std::FILE* f = std::fopen(path.c_str(), "r");
47 if (!f) return false;
48 unsigned long long v = 0;
49 const bool ok = std::fscanf(f, "%llu", &v) == 1;
50 std::fclose(f);
51 value = v;
52 return ok;
53}
54
55// The room left under the cgroup v2 memory.max of this process and of every cgroup above it (a container or
56// systemd-run -p MemoryMax=...), or UINT64_MAX when none sets a limit. cgroup_root is a parameter for the tests.
57inline uint64_t cgroup_memory_room(const std::string& self_cgroup_file = "/proc/self/cgroup",
58 const std::string& cgroup_root = "/sys/fs/cgroup") {
59 std::FILE* f = std::fopen(self_cgroup_file.c_str(), "r");
60 if (!f) return UINT64_MAX;
61 char line[4096];
62 std::string rel;
63 while (std::fgets(line, sizeof(line), f)) {
64 std::string l(line);
65 if (l.rfind("0::", 0) == 0) { // the cgroup v2 line
66 rel = l.substr(3);
67 while (!rel.empty() && (rel.back() == '\n' || rel.back() == '\r')) rel.pop_back();
68 break;
69 }
70 }
71 std::fclose(f);
72 uint64_t room = UINT64_MAX;
73 for (std::string dir = rel; !dir.empty();) {
74 // In a cgroup namespace, "/" can be a constrained cgroup mounted as the visible root.
75 const std::string base = dir == "/" ? cgroup_root : cgroup_root + dir;
76 uint64_t max = 0, current = 0;
77 if (read_u64_file(base + "/memory.max", max) && read_u64_file(base + "/memory.current", current))
78 room = std::min(room, max > current ? max - current : 0);
79 const auto slash = dir.find_last_of('/');
80 if (dir == "/" || slash == std::string::npos) break;
81 dir.resize(slash == 0 ? 1 : slash);
82 }
83 return room;
84}
85#endif
86
87// Memory the OS could give this process now, or 0 when it can't tell (then the caller keeps the old exclusive gate).
88inline uint64_t available_memory_bytes() {
89#ifdef _WIN32
90 MEMORYSTATUSEX status{};
91 status.dwLength = sizeof(status);
92 return GlobalMemoryStatusEx(&status) ? uint64_t(status.ullAvailPhys) : 0;
93#elif defined(__linux__)
94 std::FILE* f = std::fopen("/proc/meminfo", "r");
95 if (!f) return 0;
96 char line[256];
97 unsigned long long kb = 0;
98 bool found = false;
99 while (std::fgets(line, sizeof(line), f))
100 if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) { found = true; break; }
101 std::fclose(f);
102 if (!found) return 0;
103 const uint64_t room = cgroup_memory_room();
104 return std::max<uint64_t>(1, std::min(uint64_t(kb) * 1024, room)); // 0 would mean "unknown"
105#else
106 return 0;
107#endif
108}
109
110// What large compiles may use of the free RAM and of the room under the commit limit: three quarters of the smaller. (On
111// Windows an allocation that the limit has no room for fails, whatever RAM is free.)
112inline uint64_t large_compile_share(uint64_t free_ram, uint64_t commit_room) {
113 return std::min(free_ram, commit_room) / 4 * 3;
114}
115
116// The same of the memory that is free at this moment. 0 when it is unknown: then they compile one at a time.
117inline uint64_t large_compile_budget_bytes() {
118#ifdef _WIN32
119 MEMORYSTATUSEX status{};
120 status.dwLength = sizeof(status);
121 if (!GlobalMemoryStatusEx(&status)) return 0;
122 return large_compile_share(status.ullAvailPhys, status.ullAvailPageFile);
123#else
124 return large_compile_share(available_memory_bytes(), UINT64_MAX);
125#endif
126}
127
128// LEONIDA_BIG_COMPILE_BUDGET_MB: a fixed budget in MiB instead of the share of the free memory (0: one at a time). Unset
129// or empty, and text that is not a number: none. `valid` is false for the latter.
130struct LargeCompileBudget {
131 std::optional<uint64_t> fixed{};
132 bool valid = true;
133};
134
135inline LargeCompileBudget large_compile_budget(const char* text) {
136 if (!text || !*text) return {};
137 uint64_t mib = 0;
138 for (const char* c = text; *c; ++c) {
139 if (*c < '0' || *c > '9') return {std::nullopt, false};
140 mib = std::min<uint64_t>(mib * 10 + uint64_t(*c - '0'), UINT64_MAX >> 20);
141 }
142 return {mib << 20, true};
143}
144
145// Return memory freed by the driver's compiler to the OS (glibc keeps it in the arena of the thread that freed it).
146inline void release_free_memory() {
147#if defined(__GLIBC__)
148 malloc_trim(0);
149#endif
150}
151
152// Lets large modules in while their estimates fit the budget and fewer than max_inflight are in. One always gets in
153// when none is, so a module bigger than the whole budget still compiles (alone among the large ones).
154//
155// The second constructor is the runtime's: the budget is read again whenever a place is given or returned, and the
156// modules get in in the order they came, those a submission waits for (demand) before the others (speculative). A
157// speculative one gets in only while no demand waits and no submission has a Demand, and only within a quarter of the
158// budget, so that a demand finds the rest free. An estimate counts in full until its module leaves, although the driver
159// 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.
160class LargeModuleGate {
161public:
162 enum class Work { demand, speculative };
163
164 LargeModuleGate(uint64_t budget, unsigned max_inflight)
165 : budget_(budget), max_inflight_(max_inflight ? max_inflight : 1) {}
166 explicit LargeModuleGate(std::function<uint64_t()> budget)
167 : budget_(0), max_inflight_(UINT32_MAX), read_budget_(std::move(budget)) {}
168
169 bool admits(uint64_t estimate) const {
170 std::lock_guard<std::mutex> g(mu_);
171 return admits_locked(estimate, Work::demand);
172 }
173 void enter(uint64_t estimate, Work work = Work::demand) {
174 std::unique_lock<std::mutex> l(mu_);
175 if (!read_budget_) {
176 cv_.wait(l, [&] { return admits_locked(estimate, work); });
177 } else {
178 auto& queue = waiting_[work == Work::demand ? 0 : 1];
179 const auto me = queue.insert(queue.end(), 0);
180 cv_.wait(l, [&] {
181 return queue.begin() == me && (work == Work::demand || (waiting_[0].empty() && !demanded_)) &&
182 admits_locked(estimate, work);
183 });
184 queue.erase(me);
185 }
186 used_ += estimate;
187 ++inflight_;
188 if (!waiting_[0].empty() || !waiting_[1].empty()) cv_.notify_all(); // the next in the queue may fit as well
189 }
190 void leave(uint64_t estimate) {
191 {
192 std::lock_guard<std::mutex> g(mu_);
193 used_ -= estimate;
194 --inflight_;
195 }
196 cv_.notify_all();
197 }
198 unsigned inflight() const {
199 std::lock_guard<std::mutex> g(mu_);
200 return inflight_;
201 }
202 size_t waiting(Work work) const { // in order: the threads in enter(), with a budget that is read
203 std::lock_guard<std::mutex> g(mu_);
204 return waiting_[work == Work::demand ? 0 : 1].size();
205 }
206 uint64_t budget() const { return read_budget_ ? read_budget_() : budget_; }
207 unsigned max_inflight() const { return max_inflight_; }
208
209 // A submission that has large modules to build: until it ends, the places that its modules leave between one and the
210 // next are not taken by speculative ones.
211 class Demand {
212 public:
213 explicit Demand(LargeModuleGate& gate) : gate_(gate) {
214 std::lock_guard<std::mutex> g(gate_.mu_);
215 ++gate_.demanded_;
216 }
217 ~Demand() {
218 {
219 std::lock_guard<std::mutex> g(gate_.mu_);
220 --gate_.demanded_;
221 }
222 gate_.cv_.notify_all();
223 }
224 Demand(const Demand&) = delete;
225 Demand& operator=(const Demand&) = delete;
226
227 private:
228 LargeModuleGate& gate_;
229 };
230
231 // Holds a place from construction until destruction (or release()), then hands freed memory back.
232 class Ticket {
233 public:
234 Ticket() = default;
235 Ticket(LargeModuleGate& gate, uint64_t estimate, Work work = Work::demand) : gate_(&gate), estimate_(estimate) {
236 gate.enter(estimate, work);
237 }
238 Ticket(Ticket&& o) noexcept : gate_(o.gate_), estimate_(o.estimate_) { o.gate_ = nullptr; }
239 Ticket& operator=(Ticket&& o) noexcept {
240 if (this != &o) { release(); gate_ = o.gate_; estimate_ = o.estimate_; o.gate_ = nullptr; }
241 return *this;
242 }
243 Ticket(const Ticket&) = delete;
244 Ticket& operator=(const Ticket&) = delete;
245 ~Ticket() { release(); }
246 void release() {
247 if (!gate_) return;
248 gate_->leave(estimate_);
249 gate_ = nullptr;
250 release_free_memory();
251 }
252 private:
253 LargeModuleGate* gate_ = nullptr;
254 uint64_t estimate_ = 0;
255 };
256
257private:
258 bool admits_locked(uint64_t estimate, Work work) const {
259 if (inflight_ == 0) return true;
260 const uint64_t limit = work == Work::demand ? budget() : budget() / 4;
261 return inflight_ < max_inflight_ && used_ + estimate <= limit;
262 }
263
264 const uint64_t budget_;
265 const unsigned max_inflight_;
266 const std::function<uint64_t()> read_budget_;
267 mutable std::mutex mu_;
268 std::condition_variable cv_;
269 std::list<char> waiting_[2]; // demand, speculative: one entry for each thread in enter(), in the order they came
270 uint64_t used_ = 0;
271 unsigned inflight_ = 0;
272 unsigned demanded_ = 0; // the Demands
273};
274
275} // namespace leonida