1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
|
//===- BalancedPartitioning.cpp -------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements BalancedPartitioning, a recursive balanced graph
// partitioning algorithm.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/BalancedPartitioning.h"
#include "llvm/Config/llvm-config.h" // for LLVM_ENABLE_THREADS
#include "llvm/Support/Debug.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/ThreadPool.h"
using namespace llvm;
#define DEBUG_TYPE "balanced-partitioning"
void BPFunctionNode::dump(raw_ostream &OS) const {
OS << formatv("{{ID={0} Utilities={{{1:$[,]}} Bucket={2}}", Id,
make_range(UtilityNodes.begin(), UtilityNodes.end()), Bucket);
}
template <typename Func>
void BalancedPartitioning::BPThreadPool::async(Func &&F) {
#if LLVM_ENABLE_THREADS
// This new thread could spawn more threads, so mark it as active
++NumActiveThreads;
TheThreadPool.async([this, F]() {
// Run the task
F();
// This thread will no longer spawn new threads, so mark it as inactive
if (--NumActiveThreads == 0) {
// There are no more active threads, so mark as finished and notify
{
std::unique_lock<std::mutex> lock(mtx);
assert(!IsFinishedSpawning);
IsFinishedSpawning = true;
}
cv.notify_one();
}
});
#else
llvm_unreachable("threads are disabled");
#endif
}
void BalancedPartitioning::BPThreadPool::wait() {
#if LLVM_ENABLE_THREADS
// TODO: We could remove the mutex and condition variable and use
// std::atomic::wait() instead, but that isn't available until C++20
{
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [&]() { return IsFinishedSpawning; });
assert(IsFinishedSpawning && NumActiveThreads == 0);
}
// Now we can call ThreadPool::wait() since all tasks have been submitted
TheThreadPool.wait();
#else
llvm_unreachable("threads are disabled");
#endif
}
BalancedPartitioning::BalancedPartitioning(
const BalancedPartitioningConfig &Config)
: Config(Config) {
// Pre-computing log2 values
Log2Cache[0] = 0.0;
for (unsigned I = 1; I < LOG_CACHE_SIZE; I++)
Log2Cache[I] = std::log2(I);
}
void BalancedPartitioning::run(std::vector<BPFunctionNode> &Nodes) const {
LLVM_DEBUG(
dbgs() << format(
"Partitioning %d nodes using depth %d and %d iterations per split\n",
Nodes.size(), Config.SplitDepth, Config.IterationsPerSplit));
std::optional<BPThreadPool> TP;
#if LLVM_ENABLE_THREADS
DefaultThreadPool TheThreadPool;
if (Config.TaskSplitDepth > 1)
TP.emplace(TheThreadPool);
#endif
// Record the input order
for (unsigned I = 0; I < Nodes.size(); I++)
Nodes[I].InputOrderIndex = I;
auto NodesRange = llvm::make_range(Nodes.begin(), Nodes.end());
auto BisectTask = [this, NodesRange, &TP]() {
bisect(NodesRange, /*RecDepth=*/0, /*RootBucket=*/1, /*Offset=*/0, TP);
};
if (TP) {
TP->async(std::move(BisectTask));
TP->wait();
} else {
BisectTask();
}
llvm::stable_sort(NodesRange, [](const auto &L, const auto &R) {
return L.Bucket < R.Bucket;
});
LLVM_DEBUG(dbgs() << "Balanced partitioning completed\n");
}
void BalancedPartitioning::bisect(const FunctionNodeRange Nodes,
unsigned RecDepth, unsigned RootBucket,
unsigned Offset,
std::optional<BPThreadPool> &TP) const {
unsigned NumNodes = std::distance(Nodes.begin(), Nodes.end());
if (NumNodes <= 1 || RecDepth >= Config.SplitDepth) {
// We've reach the lowest level of the recursion tree. Fall back to the
// original order and assign to buckets.
llvm::sort(Nodes, [](const auto &L, const auto &R) {
return L.InputOrderIndex < R.InputOrderIndex;
});
for (auto &N : Nodes)
N.Bucket = Offset++;
return;
}
LLVM_DEBUG(dbgs() << format("Bisect with %d nodes and root bucket %d\n",
NumNodes, RootBucket));
std::mt19937 RNG(RootBucket);
unsigned LeftBucket = 2 * RootBucket;
unsigned RightBucket = 2 * RootBucket + 1;
// Split into two and assign to the left and right buckets
split(Nodes, LeftBucket);
runIterations(Nodes, LeftBucket, RightBucket, RNG);
// Split nodes wrt the resulting buckets
auto NodesMid =
llvm::partition(Nodes, [&](auto &N) { return N.Bucket == LeftBucket; });
unsigned MidOffset = Offset + std::distance(Nodes.begin(), NodesMid);
auto LeftNodes = llvm::make_range(Nodes.begin(), NodesMid);
auto RightNodes = llvm::make_range(NodesMid, Nodes.end());
auto LeftRecTask = [this, LeftNodes, RecDepth, LeftBucket, Offset, &TP]() {
bisect(LeftNodes, RecDepth + 1, LeftBucket, Offset, TP);
};
auto RightRecTask = [this, RightNodes, RecDepth, RightBucket, MidOffset,
&TP]() {
bisect(RightNodes, RecDepth + 1, RightBucket, MidOffset, TP);
};
if (TP && RecDepth < Config.TaskSplitDepth && NumNodes >= 4) {
TP->async(std::move(LeftRecTask));
TP->async(std::move(RightRecTask));
} else {
LeftRecTask();
RightRecTask();
}
}
void BalancedPartitioning::runIterations(const FunctionNodeRange Nodes,
unsigned LeftBucket,
unsigned RightBucket,
std::mt19937 &RNG) const {
unsigned NumNodes = std::distance(Nodes.begin(), Nodes.end());
DenseMap<BPFunctionNode::UtilityNodeT, unsigned> UtilityNodeIndex;
for (auto &N : Nodes)
for (auto &UN : N.UtilityNodes)
++UtilityNodeIndex[UN];
// Remove utility nodes if they have just one edge or are connected to all
// functions
for (auto &N : Nodes)
llvm::erase_if(N.UtilityNodes, [&](auto &UN) {
unsigned UNI = UtilityNodeIndex[UN];
return UNI == 1 || UNI == NumNodes;
});
// Renumber utility nodes so they can be used to index into Signatures
UtilityNodeIndex.clear();
for (auto &N : Nodes)
for (auto &UN : N.UtilityNodes)
UN = UtilityNodeIndex.insert({UN, UtilityNodeIndex.size()}).first->second;
// Initialize signatures
SignaturesT Signatures(/*Size=*/UtilityNodeIndex.size());
for (auto &N : Nodes) {
for (auto &UN : N.UtilityNodes) {
assert(UN < Signatures.size());
if (N.Bucket == LeftBucket) {
Signatures[UN].LeftCount++;
} else {
Signatures[UN].RightCount++;
}
}
}
for (unsigned I = 0; I < Config.IterationsPerSplit; I++) {
unsigned NumMovedNodes =
runIteration(Nodes, LeftBucket, RightBucket, Signatures, RNG);
if (NumMovedNodes == 0)
break;
}
}
unsigned BalancedPartitioning::runIteration(const FunctionNodeRange Nodes,
unsigned LeftBucket,
unsigned RightBucket,
SignaturesT &Signatures,
std::mt19937 &RNG) const {
// Init signature cost caches
for (auto &Signature : Signatures) {
if (Signature.CachedGainIsValid)
continue;
unsigned L = Signature.LeftCount;
unsigned R = Signature.RightCount;
assert((L > 0 || R > 0) && "incorrect signature");
float Cost = logCost(L, R);
Signature.CachedGainLR = 0.f;
Signature.CachedGainRL = 0.f;
if (L > 0)
Signature.CachedGainLR = Cost - logCost(L - 1, R + 1);
if (R > 0)
Signature.CachedGainRL = Cost - logCost(L + 1, R - 1);
Signature.CachedGainIsValid = true;
}
// Compute move gains
typedef std::pair<float, BPFunctionNode *> GainPair;
std::vector<GainPair> Gains;
for (auto &N : Nodes) {
bool FromLeftToRight = (N.Bucket == LeftBucket);
float Gain = moveGain(N, FromLeftToRight, Signatures);
Gains.push_back(std::make_pair(Gain, &N));
}
// Collect left and right gains
auto LeftEnd = llvm::partition(
Gains, [&](const auto &GP) { return GP.second->Bucket == LeftBucket; });
auto LeftRange = llvm::make_range(Gains.begin(), LeftEnd);
auto RightRange = llvm::make_range(LeftEnd, Gains.end());
// Sort gains in descending order
auto LargerGain = [](const auto &L, const auto &R) {
return L.first > R.first;
};
llvm::stable_sort(LeftRange, LargerGain);
llvm::stable_sort(RightRange, LargerGain);
unsigned NumMovedDataVertices = 0;
for (auto [LeftPair, RightPair] : llvm::zip(LeftRange, RightRange)) {
auto &[LeftGain, LeftNode] = LeftPair;
auto &[RightGain, RightNode] = RightPair;
// Stop when the gain is no longer beneficial
if (LeftGain + RightGain <= 0.f)
break;
// Try to exchange the nodes between buckets
if (moveFunctionNode(*LeftNode, LeftBucket, RightBucket, Signatures, RNG))
++NumMovedDataVertices;
if (moveFunctionNode(*RightNode, LeftBucket, RightBucket, Signatures, RNG))
++NumMovedDataVertices;
}
return NumMovedDataVertices;
}
bool BalancedPartitioning::moveFunctionNode(BPFunctionNode &N,
unsigned LeftBucket,
unsigned RightBucket,
SignaturesT &Signatures,
std::mt19937 &RNG) const {
// Sometimes we skip the move. This helps to escape local optima
if (std::uniform_real_distribution<float>(0.f, 1.f)(RNG) <=
Config.SkipProbability)
return false;
bool FromLeftToRight = (N.Bucket == LeftBucket);
// Update the current bucket
N.Bucket = (FromLeftToRight ? RightBucket : LeftBucket);
// Update signatures and invalidate gain cache
if (FromLeftToRight) {
for (auto &UN : N.UtilityNodes) {
auto &Signature = Signatures[UN];
Signature.LeftCount--;
Signature.RightCount++;
Signature.CachedGainIsValid = false;
}
} else {
for (auto &UN : N.UtilityNodes) {
auto &Signature = Signatures[UN];
Signature.LeftCount++;
Signature.RightCount--;
Signature.CachedGainIsValid = false;
}
}
return true;
}
void BalancedPartitioning::split(const FunctionNodeRange Nodes,
unsigned StartBucket) const {
unsigned NumNodes = std::distance(Nodes.begin(), Nodes.end());
auto NodesMid = Nodes.begin() + (NumNodes + 1) / 2;
llvm::sort(Nodes.begin(), Nodes.end(), [](auto &L, auto &R) {
return L.InputOrderIndex < R.InputOrderIndex;
});
for (auto &N : llvm::make_range(Nodes.begin(), NodesMid))
N.Bucket = StartBucket;
for (auto &N : llvm::make_range(NodesMid, Nodes.end()))
N.Bucket = StartBucket + 1;
}
float BalancedPartitioning::moveGain(const BPFunctionNode &N,
bool FromLeftToRight,
const SignaturesT &Signatures) {
float Gain = 0.f;
for (auto &UN : N.UtilityNodes)
Gain += (FromLeftToRight ? Signatures[UN].CachedGainLR
: Signatures[UN].CachedGainRL);
return Gain;
}
float BalancedPartitioning::logCost(unsigned X, unsigned Y) const {
return -(X * log2Cached(X + 1) + Y * log2Cached(Y + 1));
}
float BalancedPartitioning::log2Cached(unsigned i) const {
return (i < LOG_CACHE_SIZE) ? Log2Cache[i] : std::log2(i);
}
|