upleb.uk

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

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