MimIR
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
solver.cpp
Go to the documentation of this file.
1#include "pbqp/solver.h"
2
3#include <cassert>
4#include <cstddef>
5#include <cstdint>
6
7#include <algorithm>
8#include <numeric>
9#include <optional>
10#include <queue>
11#include <ranges>
12#include <thread>
13#include <utility>
14
15#include <fe/arena.h>
16#include <fe/container.h>
17#include <fe/vector.h>
18
19#if defined(__SANITIZE_THREAD__)
20# define PBQP_TSAN 1
21#elif defined(__has_feature)
22# if __has_feature(thread_sanitizer)
23# define PBQP_TSAN 1
24# endif
25#endif
26
27// ifunc resolvers run during relocation, before the ThreadSanitizer runtime exists.
28#if defined(__x86_64__) && defined(__ELF__) && (defined(__GNUC__) || defined(__clang__)) && !defined(PBQP_TSAN)
29# define PBQP_DISPATCH __attribute__((target_clones("arch=x86-64-v4", "avx2", "default")))
30#else
31# define PBQP_DISPATCH
32#endif
33
34namespace pbqp {
35namespace {
36
37/// By value, as GCC fails to vectorize `std::min` over references to a class.
38Cost min(Cost lhs, Cost rhs) { return lhs.value() < rhs.value() ? lhs : rhs; }
39
40/// Only valid for normalized, hence non-negative, costs: their sum fits into 32 unsigned bits.
41Cost add_normalized(Cost lhs, Cost rhs) {
42 const auto sum = static_cast<std::uint32_t>(lhs.value()) + static_cast<std::uint32_t>(rhs.value());
43 return static_cast<Cost::Rep>(std::min(sum, static_cast<std::uint32_t>(Cost::inf().value())));
44}
45
46/// Only valid for normalized costs with `minimum <= value`; an inf minimum means the whole row was moved elsewhere.
47Cost sub_normalized(Cost value, Cost minimum) {
48 if (minimum.is_inf()) return 0;
49 if (value.is_inf()) return Cost::inf();
50 return static_cast<Cost::Rep>(std::min<int64_t>(int64_t{value.value()} - minimum.value(), Cost::inf().value()));
51}
52
53PBQP_DISPATCH void add_into(Cost* __restrict dst, const Cost* __restrict src, size_t count) {
54 for (size_t i = 0; i < count; ++i)
55 dst[i] = add_normalized(dst[i], src[i]);
56}
57
58PBQP_DISPATCH void fold_row(Cost* __restrict dst, const Cost* __restrict row, Cost cost, size_t count) {
59 for (size_t i = 0; i < count; ++i)
60 dst[i] = min(dst[i], add_normalized(cost, row[i]));
61}
62
63MatrixSpan allocate_matrix(fe::Arena& arena, size_t rows, size_t cols) {
64 return {arena.allocate<Cost>(rows * cols), rows, cols};
65}
66
67/// Row-major matrix of an edge oriented (reduced option, neighbour option).
68struct TrimmedEdge {
69 NodeId neighbour = 0;
70 MatrixView matrix;
71};
72
73struct Reduction {
74 fe::View<Cost> costs;
75 fe::View<TrimmedEdge> edges;
76};
77
78/// What back-substitution needs of an edge; dead edges are never written, so their matrices stay as reduced.
79struct Link {
80 NodeId neighbour = 0;
81 MatrixView matrix; // (reduced option, neighbour option)
82 const OptionId* neighbour_working = nullptr; // original -> working option or npos; null if none was deleted
83};
84
85/// A reduced node in working option order.
86struct Subst {
87 NodeId node = 0;
88 fe::View<Cost> costs;
89 const OptionId* original = nullptr; // original[working option]; null if no option was deleted
90 fe::View<Link> links;
91};
92
93/// Normalized working copy of a Graph with worklists for exact and RN reductions.
94class Reducer {
95public:
96 Reducer(const Graph& graph, fe::View<size_t> rn_priority)
97 : rn_priority_(rn_priority) {
98 nodes_.resize(graph.num_nodes());
99 for (const auto n : graph.nodes()) {
100 const auto costs = graph.node_costs(n);
101 nodes_[n].costs.assign(costs.begin(), costs.end());
102 nodes_[n].original.resize(costs.size());
103 nodes_[n].original_options = costs.size();
104 std::ranges::iota(nodes_[n].original, OptionId{0});
105 nodes_[n].alive = true;
106 }
107 assert((rn_priority.empty() || rn_priority.size() >= nodes_.size())
108 && "solve: rn_priority does not cover every node");
109 for (const auto e : graph.edges()) {
110 const auto [src, dst] = graph.edge(e);
111 link(src, dst, graph.edge_matrix(e).data(), nullptr);
112 }
113 for (EdgeId e = 0; e < edges_.size(); ++e)
114 normalize_edge(e);
115 for (const auto n : graph.nodes()) {
116 normalize_node(n);
117 touch(n);
118 }
119 }
120
121 [[nodiscard]] const Statistics& statistics() const { return statistics_; }
122
123 /// Exact reductions first; RN takes the highest priority, then degree, then rn_score.
124 NodeId next() {
125 while (!dirty_.empty()) {
126 const NodeId n = dirty_.back();
127 dirty_.pop_back();
128 nodes_[n].dirty = false;
129 if (nodes_[n].alive) prune(n);
130 }
131 while (!low_.empty()) {
132 const NodeId n = low_.back();
133 low_.pop_back();
134 if (nodes_[n].alive) return n;
135 }
136 while (!high_.empty()) {
137 const auto candidate = fe::pop(high_);
138 const Node& node = nodes_[candidate.node];
139 if (node.alive && node.version == candidate.version) return candidate.node;
140 }
141 return Graph::npos;
142 }
143
144 void reduce(NodeId n, fe::Vector<Subst>& stack) {
145 if (degree(n) > 2 && options(n) > 1) {
146 bool merged = false;
147 while (merge_neighbour(n, stack))
148 merged = true;
149 if (merged) {
150 touch(n);
151 return;
152 }
153 }
154
155 stack.emplace_back(record(n));
156 const auto mark = scratch_.state();
157 switch (const auto reduction = snapshot(n, stack.back()); reduction.edges.size()) {
158 case 0: ++statistics_.r0; break;
159 case 1:
160 ++statistics_.r1;
161 fold_into_neighbour(reduction);
162 break;
163 case 2:
164 ++statistics_.r2;
165 contract(reduction);
166 break;
167 default:
168 ++(options(n) == 1 ? statistics_.single_option : statistics_.rn);
169 fold_locally_best_option(reduction);
170 break;
171 }
172 scratch_.deallocate(mark);
173 remove_node(n);
174 }
175
176 /// Exact for degree <= 2 nodes; RN nodes may still improve on their RN choice here.
177 [[nodiscard]] OptionId choose(const Subst& subst, const Choices& choices) const {
178 const auto original = [&](OptionId x) { return subst.original ? subst.original[x] : x; };
179
180 OptionId best = original(0);
181 Cost best_total = Cost::inf();
182 for (OptionId x = 0; x < subst.costs.size(); ++x) {
183 Cost total = subst.costs[x];
184 for (const Link& link : subst.links) {
185 if (total.is_inf()) break;
186 const OptionId chosen = choices[link.neighbour];
187 const OptionId y = link.neighbour_working ? link.neighbour_working[chosen] : chosen;
188 assert(y != Graph::npos && "choose: a neighbour picked an option it had already lost");
189 total += link.matrix[x, y];
190 }
191 if (total < best_total) {
192 best_total = total;
193 best = original(x);
194 }
195 }
196 return best;
197 }
198
199private:
200 struct Node {
201 Costs costs;
202 fe::Vector<OptionId, 4> original; // original[working option]
203 const OptionId* working = nullptr; // inverse of original once an option was deleted, built on demand
204 Edges edges;
205 size_t original_options = 0;
206 size_t version = 0;
207 bool alive = false;
208 bool low = false;
209 bool dirty = false;
210 };
211
212 struct Edge {
213 NodeId src = 0;
214 NodeId dst = 0;
215 const Cost* shared = nullptr; // the input graph's matrix until the first write
216 Cost* owned = nullptr;
217 };
218
219 struct Candidate {
220 size_t priority = 0;
221 size_t degree = 0;
222 double score = 0.0;
223 NodeId node = 0;
224 size_t version = 0;
225
226 auto operator<=>(const Candidate&) const = default;
227 };
228
229 [[nodiscard]] size_t degree(NodeId n) const { return nodes_[n].edges.size(); }
230 [[nodiscard]] size_t options(NodeId n) const { return nodes_[n].costs.size(); }
231
232 [[nodiscard]] MatrixView view(EdgeId e) const {
233 const Edge& edge = edges_[e];
234 return {edge.owned != nullptr ? edge.owned : edge.shared, options(edge.src), options(edge.dst)};
235 }
236
237 [[nodiscard]] MatrixSpan writable(EdgeId e) {
238 if (edges_[e].owned == nullptr) edges_[e].owned = arena_.copy(view(e)).data();
239 const Edge& edge = edges_[e];
240 return {edge.owned, options(edge.src), options(edge.dst)};
241 }
242
243 /// The options of `from` are the rows.
244 [[nodiscard]] MatrixView view(EdgeId e, NodeId from) const {
245 return edges_[e].src == from ? view(e) : view(e).transposed();
246 }
247
248 [[nodiscard]] MatrixSpan writable(EdgeId e, NodeId from) {
249 return edges_[e].src == from ? writable(e) : writable(e).transposed();
250 }
251
252 /// Cost spread per incident edge: what a wrong RN decision is likely to cost.
253 [[nodiscard]] double rn_score(NodeId n) const {
254 const auto [low, high] = std::ranges::minmax(nodes_[n].costs);
255 return static_cast<double>(high.value() - low.value()) / static_cast<double>(std::max<size_t>(1, degree(n)));
256 }
257
258 /// Single-option nodes are reduced exactly at any degree, so they belong on the low worklist.
259 void touch(NodeId n) {
260 Node& node = nodes_[n];
261 ++node.version;
262 if (!node.dirty) dirty_.emplace_back(n);
263 node.dirty = true;
264 if (degree(n) <= 2 || options(n) == 1) {
265 if (!node.low) low_.emplace_back(n);
266 node.low = true;
267 } else {
268 high_.push(Candidate{.priority = rn_priority_.empty() ? 0 : rn_priority_[n],
269 .degree = degree(n),
270 .score = rn_score(n),
271 .node = n,
272 .version = node.version});
273 }
274 }
275
276 void normalize_node(NodeId n) {
277 Costs& costs = nodes_[n].costs;
278 const Cost minimum = std::accumulate(costs.begin(), costs.end(), Cost::inf(), min);
279 if (minimum == 0 || minimum.is_inf()) return;
280 for (auto& cost : costs)
281 cost = sub_normalized(cost, minimum);
282 }
283
284 /// Moves row and column minima into the node vectors and drops the edge if nothing is left.
285 void normalize_edge(EdgeId e) {
286 const NodeId src = edges_[e].src;
287 const NodeId dst = edges_[e].dst;
288 Costs& src_costs = nodes_[src].costs;
289 Costs& dst_costs = nodes_[dst].costs;
290 const size_t rows = src_costs.size();
291 const size_t cols = dst_costs.size();
292
293 for (size_t r = 0; r < rows; ++r) {
294 const Cost* const row = view(e).row(r);
295 const Cost minimum = std::accumulate(row, row + cols, Cost::inf(), min);
296 if (minimum == 0) continue;
297 src_costs[r] += minimum;
298 const MatrixSpan matrix = writable(e);
299 for (size_t c = 0; c < cols; ++c)
300 matrix[r, c] = sub_normalized(matrix[r, c], minimum);
301 }
302 const auto mark = scratch_.state();
303 Cost* const minima = scratch_.allocate<Cost>(cols);
304 std::fill_n(minima, cols, Cost::inf());
305 for (size_t r = 0; r < rows; ++r)
306 fold_row(minima, view(e).row(r), 0, cols);
307 if (std::ranges::any_of(fe::View<Cost>{minima, cols}, [](Cost minimum) { return minimum != 0; })) {
308 for (size_t c = 0; c < cols; ++c)
309 dst_costs[c] += minima[c];
310 const MatrixSpan matrix = writable(e);
311 for (size_t r = 0; r < rows; ++r)
312 for (size_t c = 0; c < cols; ++c)
313 matrix[r, c] = sub_normalized(matrix[r, c], minima[c]);
314 }
315 scratch_.deallocate(mark);
316 if (std::ranges::all_of(view(e), [](Cost cost) { return cost == 0; })) {
317 erase(nodes_[src].edges, e);
318 erase(nodes_[dst].edges, e);
319 ++statistics_.dropped_edges;
320 }
321 }
322
323 [[nodiscard]] NodeId other_end(EdgeId e, NodeId n) const {
324 return edges_[e].src == n ? edges_[e].dst : edges_[e].src;
325 }
326
327 /// Deletes the options in `options`, which are sorted and distinct, from `n` and its incident edges.
328 void erase_options(NodeId n, fe::View<OptionId> options) {
329 Node& node = nodes_[n];
330 for (const auto e : node.edges) {
331 MatrixSpan matrix = writable(e, n);
332 matrix.erase_rows(options);
333 }
334 for (size_t k = 0; k < options.size(); ++k) {
335 const auto index = static_cast<std::ptrdiff_t>(options[k] - k);
336 node.costs.erase(node.costs.begin() + index);
337 node.original.erase(node.original.begin() + index);
338 }
339 node.working = nullptr;
340 }
341
342 /// Deletes forbidden options, always keeping at least one.
343 void prune(NodeId n) {
344 const auto num_options = options(n);
345 if (forbidden_capacity_ < num_options) {
346 forbidden_ = arena_.allocate<OptionId>(num_options);
347 forbidden_capacity_ = num_options;
348 }
349 size_t count = 0;
350 for (OptionId a = 0; a < num_options; ++a)
351 if (nodes_[n].costs[a].is_inf()) forbidden_[count++] = a;
352 if (count == num_options) --count;
353 if (count == 0) return;
354 statistics_.forbidden_options += count;
355 erase_options(n, {forbidden_, count});
356
357 const Edges incident = nodes_[n].edges;
358 for (const auto e : incident)
359 normalize_edge(e);
360 normalize_node(n);
361 touch(n);
362 for (const auto e : incident) {
363 normalize_node(other_end(e, n));
364 touch(other_end(e, n));
365 }
366 }
367
368 [[nodiscard]] const OptionId* working_options(NodeId n) {
369 Node& node = nodes_[n];
370 if (node.original.size() == node.original_options || node.working != nullptr) return node.working;
371 OptionId* const working = arena_.allocate<OptionId>(node.original_options);
372 std::fill_n(working, node.original_options, Graph::npos);
373 for (OptionId x = 0; x < node.original.size(); ++x)
374 working[node.original[x]] = x;
375 return node.working = working;
376 }
377
378 [[nodiscard]] Subst record(NodeId n) {
379 const Node& node = nodes_[n];
380 const auto links = arena_.copy(
381 node.edges | std::views::transform([&](EdgeId e) {
382 const NodeId other = other_end(e, n);
383 return Link{.neighbour = other, .matrix = view(e, n), .neighbour_working = working_options(other)};
384 }));
385 const bool deleted = node.original.size() != node.original_options;
386 return Subst{.node = n,
387 .costs = arena_.copy(node.costs),
388 .original = deleted ? arena_.copy(node.original).data() : nullptr,
389 .links = links};
390 }
391
392 void link(NodeId m, NodeId n, const Cost* shared, Cost* owned) {
393 edges_.emplace_back(Edge{.src = m, .dst = n, .shared = shared, .owned = owned});
394 nodes_[m].edges.emplace_back(edges_.size() - 1);
395 nodes_[n].edges.emplace_back(edges_.size() - 1);
396 }
397
398 [[nodiscard]] EdgeId find_edge(NodeId m, NodeId n) const {
399 if (degree(n) < degree(m)) std::swap(m, n);
400 for (const auto e : nodes_[m].edges)
401 if (edges_[e].src == n || edges_[e].dst == n) return e;
402 return Graph::npos;
403 }
404
405 void remove_node(NodeId n) {
406 Node& node = nodes_[n];
407 const Edges incident = std::move(node.edges);
408 node.edges.clear();
409 node.alive = false;
410 for (const auto e : incident) {
411 const NodeId other = other_end(e, n);
412 erase(nodes_[other].edges, e);
413 touch(other);
414 }
415 }
416
417 /// Copies a matrix without contiguous rows into the scratch arena.
418 [[nodiscard]] TrimmedEdge trim_edge(EdgeId e, NodeId from) {
419 const NodeId other = other_end(e, from);
420 const MatrixView matrix = view(e, from);
421 if (matrix.row_major()) return {.neighbour = other, .matrix = matrix};
422
423 const MatrixSpan copy = allocate_matrix(scratch_, matrix.rows(), matrix.cols());
424 copy.copy_from(matrix);
425 return {.neighbour = other, .matrix = copy};
426 }
427
428 [[nodiscard]] Reduction snapshot(NodeId n, const Subst& subst) {
429 return {.costs = subst.costs,
430 .edges
431 = scratch_.copy(nodes_[n].edges | std::views::transform([&](EdgeId e) { return trim_edge(e, n); }))};
432 }
433
434 /// RI: c'_n(y) = c_n(y) + min_x ( c(x) + M(x, y) )
435 void fold_into_neighbour(const Reduction& reduction) {
436 const TrimmedEdge& edge = reduction.edges.front();
437 const size_t y_dim = edge.matrix.cols();
438
439 Cost* const best = scratch_.allocate<Cost>(y_dim);
440 std::fill_n(best, y_dim, Cost::inf());
441 for (size_t x = 0; x < reduction.costs.size(); ++x)
442 fold_row(best, edge.matrix.row(x), reduction.costs[x], y_dim);
443 add_into(nodes_[edge.neighbour].costs.data(), best, y_dim);
444 normalize_node(edge.neighbour);
445 }
446
447 /// RII: M'_mn(i, j) = min_x ( c(x) + M_m(x, i) + M_n(x, j) )
448 void contract(const Reduction& reduction) {
449 const TrimmedEdge* to_m = &reduction.edges[0];
450 const TrimmedEdge* to_n = &reduction.edges[1];
451 const EdgeId e = find_edge(to_m->neighbour, to_n->neighbour);
452 // fold_row fills whole rows, so they must be the rows of the edge's storage.
453 if (e != Graph::npos && edges_[e].src != to_m->neighbour) std::swap(to_m, to_n);
454 const size_t m_dim = to_m->matrix.cols();
455 const size_t n_dim = to_n->matrix.cols();
456
457 const auto state = arena_.state();
458 const MatrixSpan merged = allocate_matrix(arena_, m_dim, n_dim);
459 std::ranges::fill(merged, Cost::inf());
460 for (size_t x = 0; x < reduction.costs.size(); ++x) {
461 const Cost* const n_row = to_n->matrix.row(x);
462 for (size_t i = 0; i < m_dim; ++i)
463 fold_row(merged.row(i), n_row, add_normalized(reduction.costs[x], to_m->matrix[x, i]), n_dim);
464 }
465 add_to_edge(e, to_m->neighbour, to_n->neighbour, merged, state);
466 }
467
468 /// A fresh options(m) × options(n) matrix whose storage is oriented like `e`, the edge between m and n, if any.
469 [[nodiscard]] MatrixSpan allocate_edge_matrix(EdgeId e, NodeId m, NodeId n) {
470 if (e != Graph::npos && edges_[e].src == n) return allocate_matrix(arena_, options(n), options(m)).transposed();
471 return allocate_matrix(arena_, options(m), options(n));
472 }
473
474 /// Adds `matrix`, the newest allocation in the arena since `state`, to `e`, the edge between m and n, if any.
475 /// Its storage is oriented like `e`, so it can become the edge's matrix.
476 void add_to_edge(EdgeId e, NodeId m, NodeId n, MatrixSpan matrix, fe::Arena::State state) {
477 assert((matrix.rows() == options(m) && matrix.cols() == options(n)) && "add_to_edge: matrix shape");
478 assert(((e == Graph::npos || edges_[e].src == m) ? matrix : matrix.transposed()).row_major()
479 && "add_to_edge: storage orientation");
480 if (e == Graph::npos) {
481 e = edges_.size();
482 link(m, n, nullptr, matrix.data());
483 } else if (edges_[e].owned == nullptr) {
484 add_into(matrix.data(), edges_[e].shared, matrix.size());
485 edges_[e].owned = matrix.data();
486 } else {
487 add_into(edges_[e].owned, matrix.data(), matrix.size());
488 arena_.deallocate(state);
489 }
490 normalize_edge(e);
491 normalize_node(m);
492 normalize_node(n);
493 }
494
495 /// The option of `m` that each option of `n` forces, or null if some option of `n` leaves `m` a choice.
496 [[nodiscard]] const OptionId* implied_options(EdgeId e, NodeId n) {
497 const MatrixView matrix = view(e, n);
498 const Costs& m_costs = nodes_[other_end(e, n)].costs;
499 OptionId* const implied = scratch_.allocate<OptionId>(options(n));
500 std::fill_n(implied, options(n), Graph::npos);
501 for (OptionId i = 0; i < options(n); ++i) {
502 if (nodes_[n].costs[i].is_inf()) continue;
503 for (OptionId j = 0; j < matrix.cols(); ++j) {
504 if (add_normalized(matrix[i, j], m_costs[j]).is_inf()) continue;
505 if (implied[i] != Graph::npos) return nullptr;
506 implied[i] = j;
507 }
508 }
509 return implied;
510 }
511
512 /// RM (Buchwald et al. 2011): moves the other edges of a neighbour whose option `n` determines onto `n`.
513 bool merge_neighbour(NodeId n, fe::Vector<Subst>& stack) {
514 // add_to_edge may grow nodes_[n].edges and dangle this loop's iterator, so a merge must return immediately.
515 for (const auto e : nodes_[n].edges) {
516 const NodeId m = other_end(e, n);
517 if (degree(m) < 2) continue;
518 const auto mark = scratch_.state();
519 const OptionId* const implied = implied_options(e, n);
520 if (implied == nullptr) {
521 scratch_.deallocate(mark);
522 continue;
523 }
524
525 const Edges moved = nodes_[m].edges;
526 for (const auto f : moved) {
527 if (f == e) continue;
528 const NodeId w = other_end(f, m);
529 const MatrixView to_w = view(f, m);
530 const EdgeId to_n_w = find_edge(n, w);
531
532 const auto state = arena_.state();
533 const MatrixSpan delta = allocate_edge_matrix(to_n_w, n, w);
534 std::ranges::fill(delta, Cost{0});
535 for (OptionId i = 0; i < options(n); ++i)
536 if (implied[i] != Graph::npos)
537 for (OptionId j = 0; j < options(w); ++j)
538 delta[i, j] = to_w[implied[i], j];
539 erase(nodes_[m].edges, f);
540 erase(nodes_[w].edges, f);
541 add_to_edge(to_n_w, n, w, delta, state);
542 touch(w);
543 }
544 scratch_.deallocate(mark);
545 ++statistics_.rm;
546 reduce(m, stack);
547 return true;
548 }
549 return false;
550 }
551
552 /// RN: commit to the locally best option and charge its matrix rows to the neighbours.
553 void fold_locally_best_option(const Reduction& reduction) {
554 OptionId best_option = 0;
555 Cost best_total = Cost::inf();
556 for (OptionId x = 0; x < reduction.costs.size(); ++x) {
557 Cost total = reduction.costs[x];
558 for (const auto& edge : reduction.edges) {
559 const Costs& neighbour_costs = nodes_[edge.neighbour].costs;
560 Cost cheapest = Cost::inf();
561 for (size_t y = 0; y < edge.matrix.cols(); ++y)
562 cheapest = min(cheapest, add_normalized(neighbour_costs[y], edge.matrix[x, y]));
563 total += cheapest;
564 }
565 if (total < best_total) {
566 best_total = total;
567 best_option = x;
568 }
569 }
570 for (const auto& edge : reduction.edges) {
571 add_into(nodes_[edge.neighbour].costs.data(), edge.matrix.row(best_option), edge.matrix.cols());
572 normalize_node(edge.neighbour);
573 }
574 }
575
576 fe::Arena arena_;
577 fe::Arena scratch_;
578 fe::Vector<Node> nodes_;
579 fe::Vector<Edge> edges_;
580 fe::Vector<NodeId> low_;
581 fe::Vector<NodeId> dirty_;
582 fe::View<size_t> rn_priority_;
583 Statistics statistics_;
584 std::priority_queue<Candidate, fe::Vector<Candidate>> high_;
585 OptionId* forbidden_ = nullptr;
586 size_t forbidden_capacity_ = 0;
587};
588
589} // namespace
590
591Cost evaluate(const Graph& graph, fe::View<OptionId> choices) {
592 Cost total = 0;
593
594 for (const auto n : graph.nodes()) {
595 assert(n < choices.size() && "evaluate: choices is too short");
596 const auto costs = graph.node_costs(n);
597 assert(choices[n] < costs.size() && "evaluate: option index out of range");
598 total += costs[choices[n]];
599 }
600 for (const auto e : graph.edges()) {
601 const auto [src, dst] = graph.edge(e);
602 total += graph.edge_matrix(e)[choices[src], choices[dst]];
603 }
604 return total;
605}
606
607fe::Bitset conflicts(const Graph& graph, fe::View<OptionId> choices) {
608 fe::Bitset result;
609 for (const auto n : graph.nodes()) {
610 assert(n < choices.size() && "conflicts: choices is too short");
611 if (graph.node_costs(n)[choices[n]].is_inf()) result.set(n);
612 }
613 for (const auto e : graph.edges()) {
614 const auto [src, dst] = graph.edge(e);
615 if (graph.edge_matrix(e)[choices[src], choices[dst]].is_inf()) result.set(src).set(dst);
616 }
617 return result;
618}
619
620namespace {
621
622Solution finish(const Graph& graph, Solution solution) {
623 if (!solution.feasible()) solution.conflicts = conflicts(graph, solution.choices);
624 return solution;
625}
626
627} // namespace
628
629Solution solve(const Graph& graph, fe::View<size_t> rn_priority) {
630 Reducer reducer{graph, rn_priority};
631 fe::Vector<Subst> stack;
632 stack.reserve(graph.num_nodes());
633
634 for (NodeId n = reducer.next(); n != Graph::npos; n = reducer.next())
635 reducer.reduce(n, stack);
636
637 Choices choices(graph.num_nodes(), 0);
638 for (const auto& subst : std::views::reverse(stack))
639 choices[subst.node] = reducer.choose(subst, choices);
640
641 const Cost cost = evaluate(graph, choices);
642 return finish(
643 graph,
644 Solution{.choices = std::move(choices), .cost = cost, .conflicts = {}, .statistics = reducer.statistics()});
645}
646
647namespace {
648
649/// Mixed-radix layout of the assignment space; digit n belongs to node n.
650struct Enumeration {
651 fe::Vector<size_t, 16> options;
652 size_t combinations = 1;
653};
654
655std::optional<Enumeration> make_enumeration(const Graph& graph, size_t max_combinations) {
656 Enumeration enumeration;
657 for (const auto n : graph.nodes())
658 enumeration.options.emplace_back(graph.num_options(n));
659 for (const auto options : enumeration.options) {
660 if (enumeration.combinations > max_combinations / options) return std::nullopt;
661 enumeration.combinations *= options;
662 }
663 return enumeration;
664}
665
666/// The smallest index wins ties so that the result does not depend on the partitioning.
667Solution search_range(const Graph& graph, const Enumeration& enumeration, size_t begin, size_t end) {
668 Choices choices(enumeration.options.size(), 0);
669 for (size_t n = 0, rest = begin; n < choices.size(); ++n) {
670 choices[n] = rest % enumeration.options[n];
671 rest /= enumeration.options[n];
672 }
673
674 auto best = Solution{.choices = choices, .cost = Cost::inf(), .conflicts = {}, .statistics = {}};
675 for (size_t index = begin; index < end; ++index) {
676 const auto cost = evaluate(graph, choices);
677 if (cost < best.cost) {
678 best.choices = choices;
679 best.cost = cost;
680 }
681 for (NodeId n = 0; n < choices.size(); ++n) {
682 if (++choices[n] < enumeration.options[n]) break;
683 choices[n] = 0;
684 }
685 }
686 return best;
687}
688
689} // namespace
690
691std::optional<Solution> solve_exhaustive(const Graph& graph, size_t max_combinations, unsigned num_threads) {
692 const auto made = make_enumeration(graph, max_combinations);
693 if (!made) return std::nullopt;
694 const Enumeration& enumeration = *made;
695 if (enumeration.options.empty()) return Solution{};
696
697 unsigned requested = num_threads;
698 if (requested == 0) requested = std::thread::hardware_concurrency();
699 if (requested == 0) requested = 1;
700 const size_t workers = std::min<size_t>(requested, enumeration.combinations);
701
702 if (workers <= 1) return finish(graph, search_range(graph, enumeration, 0, enumeration.combinations));
703
704 fe::Vector<Solution> partials(workers);
705 {
706 fe::Vector<std::jthread> threads;
707 threads.reserve(workers);
708
709 const size_t base = enumeration.combinations / workers;
710 const size_t extra = enumeration.combinations % workers;
711 size_t begin = 0;
712 for (size_t i = 0; i < workers; ++i) {
713 const size_t end = begin + base + (i < extra ? 1 : 0);
714 threads.emplace_back([&graph, &enumeration, &partials, i, begin, end] {
715 partials[i] = search_range(graph, enumeration, begin, end);
716 });
717 begin = end;
718 }
719 }
720
721 // Ranges ascend, so the first minimum is the one with the smallest index.
722 return finish(graph, std::move(*std::ranges::min_element(partials, {}, &Solution::cost)));
723}
724
725} // namespace pbqp
constexpr BasicMatrix transposed() const
Definition graph.h:94
constexpr T * data() const
Definition graph.h:99
A saturating cost; Cost::inf forbids an option or option pair.
Definition graph.h:31
static constexpr Cost inf()
Definition graph.h:39
int32_t Rep
Definition graph.h:33
A PBQP problem graph.
Definition graph.h:252
Ends edge(EdgeId e) const
Definition graph.h:303
static constexpr EdgeId npos
Definition graph.h:259
size_t num_nodes() const
Definition graph.h:312
MatrixView edge_matrix(EdgeId e) const
Row-major with the src option as the row.
Definition graph.h:287
fe::View< Cost > node_costs(NodeId n) const
Definition graph.h:284
auto nodes() const
All node ids.
Definition graph.h:309
auto edges() const
All edge ids.
Definition graph.h:310
u32 cost(const App *app)
The cost of the instruction app: its latency plus one, so of two equally fast covers the shorter wins...
Definition insn.h:24
Definition dot.h:9
size_t OptionId
Index of an option within a node's cost vector.
Definition graph.h:27
BasicMatrix< const Cost > MatrixView
Definition graph.h:186
fe::Vector< OptionId, 8 > Choices
One option per node, indexed by node id.
Definition graph.h:68
fe::Vector< EdgeId, 4 > Edges
Definition graph.h:67
Solution solve(const Graph &graph, fe::View< size_t > rn_priority={})
Heuristic PBQP solver.
Definition solver.cpp:629
Cost evaluate(const Graph &graph, fe::View< OptionId > choices)
All solver functions are safe to call concurrently on a graph that nobody mutates meanwhile.
Definition solver.cpp:591
fe::Bitset conflicts(const Graph &graph, fe::View< OptionId > choices)
Nodes whose choice is Cost::inf in their cost vector or, given the neighbour's choice,...
Definition solver.cpp:607
fe::Vector< Cost, 4 > Costs
Definition graph.h:66
std::optional< Solution > solve_exhaustive(const Graph &graph, size_t max_combinations=10 '000 '000, unsigned num_threads=0)
Brute-force optimum, useful to cross-check small instances.
Definition solver.cpp:691
size_t EdgeId
Identifier of an edge in a Graph.
Definition graph.h:26
size_t NodeId
Identifier of a node in a Graph.
Definition graph.h:25
BasicMatrix< Cost > MatrixSpan
Definition graph.h:185
#define PBQP_DISPATCH
Definition solver.cpp:31
A complete assignment of options to nodes.
Definition solver.h:27
Cost cost
Total cost of the assignment under the original graph.
Definition solver.h:31