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:
authorJan Trencansky <jan.trencansky@protonmail.com>2026-11-25 17:11:38 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-25 17:11:38 -0500
commitca9e45dbd136feae14936ffbbe300d18bcda48c7 (patch)
treed6cad81523cd0cbdd774b9d6c1c597584055d1ec /runtime/src
parentb8c925002c6b4a6bfb5cfad6e7cc60ce2414586e (diff)
parentd3b8251bc390418cdbc1f2d30727b6b31d889cfa (diff)
Merge main into pe-inspect-linux-classes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src')
-rw-r--r--runtime/src/gfx10_descriptors.h10
-rw-r--r--runtime/src/large_module_gate.h293
-rw-r--r--runtime/src/vulkan_backend.h17
-rw-r--r--runtime/src/vulkan_replay.h74
4 files changed, 379 insertions, 15 deletions
diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h
index 219e0a8c5..acfa590f8 100644
--- a/runtime/src/gfx10_descriptors.h
+++ b/runtime/src/gfx10_descriptors.h
@@ -236,6 +236,16 @@ inline constexpr VkImageViewType vulkan_view_type(ImageType type) {
236 } 236 }
237} 237}
238 238
239inline constexpr VkImageSubresourceRange vulkan_subresource_range(const Image& image, VkImageAspectFlags aspects) {
240 const bool volume = image.type == ImageType::image_3d;
241 return {aspects, image.first_mip, image.mip_count, volume ? 0u : image.first_layer,
242 volume ? 1u : image.layer_count};
243}
244
245inline constexpr bool has_hardware_volume_uav_slice_offset(const ImageWords& words, const Image& image) {
246 return image.type == ImageType::image_3d && image.first_layer != 0 && detail::get(words[5], 0, 4) == 1;
247}
248
239// ---- formats ---- 249// ---- formats ----
240 250
241// One row for each Vulkan format: its GFX10_FORMAT code, and the DST_SEL that reads its channels as R, G, B, A 251// One row for each Vulkan format: its GFX10_FORMAT code, and the DST_SEL that reads its channels as R, G, B, A
diff --git a/runtime/src/large_module_gate.h b/runtime/src/large_module_gate.h
new file mode 100644
index 000000000..f66420bc2
--- /dev/null
+++ b/runtime/src/large_module_gate.h
@@ -0,0 +1,293 @@
1// How many large SPIR-V modules vk_pipeline_check and the runtime let into the driver at once, by a memory budget.
2//
3// Measured on RADV GFX1201 (Mesa 25.3.6) with the Mesa shader cache off: a 5.7 MB translated ray-tracing compute
4// module peaks at 1.96 GB of process memory compiling alone (~330 bytes per SPIR-V byte), a 0.36 MB one at 94 MB.
5// Compiling the large ones strictly one at a time left the other threads idle: 40 modules (27 over 4 MiB) on 6
6// threads took 308 s exclusively and 75 s in parallel, 7.0 GB and 8.7 GB peak. kBytesPerSpirvByte keeps a margin
7// over the measurement. The NVIDIA 621.24 driver (RTX 3080) took 85 to 131 bytes per SPIR-V byte for synthetic compute
8// modules of 128 KiB to 4 MiB (docs/d3d12_vulkan.md, "Large pipelines").
9//
10// The process grew past one module's peak even one at a time because glibc keeps freed memory in per-thread arenas
11// (6 threads: 6.2 GB; MALLOC_ARENA_MAX=1: 2.1 GB, same modules). release_free_memory() hands it back after each
12// large module.
13#pragma once
14
15#include <algorithm>
16#include <condition_variable>
17#include <cstddef>
18#include <cstdint>
19#include <cstdio>
20#include <functional>
21#include <list>
22#include <mutex>
23#include <optional>
24#include <string>
25#include <utility>
26
27#ifdef _WIN32
28#ifndef NOMINMAX
29#define NOMINMAX
30#endif
31#include <windows.h>
32#endif
33#if defined(__GLIBC__)
34#include <malloc.h>
35#endif
36
37namespace leonida {
38
39inline constexpr uint64_t kBytesPerSpirvByte = 512;
40
41inline uint64_t large_module_estimate(uint64_t spirv_bytes) { return spirv_bytes * kBytesPerSpirvByte; }
42
43#if defined(__linux__)
44// The first unsigned number in a file ("max" and unreadable files give no value).
45inline bool read_u64_file(const std::string& path, uint64_t& value) {
46 std::FILE* f = std::fopen(path.c_str(), "r");
47 if (!f) return false;
48 unsigned long long v = 0;
49 const bool ok = std::fscanf(f, "%llu", &v) == 1;
50 std::fclose(f);
51 value = v;
52 return ok;
53}
54
55// The room left under the cgroup v2 memory.max of this process and of every cgroup above it (a container or
56// systemd-run -p MemoryMax=...), or UINT64_MAX when none sets a limit. cgroup_root is a parameter for the tests.
57inline uint64_t cgroup_memory_room(const std::string& self_cgroup_file = "/proc/self/cgroup",
58 const std::string& cgroup_root = "/sys/fs/cgroup") {
59 std::FILE* f = std::fopen(self_cgroup_file.c_str(), "r");
60 if (!f) return UINT64_MAX;
61 char line[4096];
62 std::string rel;
63 while (std::fgets(line, sizeof(line), f)) {
64 std::string l(line);
65 if (l.rfind("0::", 0) == 0) { // the cgroup v2 line
66 rel = l.substr(3);
67 while (!rel.empty() && (rel.back() == '\n' || rel.back() == '\r')) rel.pop_back();
68 break;
69 }
70 }
71 std::fclose(f);
72 uint64_t room = UINT64_MAX;
73 for (std::string dir = rel; !dir.empty();) {
74 // In a cgroup namespace, "/" can be a constrained cgroup mounted as the visible root.
75 const std::string base = dir == "/" ? cgroup_root : cgroup_root + dir;
76 uint64_t max = 0, current = 0;
77 if (read_u64_file(base + "/memory.max", max) && read_u64_file(base + "/memory.current", current))
78 room = std::min(room, max > current ? max - current : 0);
79 const auto slash = dir.find_last_of('/');
80 if (dir == "/" || slash == std::string::npos) break;
81 dir.resize(slash == 0 ? 1 : slash);
82 }
83 return room;
84}
85#endif
86
87// Memory the OS could give this process now, or 0 when it can't tell (then the caller keeps the old exclusive gate).
88inline uint64_t available_memory_bytes() {
89#ifdef _WIN32
90 MEMORYSTATUSEX status{};
91 status.dwLength = sizeof(status);
92 return GlobalMemoryStatusEx(&status) ? uint64_t(status.ullAvailPhys) : 0;
93#elif defined(__linux__)
94 std::FILE* f = std::fopen("/proc/meminfo", "r");
95 if (!f) return 0;
96 char line[256];
97 unsigned long long kb = 0;
98 bool found = false;
99 while (std::fgets(line, sizeof(line), f))
100 if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) { found = true; break; }
101 std::fclose(f);
102 if (!found) return 0;
103 const uint64_t room = cgroup_memory_room();
104 return std::max<uint64_t>(1, std::min(uint64_t(kb) * 1024, room)); // 0 would mean "unknown"
105#else
106 return 0;
107#endif
108}
109
110// What large compiles may use of the free RAM and of the room under the commit limit: three quarters of the smaller. (On
111// Windows an allocation that the limit has no room for fails, whatever RAM is free.)
112inline uint64_t large_compile_share(uint64_t free_ram, uint64_t commit_room) {
113 return std::min(free_ram, commit_room) / 4 * 3;
114}
115
116// The same of the memory that is free at this moment. 0 when it is unknown: then they compile one at a time.
117inline uint64_t large_compile_budget_bytes() {
118#ifdef _WIN32
119 MEMORYSTATUSEX status{};
120 status.dwLength = sizeof(status);
121 if (!GlobalMemoryStatusEx(&status)) return 0;
122 return large_compile_share(status.ullAvailPhys, status.ullAvailPageFile);
123#else
124 return large_compile_share(available_memory_bytes(), UINT64_MAX);
125#endif
126}
127
128// LEONIDA_BIG_COMPILE_BUDGET_MB: a fixed budget in MiB instead of the share of the free memory (0: one at a time). Unset
129// or empty, and text that is not a number: none. `valid` is false for the latter.
130struct LargeCompileBudget {
131 std::optional<uint64_t> fixed{};
132 bool valid = true;
133};
134
135inline LargeCompileBudget large_compile_budget(const char* text) {
136 if (!text || !*text) return {};
137 uint64_t mib = 0;
138 for (const char* c = text; *c; ++c) {
139 if (*c < '0' || *c > '9') return {std::nullopt, false};
140 mib = std::min<uint64_t>(mib * 10 + uint64_t(*c - '0'), UINT64_MAX >> 20);
141 }
142 return {mib << 20, true};
143}
144
145// Return memory freed by the driver's compiler to the OS (glibc keeps it in the arena of the thread that freed it).
146inline void release_free_memory() {
147#if defined(__GLIBC__)
148 malloc_trim(0);
149#endif
150}
151
152// Lets large modules in while their estimates fit the budget and fewer than max_inflight are in. One always gets in
153// when none is, so a module bigger than the whole budget still compiles (alone among the large ones).
154//
155// The second constructor is the runtime's: the budget is read again whenever a place is given or returned, and the
156// modules get in in the order they came, those a submission waits for (demand) before the others (speculative). While the
157// first in line does not fit, the next behind it that does may pass, as long as all that have passed it would fit the
158// budget together with it. So, with the budget as it is, it waits at most for those that were in when it became the first,
159// however many come after it, and one larger than the budget is not passed. A speculative one gets in only while no demand
160// waits and no submission has a Demand, and only within a quarter of the budget, so that a demand finds the rest free. An
161// estimate counts in full until its module leaves, although the driver has allocated part of it by then and the budget is
162// that much smaller: what is in has not taken all it is going to.
163class LargeModuleGate {
164public:
165 enum class Work { demand, speculative };
166
167 LargeModuleGate(uint64_t budget, unsigned max_inflight)
168 : budget_(budget), max_inflight_(max_inflight ? max_inflight : 1) {}
169 explicit LargeModuleGate(std::function<uint64_t()> budget)
170 : budget_(0), max_inflight_(UINT32_MAX), read_budget_(std::move(budget)) {}
171
172 bool admits(uint64_t estimate) const {
173 std::lock_guard<std::mutex> g(mu_);
174 return admits_locked(estimate, budget());
175 }
176 void enter(uint64_t estimate, Work work = Work::demand) {
177 std::unique_lock<std::mutex> l(mu_);
178 if (!read_budget_) {
179 cv_.wait(l, [&] { return admits_locked(estimate, limit_for(work)); });
180 } else {
181 auto& queue = waiting_[work == Work::demand ? 0 : 1];
182 const auto me = queue.insert(queue.end(), Waiter{estimate});
183 cv_.wait(l, [&] {
184 return (work == Work::demand || (waiting_[0].empty() && !demanded_)) && next_locked(work) == &*me;
185 });
186 if (me != queue.begin()) queue.front().passed += estimate;
187 queue.erase(me);
188 }
189 used_ += estimate;
190 ++inflight_;
191 if (!waiting_[0].empty() || !waiting_[1].empty()) cv_.notify_all(); // the next in the queue may fit as well
192 }
193 void leave(uint64_t estimate) {
194 {
195 std::lock_guard<std::mutex> g(mu_);
196 used_ -= estimate;
197 --inflight_;
198 }
199 cv_.notify_all();
200 }
201 unsigned inflight() const {
202 std::lock_guard<std::mutex> g(mu_);
203 return inflight_;
204 }
205 size_t waiting(Work work) const { // in order: the threads in enter(), with a budget that is read
206 std::lock_guard<std::mutex> g(mu_);
207 return waiting_[work == Work::demand ? 0 : 1].size();
208 }
209 uint64_t budget() const { return read_budget_ ? read_budget_() : budget_; }
210 unsigned max_inflight() const { return max_inflight_; }
211
212 // A submission that has large modules to build: until it ends, the places that its modules leave between one and the
213 // next are not taken by speculative ones.
214 class Demand {
215 public:
216 explicit Demand(LargeModuleGate& gate) : gate_(gate) {
217 std::lock_guard<std::mutex> g(gate_.mu_);
218 ++gate_.demanded_;
219 }
220 ~Demand() {
221 {
222 std::lock_guard<std::mutex> g(gate_.mu_);
223 --gate_.demanded_;
224 }
225 gate_.cv_.notify_all();
226 }
227 Demand(const Demand&) = delete;
228 Demand& operator=(const Demand&) = delete;
229
230 private:
231 LargeModuleGate& gate_;
232 };
233
234 // Holds a place from construction until destruction (or release()), then hands freed memory back.
235 class Ticket {
236 public:
237 Ticket() = default;
238 Ticket(LargeModuleGate& gate, uint64_t estimate, Work work = Work::demand) : gate_(&gate), estimate_(estimate) {
239 gate.enter(estimate, work);
240 }
241 Ticket(Ticket&& o) noexcept : gate_(o.gate_), estimate_(o.estimate_) { o.gate_ = nullptr; }
242 Ticket& operator=(Ticket&& o) noexcept {
243 if (this != &o) { release(); gate_ = o.gate_; estimate_ = o.estimate_; o.gate_ = nullptr; }
244 return *this;
245 }
246 Ticket(const Ticket&) = delete;
247 Ticket& operator=(const Ticket&) = delete;
248 ~Ticket() { release(); }
249 void release() {
250 if (!gate_) return;
251 gate_->leave(estimate_);
252 gate_ = nullptr;
253 release_free_memory();
254 }
255 private:
256 LargeModuleGate* gate_ = nullptr;
257 uint64_t estimate_ = 0;
258 };
259
260private:
261 struct Waiter {
262 uint64_t estimate;
263 uint64_t passed = 0; // the estimates of those that have passed it while it was the first in line
264 };
265
266 uint64_t limit_for(Work work) const { return work == Work::demand ? budget() : budget() / 4; }
267 bool admits_locked(uint64_t estimate, uint64_t limit) const {
268 return inflight_ == 0 || (inflight_ < max_inflight_ && used_ + estimate <= limit);
269 }
270 // The one in line that gets in now, if any: the first, or else the first that fits and may pass it.
271 const Waiter* next_locked(Work work) const {
272 const auto& queue = waiting_[work == Work::demand ? 0 : 1];
273 const uint64_t limit = limit_for(work);
274 for (const Waiter& w : queue) {
275 const Waiter& first = queue.front();
276 if (&w != &first && first.passed + w.estimate + first.estimate > limit) continue;
277 if (admits_locked(w.estimate, limit)) return &w;
278 }
279 return nullptr;
280 }
281
282 const uint64_t budget_;
283 const unsigned max_inflight_;
284 const std::function<uint64_t()> read_budget_;
285 mutable std::mutex mu_;
286 std::condition_variable cv_;
287 std::list<Waiter> waiting_[2]; // demand, speculative: one for each thread in enter(), in the order they came
288 uint64_t used_ = 0;
289 unsigned inflight_ = 0;
290 unsigned demanded_ = 0; // the Demands
291};
292
293} // namespace leonida
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index d0a863421..ecc2eef9c 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -1572,6 +1572,14 @@ public:
1572 std::unique_lock lock(pipeline_mutex_); 1572 std::unique_lock lock(pipeline_mutex_);
1573 pipeline_workers_.swap(workers); 1573 pipeline_workers_.swap(workers);
1574 } 1574 }
1575 // For the large pipelines of a submission: the memory they may use while they compile together
1576 // (PipelineCompiles::build), and what is kept while they do (LargeModuleGate::Demand). None (the default): they compile
1577 // one after another.
1578 void set_large_compiles(std::function<std::uint64_t()> budget, std::function<std::shared_ptr<void>()> demand) {
1579 std::unique_lock lock(pipeline_mutex_);
1580 large_compile_budget_ = std::move(budget);
1581 large_compile_demand_ = std::move(demand);
1582 }
1575 PipelineWorkers::Stats pipeline_worker_stats() { 1583 PipelineWorkers::Stats pipeline_worker_stats() {
1576 std::shared_lock lock(pipeline_mutex_); 1584 std::shared_lock lock(pipeline_mutex_);
1577 return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{}; 1585 return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{};
@@ -2189,6 +2197,8 @@ private:
2189 std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_; 2197 std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_;
2190 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_; 2198 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_;
2191 std::unique_ptr<PipelineWorkers> pipeline_workers_; 2199 std::unique_ptr<PipelineWorkers> pipeline_workers_;
2200 std::function<std::uint64_t()> large_compile_budget_;
2201 std::function<std::shared_ptr<void>()> large_compile_demand_;
2192 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_; 2202 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_;
2193 LayoutTracker tracker_; 2203 LayoutTracker tracker_;
2194 std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only 2204 std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only
@@ -3168,10 +3178,13 @@ private:
3168 recycle_khr_as_queries(khr_guard.as_queries); 3178 recycle_khr_as_queries(khr_guard.as_queries);
3169 geometry.clear(); 3179 geometry.clear();
3170 3180
3181 std::shared_ptr<void> demand;
3182 if (context_.large_compile_demand_ && compiles.any_large()) demand = context_.large_compile_demand_();
3171 if (context_.pipeline_workers_) 3183 if (context_.pipeline_workers_)
3172 compiles.build(run_compiles); 3184 compiles.build(run_compiles, context_.large_compile_budget_);
3173 else 3185 else
3174 compiles.build_serial(); 3186 compiles.build_serial();
3187 demand.reset();
3175 const ReplayResult compile_result = check_compiled_pipelines(compiles, prepare_result); 3188 const ReplayResult compile_result = check_compiled_pipelines(compiles, prepare_result);
3176 if (compile_result != ReplayResult::success) return compile_result; 3189 if (compile_result != ReplayResult::success) return compile_result;
3177 prior_compiles = std::move(compiles); 3190 prior_compiles = std::move(compiles);
@@ -3181,7 +3194,7 @@ private:
3181 const PipelineCompiles* prior = has_prior_compiles ? &prior_compiles : nullptr; 3194 const PipelineCompiles* prior = has_prior_compiles ? &prior_compiles : nullptr;
3182 prepare_result = context_.pipeline_workers_ 3195 prepare_result = context_.pipeline_workers_
3183 ? build_pipelines(compiles, std::span(prepared).first(lists.size()), prepare_result, 3196 ? build_pipelines(compiles, std::span(prepared).first(lists.size()), prepare_result,
3184 run_compiles, prior) 3197 run_compiles, context_.large_compile_budget_, prior)
3185 : build_pipelines_serial(compiles, std::span(prepared).first(lists.size()), 3198 : build_pipelines_serial(compiles, std::span(prepared).first(lists.size()),
3186 prepare_result, prior); 3199 prepare_result, prior);
3187 replay.compiles = nullptr; 3200 replay.compiles = nullptr;
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index b735fbaa6..449f8de5d 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -60,6 +60,7 @@
60#include <limits> 60#include <limits>
61#include <map> 61#include <map>
62#include <memory> 62#include <memory>
63#include <mutex>
63#include <optional> 64#include <optional>
64#include <type_traits> 65#include <type_traits>
65#include <unordered_map> 66#include <unordered_map>
@@ -868,8 +869,9 @@ struct ComputePipeline {
868 // What `build` would return when it is built already and nobody is building it, else null; builds nothing. Null: a 869 // What `build` would return when it is built already and nobody is building it, else null; builds nothing. Null: a
869 // first use is always built where prepare() meets it. Not used with async_build. See PipelineCompiles. 870 // first use is always built where prepare() meets it. Not used with async_build. See PipelineCompiles.
870 VkPipeline (*built)(void*) = nullptr; 871 VkPipeline (*built)(void*) = nullptr;
871 bool large = false; // compiled one after another with the other large ones (PipelineCompiles) 872 bool large = false; // PipelineCompiles limits how many of these compile at once
872 bool skipped = false; // never built on request (LEONIDA_SKIP_COMPUTE): its dispatches are dropped 873 bool skipped = false; // never built on request (LEONIDA_SKIP_COMPUTE): its dispatches are dropped
874 std::uint64_t estimate = 0; // large: the bytes of memory its compile is expected to take
873}; 875};
874 876
875// A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it 877// A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it
@@ -903,6 +905,7 @@ struct GraphicsPipeline {
903 std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count 905 std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count
904 bool async_build = false; 906 bool async_build = false;
905 bool nonunit_vertex_divisor = false; // an actual instance divisor > 1, not a zero-stride emulation 907 bool nonunit_vertex_divisor = false; // an actual instance divisor > 1, not a zero-stride emulation
908 std::uint64_t estimate = 0; // as ComputePipeline::estimate
906}; 909};
907 910
908// The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base. 911// The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base.
@@ -1000,7 +1003,7 @@ public:
1000 User user; 1003 User user;
1001 }; 1004 };
1002 // A compile takes the driver some hundred bytes of memory for each byte of SPIR-V (docs/pipeline_check.md): graphics 1005 // A compile takes the driver some hundred bytes of memory for each byte of SPIR-V (docs/pipeline_check.md): graphics
1003 // pipelines of this much or more are `large`. 1006 // pipelines of this much or more are `large`. For compute pipelines the D3D12 layer decides.
1004 static constexpr std::uint64_t large_spirv_bytes = 1u << 20; 1007 static constexpr std::uint64_t large_spirv_bytes = 1u << 20;
1005 1008
1006 Ticket add(const GraphicsPipeline& pipeline, std::uint32_t flags) { 1009 Ticket add(const GraphicsPipeline& pipeline, std::uint32_t flags) {
@@ -1009,6 +1012,9 @@ public:
1009 Ticket add(const ComputePipeline& pipeline, User user) { return add({nullptr, &pipeline, 0}, user); } 1012 Ticket add(const ComputePipeline& pipeline, User user) { return add({nullptr, &pipeline, 0}, user); }
1010 1013
1011 bool empty() const { return jobs_.empty(); } 1014 bool empty() const { return jobs_.empty(); }
1015 bool any_large() const {
1016 return std::any_of(jobs_.begin(), jobs_.end(), [](const Job& job) { return is_large(job); });
1017 }
1012 std::size_t size() const { return jobs_.size(); } 1018 std::size_t size() const { return jobs_.size(); }
1013 VkPipeline built(Ticket ticket) const { return jobs_[ticket - 1].built; } 1019 VkPipeline built(Ticket ticket) const { return jobs_[ticket - 1].built; }
1014 const std::vector<Use>& uses() const { return uses_; } // in the order of the commands 1020 const std::vector<Use>& uses() const { return uses_; } // in the order of the commands
@@ -1030,26 +1036,64 @@ public:
1030 return lookup(job.graphics, job.compute, job.flags, unused); 1036 return lookup(job.graphics, job.compute, job.flags, unused);
1031 } 1037 }
1032 1038
1033 // Compiles all of them through run(count, job) (PipelineWorkers::run): the large ones one after another, as without 1039 // Compiles all of them through run(count, job) (PipelineWorkers::run). The large ones share budget() bytes of memory:
1034 // workers, beside the others. Jobs already attempted in `prior` reuse that outcome without re-invoking build(). 1040 // the largest first, as many at once as their estimates fit, one at least; while the next one does not fit, the
1041 // others are compiled first. No budget, or 0: the large ones one after another, as without workers, beside the others.
1035 template<typename Run> 1042 template<typename Run>
1036 void build(Run&& run, const PipelineCompiles* prior = nullptr) { 1043 void build(Run&& run, const std::function<std::uint64_t()>& read_budget = {},
1044 const PipelineCompiles* prior = nullptr) {
1037 std::vector<std::size_t> single, large; 1045 std::vector<std::size_t> single, large;
1038 for (std::size_t i = 0; i < jobs_.size(); ++i) { 1046 for (std::size_t i = 0; i < jobs_.size(); ++i) {
1039 if (prior && prior->lookup(jobs_[i].graphics, jobs_[i].compute, jobs_[i].flags, jobs_[i].built)) continue; 1047 if (prior && prior->lookup(jobs_[i].graphics, jobs_[i].compute, jobs_[i].flags, jobs_[i].built)) continue;
1040 (is_large(jobs_[i]) ? large : single).push_back(i); 1048 (is_large(jobs_[i]) ? large : single).push_back(i);
1041 } 1049 }
1042 if (single.empty() && large.empty()) return; 1050 if (single.empty() && large.empty()) return;
1051 // The first jobs of the run are lanes, which take large ones until none is left: no more of them than there are
1052 // large ones that fit the budget together (the smallest), so that no thread waits here for room in vain.
1053 std::size_t lanes = large.empty() ? 0 : 1;
1054 const std::uint64_t budget = lanes && read_budget ? read_budget() : 0;
1055 if (budget) {
1056 std::stable_sort(large.begin(), large.end(), [this](std::size_t a, std::size_t b) {
1057 return estimate(jobs_[a]) > estimate(jobs_[b]);
1058 });
1059 std::uint64_t sum = estimate(jobs_[large.back()]);
1060 while (lanes < large.size() && (sum += estimate(jobs_[large[large.size() - 1 - lanes]])) <= budget) ++lanes;
1061 }
1043 const auto compile = [this](std::size_t i) { 1062 const auto compile = [this](std::size_t i) {
1044 Job& job = jobs_[i]; 1063 Job& job = jobs_[i];
1045 job.built = job.graphics ? job.graphics->variant(job.flags) : job.compute->build(job.compute->build_context); 1064 job.built = job.graphics ? job.graphics->variant(job.flags) : job.compute->build(job.compute->build_context);
1046 }; 1065 };
1047 const std::size_t chain = large.empty() ? 0 : 1; // the large ones are one unit, the first 1066 std::mutex mutex; // guards the four below
1048 run(chain + single.size(), [&](std::size_t i) { 1067 std::size_t next_single = 0, next_large = 0, compiling = 0;
1049 if (i >= chain) 1068 std::uint64_t reserved = 0; // the estimates of the large ones compiling
1050 compile(single[i - chain]); 1069 run(lanes + single.size(), [&](std::size_t i) {
1051 else 1070 std::unique_lock lock(mutex);
1052 for (const std::size_t each : large) compile(each); 1071 if (i >= lanes) {
1072 if (next_single == single.size()) return; // a lane has taken it
1073 const std::size_t index = single[next_single++];
1074 lock.unlock();
1075 compile(index);
1076 return;
1077 }
1078 while (next_large < large.size()) {
1079 const std::uint64_t need = estimate(jobs_[large[next_large]]);
1080 const bool fits = !compiling || reserved + need <= budget;
1081 if (!fits && next_single < single.size()) {
1082 const std::size_t index = single[next_single++];
1083 lock.unlock();
1084 compile(index);
1085 lock.lock();
1086 continue;
1087 }
1088 const std::size_t index = large[next_large++];
1089 ++compiling;
1090 reserved += need;
1091 lock.unlock();
1092 compile(index);
1093 lock.lock();
1094 --compiling;
1095 reserved -= need;
1096 }
1053 }); 1097 });
1054 } 1098 }
1055 1099
@@ -1081,6 +1125,9 @@ private:
1081 VkPipeline built = VK_NULL_HANDLE; 1125 VkPipeline built = VK_NULL_HANDLE;
1082 }; 1126 };
1083 static bool is_large(const Job& job) { return job.graphics ? job.graphics->large : job.compute->large; } 1127 static bool is_large(const Job& job) { return job.graphics ? job.graphics->large : job.compute->large; }
1128 static std::uint64_t estimate(const Job& job) {
1129 return job.graphics ? job.graphics->estimate : job.compute->estimate;
1130 }
1084 Ticket add(const Job& job, User user) { 1131 Ticket add(const Job& job, User user) {
1085 const void* const pipeline = job.graphics ? static_cast<const void*>(job.graphics) : job.compute; 1132 const void* const pipeline = job.graphics ? static_cast<const void*>(job.graphics) : job.compute;
1086 const auto [it, added] = tickets_.try_emplace({pipeline, job.flags}, Ticket(jobs_.size() + 1)); 1133 const auto [it, added] = tickets_.try_emplace({pipeline, job.flags}, Ticket(jobs_.size() + 1));
@@ -3014,9 +3061,10 @@ inline ReplayResult finish_compiled_pipelines(const PipelineCompiles& compiles,
3014// have returned had they built each pipeline themselves. 3061// have returned had they built each pipeline themselves.
3015template<typename Run> 3062template<typename Run>
3016ReplayResult build_pipelines(PipelineCompiles& compiles, std::span<PreparedList> lists, ReplayResult result, 3063ReplayResult build_pipelines(PipelineCompiles& compiles, std::span<PreparedList> lists, ReplayResult result,
3017 Run&& run, const PipelineCompiles* prior = nullptr) { 3064 Run&& run, const std::function<std::uint64_t()>& budget = {},
3065 const PipelineCompiles* prior = nullptr) {
3018 if (compiles.empty()) return result; 3066 if (compiles.empty()) return result;
3019 compiles.build(run, prior); 3067 compiles.build(run, budget, prior);
3020 return finish_compiled_pipelines(compiles, lists, result, prior); 3068 return finish_compiled_pipelines(compiles, lists, result, prior);
3021} 3069}
3022 3070