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