16#include <fe/container.h>
19#if defined(__SANITIZE_THREAD__)
21#elif defined(__has_feature)
22# if __has_feature(thread_sanitizer)
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")))
38Cost min(Cost lhs, Cost rhs) {
return lhs.value() < rhs.value() ? lhs : rhs; }
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())));
47Cost sub_normalized(Cost value, Cost minimum) {
48 if (minimum.is_inf())
return 0;
50 return static_cast<Cost::Rep>(std::min<int64_t>(int64_t{value.value()} - minimum.value(),
Cost::inf().value()));
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]);
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]));
63MatrixSpan allocate_matrix(fe::Arena& arena,
size_t rows,
size_t cols) {
64 return {arena.allocate<Cost>(rows * cols), rows, cols};
75 fe::View<TrimmedEdge> edges;
82 const OptionId* neighbour_working =
nullptr;
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;
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);
113 for (
EdgeId e = 0; e < edges_.size(); ++e)
115 for (
const auto n : graph.nodes()) {
121 [[nodiscard]]
const Statistics& statistics()
const {
return statistics_; }
125 while (!dirty_.empty()) {
126 const NodeId n = dirty_.back();
128 nodes_[n].dirty =
false;
129 if (nodes_[n].alive) prune(n);
131 while (!low_.empty()) {
132 const NodeId n = low_.back();
134 if (nodes_[n].alive)
return n;
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;
144 void reduce(
NodeId n, fe::Vector<Subst>& stack) {
145 if (degree(n) > 2 && options(n) > 1) {
147 while (merge_neighbour(n, stack))
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;
161 fold_into_neighbour(reduction);
168 ++(options(n) == 1 ? statistics_.single_option : statistics_.rn);
169 fold_locally_best_option(reduction);
172 scratch_.deallocate(mark);
177 [[nodiscard]]
OptionId choose(
const Subst& subst,
const Choices& choices)
const {
178 const auto original = [&](
OptionId x) {
return subst.original ? subst.original[x] : x; };
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];
191 if (total < best_total) {
202 fe::Vector<OptionId, 4> original;
205 size_t original_options = 0;
215 const Cost* shared =
nullptr;
216 Cost* owned =
nullptr;
226 auto operator<=>(
const Candidate&)
const =
default;
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(); }
233 const Edge& edge = edges_[e];
234 return {edge.owned !=
nullptr ? edge.owned : edge.shared, options(edge.src), options(edge.dst)};
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)};
245 return edges_[e].src == from ? view(e) : view(e).transposed();
249 return edges_[e].src == from ? writable(e) : writable(e).transposed();
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)));
260 Node& node = nodes_[n];
262 if (!node.dirty) dirty_.emplace_back(n);
264 if (degree(n) <= 2 || options(n) == 1) {
265 if (!node.low) low_.emplace_back(n);
268 high_.push(Candidate{.priority = rn_priority_.empty() ? 0 : rn_priority_[n],
270 .score = rn_score(n),
272 .version = node.version});
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);
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();
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;
299 for (
size_t c = 0; c < cols; ++c)
300 matrix[r, c] = sub_normalized(matrix[r, c], minimum);
302 const auto mark = scratch_.state();
303 Cost*
const minima = scratch_.allocate<Cost>(cols);
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];
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]);
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;
324 return edges_[e].src == n ? edges_[e].dst : edges_[e].src;
328 void erase_options(
NodeId n, fe::View<OptionId> options) {
329 Node& node = nodes_[n];
330 for (
const auto e : node.edges) {
332 matrix.erase_rows(options);
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);
339 node.working =
nullptr;
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;
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});
357 const Edges incident = nodes_[n].edges;
358 for (
const auto e : incident)
362 for (
const auto e : incident) {
363 normalize_node(other_end(e, n));
364 touch(other_end(e, n));
369 Node& node = nodes_[n];
370 if (node.original.size() == node.original_options || node.working !=
nullptr)
return node.working;
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;
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)};
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,
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);
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;
405 void remove_node(
NodeId n) {
406 Node& node = nodes_[n];
407 const Edges incident = std::move(node.edges);
410 for (
const auto e : incident) {
411 const NodeId other = other_end(e, n);
412 erase(nodes_[other].edges, e);
418 [[nodiscard]] TrimmedEdge trim_edge(
EdgeId e,
NodeId from) {
419 const NodeId other = other_end(e, from);
421 if (matrix.row_major())
return {.neighbour = other, .matrix = matrix};
423 const MatrixSpan copy = allocate_matrix(scratch_, matrix.rows(), matrix.cols());
424 copy.copy_from(matrix);
425 return {.neighbour = other, .matrix = copy};
428 [[nodiscard]] Reduction snapshot(
NodeId n,
const Subst& subst) {
429 return {.costs = subst.costs,
431 = scratch_.copy(nodes_[n].edges | std::views::transform([&](
EdgeId e) {
return trim_edge(e, n); }))};
435 void fold_into_neighbour(
const Reduction& reduction) {
436 const TrimmedEdge& edge = reduction.edges.front();
437 const size_t y_dim = edge.matrix.cols();
439 Cost*
const best = scratch_.allocate<Cost>(y_dim);
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);
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);
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();
457 const auto state = arena_.state();
458 const MatrixSpan merged = allocate_matrix(arena_, m_dim, n_dim);
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);
465 add_to_edge(e, to_m->neighbour, to_n->neighbour, merged, state);
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));
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");
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();
487 add_into(edges_[e].owned, matrix.data(), matrix.size());
488 arena_.deallocate(state);
498 const Costs& m_costs = nodes_[other_end(e, n)].costs;
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;
513 bool merge_neighbour(
NodeId n, fe::Vector<Subst>& stack) {
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);
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);
530 const EdgeId to_n_w = find_edge(n, w);
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)
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);
544 scratch_.deallocate(mark);
553 void fold_locally_best_option(
const Reduction& reduction) {
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;
561 for (
size_t y = 0; y < edge.matrix.cols(); ++y)
562 cheapest = min(cheapest, add_normalized(neighbour_costs[y], edge.matrix[x, y]));
565 if (total < best_total) {
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);
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_;
586 size_t forbidden_capacity_ = 0;
594 for (
const auto n : graph.
nodes()) {
595 assert(n < choices.size() &&
"evaluate: choices is too short");
597 assert(choices[n] < costs.size() &&
"evaluate: option index out of range");
598 total += costs[choices[n]];
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]];
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);
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);
622Solution finish(
const Graph& graph, Solution solution) {
623 if (!solution.feasible()) solution.conflicts = conflicts(graph, solution.choices);
630 Reducer reducer{graph, rn_priority};
631 fe::Vector<Subst> stack;
635 reducer.reduce(n, stack);
638 for (
const auto& subst : std::views::reverse(stack))
639 choices[subst.node] = reducer.choose(subst, choices);
644 Solution{.choices = std::move(choices), .cost = cost, .conflicts = {}, .statistics = reducer.statistics()});
651 fe::Vector<size_t, 16> options;
652 size_t combinations = 1;
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;
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];
674 auto best = Solution{.choices = choices, .cost = Cost::inf(), .conflicts = {}, .statistics = {}};
675 for (
size_t index = begin;
index < end; ++
index) {
677 if (cost < best.cost) {
678 best.choices = choices;
681 for (NodeId n = 0; n < choices.size(); ++n) {
682 if (++choices[n] < enumeration.options[n])
break;
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{};
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);
702 if (workers <= 1)
return finish(graph, search_range(graph, enumeration, 0, enumeration.combinations));
704 fe::Vector<Solution> partials(workers);
706 fe::Vector<std::jthread> threads;
707 threads.reserve(workers);
709 const size_t base = enumeration.combinations / workers;
710 const size_t extra = enumeration.combinations % workers;
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);
722 return finish(graph, std::move(*std::ranges::min_element(partials, {}, &
Solution::cost)));
constexpr BasicMatrix transposed() const
constexpr T * data() const
A saturating cost; Cost::inf forbids an option or option pair.
static constexpr Cost inf()
Ends edge(EdgeId e) const
static constexpr EdgeId npos
MatrixView edge_matrix(EdgeId e) const
Row-major with the src option as the row.
fe::View< Cost > node_costs(NodeId n) const
auto nodes() const
All node ids.
auto edges() const
All edge ids.
u32 cost(const App *app)
The cost of the instruction app: its latency plus one, so of two equally fast covers the shorter wins...
size_t OptionId
Index of an option within a node's cost vector.
BasicMatrix< const Cost > MatrixView
fe::Vector< OptionId, 8 > Choices
One option per node, indexed by node id.
fe::Vector< EdgeId, 4 > Edges
Solution solve(const Graph &graph, fe::View< size_t > rn_priority={})
Heuristic PBQP solver.
Cost evaluate(const Graph &graph, fe::View< OptionId > choices)
All solver functions are safe to call concurrently on a graph that nobody mutates meanwhile.
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,...
fe::Vector< Cost, 4 > Costs
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.
size_t EdgeId
Identifier of an edge in a Graph.
size_t NodeId
Identifier of a node in a Graph.
BasicMatrix< Cost > MatrixSpan
A complete assignment of options to nodes.
Cost cost
Total cost of the assignment under the original graph.