1 //===- AsyncParallelFor.cpp - Implementation of Async Parallel For --------===// 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 scf.parallel to scf.for + async.execute conversion pass. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "PassDetail.h" 14 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h" 15 #include "mlir/Dialect/Async/IR/Async.h" 16 #include "mlir/Dialect/Async/Passes.h" 17 #include "mlir/Dialect/SCF/SCF.h" 18 #include "mlir/Dialect/StandardOps/IR/Ops.h" 19 #include "mlir/IR/BlockAndValueMapping.h" 20 #include "mlir/IR/ImplicitLocOpBuilder.h" 21 #include "mlir/IR/PatternMatch.h" 22 #include "mlir/Transforms/GreedyPatternRewriteDriver.h" 23 #include "mlir/Transforms/RegionUtils.h" 24 25 using namespace mlir; 26 using namespace mlir::async; 27 28 #define DEBUG_TYPE "async-parallel-for" 29 30 namespace { 31 32 // Rewrite scf.parallel operation into multiple concurrent async.execute 33 // operations over non overlapping subranges of the original loop. 34 // 35 // Example: 36 // 37 // scf.parallel (%i, %j) = (%lbi, %lbj) to (%ubi, %ubj) step (%si, %sj) { 38 // "do_some_compute"(%i, %j): () -> () 39 // } 40 // 41 // Converted to: 42 // 43 // // Parallel compute function that executes the parallel body region for 44 // // a subset of the parallel iteration space defined by the one-dimensional 45 // // compute block index. 46 // func parallel_compute_function(%block_index : index, %block_size : index, 47 // <parallel operation properties>, ...) { 48 // // Compute multi-dimensional loop bounds for %block_index. 49 // %block_lbi, %block_lbj = ... 50 // %block_ubi, %block_ubj = ... 51 // 52 // // Clone parallel operation body into the scf.for loop nest. 53 // scf.for %i = %blockLbi to %blockUbi { 54 // scf.for %j = block_lbj to %block_ubj { 55 // "do_some_compute"(%i, %j): () -> () 56 // } 57 // } 58 // } 59 // 60 // And a dispatch function depending on the `asyncDispatch` option. 61 // 62 // When async dispatch is on: (pseudocode) 63 // 64 // %block_size = ... compute parallel compute block size 65 // %block_count = ... compute the number of compute blocks 66 // 67 // func @async_dispatch(%block_start : index, %block_end : index, ...) { 68 // // Keep splitting block range until we reached a range of size 1. 69 // while (%block_end - %block_start > 1) { 70 // %mid_index = block_start + (block_end - block_start) / 2; 71 // async.execute { call @async_dispatch(%mid_index, %block_end); } 72 // %block_end = %mid_index 73 // } 74 // 75 // // Call parallel compute function for a single block. 76 // call @parallel_compute_fn(%block_start, %block_size, ...); 77 // } 78 // 79 // // Launch async dispatch for [0, block_count) range. 80 // call @async_dispatch(%c0, %block_count); 81 // 82 // When async dispatch is off: 83 // 84 // %block_size = ... compute parallel compute block size 85 // %block_count = ... compute the number of compute blocks 86 // 87 // scf.for %block_index = %c0 to %block_count { 88 // call @parallel_compute_fn(%block_index, %block_size, ...) 89 // } 90 // 91 struct AsyncParallelForPass 92 : public AsyncParallelForBase<AsyncParallelForPass> { 93 AsyncParallelForPass() = default; 94 95 AsyncParallelForPass(bool asyncDispatch, int32_t numWorkerThreads, 96 int32_t minTaskSize) { 97 this->asyncDispatch = asyncDispatch; 98 this->numWorkerThreads = numWorkerThreads; 99 this->minTaskSize = minTaskSize; 100 } 101 102 void runOnOperation() override; 103 }; 104 105 struct AsyncParallelForRewrite : public OpRewritePattern<scf::ParallelOp> { 106 public: 107 AsyncParallelForRewrite(MLIRContext *ctx, bool asyncDispatch, 108 int32_t numWorkerThreads, int32_t minTaskSize) 109 : OpRewritePattern(ctx), asyncDispatch(asyncDispatch), 110 numWorkerThreads(numWorkerThreads), minTaskSize(minTaskSize) {} 111 112 LogicalResult matchAndRewrite(scf::ParallelOp op, 113 PatternRewriter &rewriter) const override; 114 115 private: 116 bool asyncDispatch; 117 int32_t numWorkerThreads; 118 int32_t minTaskSize; 119 }; 120 121 struct ParallelComputeFunctionType { 122 FunctionType type; 123 llvm::SmallVector<Value> captures; 124 }; 125 126 struct ParallelComputeFunction { 127 FuncOp func; 128 llvm::SmallVector<Value> captures; 129 }; 130 131 } // namespace 132 133 // Converts one-dimensional iteration index in the [0, tripCount) interval 134 // into multidimensional iteration coordinate. 135 static SmallVector<Value> delinearize(ImplicitLocOpBuilder &b, Value index, 136 ArrayRef<Value> tripCounts) { 137 SmallVector<Value> coords(tripCounts.size()); 138 assert(!tripCounts.empty() && "tripCounts must be not empty"); 139 140 for (ssize_t i = tripCounts.size() - 1; i >= 0; --i) { 141 coords[i] = b.create<arith::RemSIOp>(index, tripCounts[i]); 142 index = b.create<arith::DivSIOp>(index, tripCounts[i]); 143 } 144 145 return coords; 146 } 147 148 // Returns a function type and implicit captures for a parallel compute 149 // function. We'll need a list of implicit captures to setup block and value 150 // mapping when we'll clone the body of the parallel operation. 151 static ParallelComputeFunctionType 152 getParallelComputeFunctionType(scf::ParallelOp op, PatternRewriter &rewriter) { 153 // Values implicitly captured by the parallel operation. 154 llvm::SetVector<Value> captures; 155 getUsedValuesDefinedAbove(op.region(), op.region(), captures); 156 157 llvm::SmallVector<Type> inputs; 158 inputs.reserve(2 + 4 * op.getNumLoops() + captures.size()); 159 160 Type indexTy = rewriter.getIndexType(); 161 162 // One-dimensional iteration space defined by the block index and size. 163 inputs.push_back(indexTy); // blockIndex 164 inputs.push_back(indexTy); // blockSize 165 166 // Multi-dimensional parallel iteration space defined by the loop trip counts. 167 for (unsigned i = 0; i < op.getNumLoops(); ++i) 168 inputs.push_back(indexTy); // loop tripCount 169 170 // Parallel operation lower bound, upper bound and step. 171 for (unsigned i = 0; i < op.getNumLoops(); ++i) { 172 inputs.push_back(indexTy); // lower bound 173 inputs.push_back(indexTy); // upper bound 174 inputs.push_back(indexTy); // step 175 } 176 177 // Types of the implicit captures. 178 for (Value capture : captures) 179 inputs.push_back(capture.getType()); 180 181 // Convert captures to vector for later convenience. 182 SmallVector<Value> capturesVector(captures.begin(), captures.end()); 183 return {rewriter.getFunctionType(inputs, TypeRange()), capturesVector}; 184 } 185 186 // Create a parallel compute fuction from the parallel operation. 187 static ParallelComputeFunction 188 createParallelComputeFunction(scf::ParallelOp op, PatternRewriter &rewriter) { 189 OpBuilder::InsertionGuard guard(rewriter); 190 ImplicitLocOpBuilder b(op.getLoc(), rewriter); 191 192 ModuleOp module = op->getParentOfType<ModuleOp>(); 193 194 // Make sure that all constants will be inside the parallel operation body to 195 // reduce the number of parallel compute function arguments. 196 cloneConstantsIntoTheRegion(op.getLoopBody(), rewriter); 197 198 ParallelComputeFunctionType computeFuncType = 199 getParallelComputeFunctionType(op, rewriter); 200 201 FunctionType type = computeFuncType.type; 202 FuncOp func = FuncOp::create(op.getLoc(), "parallel_compute_fn", type); 203 func.setPrivate(); 204 205 // Insert function into the module symbol table and assign it unique name. 206 SymbolTable symbolTable(module); 207 symbolTable.insert(func); 208 rewriter.getListener()->notifyOperationInserted(func); 209 210 // Create function entry block. 211 Block *block = b.createBlock(&func.getBody(), func.begin(), type.getInputs()); 212 b.setInsertionPointToEnd(block); 213 214 unsigned offset = 0; // argument offset for arguments decoding 215 216 // Returns `numArguments` arguments starting from `offset` and updates offset 217 // by moving forward to the next argument. 218 auto getArguments = [&](unsigned numArguments) -> ArrayRef<Value> { 219 auto args = block->getArguments(); 220 auto slice = args.drop_front(offset).take_front(numArguments); 221 offset += numArguments; 222 return {slice.begin(), slice.end()}; 223 }; 224 225 // Block iteration position defined by the block index and size. 226 Value blockIndex = block->getArgument(offset++); 227 Value blockSize = block->getArgument(offset++); 228 229 // Constants used below. 230 Value c0 = b.create<arith::ConstantIndexOp>(0); 231 Value c1 = b.create<arith::ConstantIndexOp>(1); 232 233 // Multi-dimensional parallel iteration space defined by the loop trip counts. 234 ArrayRef<Value> tripCounts = getArguments(op.getNumLoops()); 235 236 // Compute a product of trip counts to get the size of the flattened 237 // one-dimensional iteration space. 238 Value tripCount = tripCounts[0]; 239 for (unsigned i = 1; i < tripCounts.size(); ++i) 240 tripCount = b.create<arith::MulIOp>(tripCount, tripCounts[i]); 241 242 // Parallel operation lower bound and step. 243 ArrayRef<Value> lowerBound = getArguments(op.getNumLoops()); 244 offset += op.getNumLoops(); // skip upper bound arguments 245 ArrayRef<Value> step = getArguments(op.getNumLoops()); 246 247 // Remaining arguments are implicit captures of the parallel operation. 248 ArrayRef<Value> captures = getArguments(block->getNumArguments() - offset); 249 250 // Find one-dimensional iteration bounds: [blockFirstIndex, blockLastIndex]: 251 // blockFirstIndex = blockIndex * blockSize 252 Value blockFirstIndex = b.create<arith::MulIOp>(blockIndex, blockSize); 253 254 // The last one-dimensional index in the block defined by the `blockIndex`: 255 // blockLastIndex = min(blockFirstIndex + blockSize, tripCount) - 1 256 Value blockEnd0 = b.create<arith::AddIOp>(blockFirstIndex, blockSize); 257 Value blockEnd1 = b.create<arith::MinSIOp>(blockEnd0, tripCount); 258 Value blockLastIndex = b.create<arith::SubIOp>(blockEnd1, c1); 259 260 // Convert one-dimensional indices to multi-dimensional coordinates. 261 auto blockFirstCoord = delinearize(b, blockFirstIndex, tripCounts); 262 auto blockLastCoord = delinearize(b, blockLastIndex, tripCounts); 263 264 // Compute loops upper bounds derived from the block last coordinates: 265 // blockEndCoord[i] = blockLastCoord[i] + 1 266 // 267 // Block first and last coordinates can be the same along the outer compute 268 // dimension when inner compute dimension contains multiple blocks. 269 SmallVector<Value> blockEndCoord(op.getNumLoops()); 270 for (size_t i = 0; i < blockLastCoord.size(); ++i) 271 blockEndCoord[i] = b.create<arith::AddIOp>(blockLastCoord[i], c1); 272 273 // Construct a loop nest out of scf.for operations that will iterate over 274 // all coordinates in [blockFirstCoord, blockLastCoord] range. 275 using LoopBodyBuilder = 276 std::function<void(OpBuilder &, Location, Value, ValueRange)>; 277 using LoopNestBuilder = std::function<LoopBodyBuilder(size_t loopIdx)>; 278 279 // Parallel region induction variables computed from the multi-dimensional 280 // iteration coordinate using parallel operation bounds and step: 281 // 282 // computeBlockInductionVars[loopIdx] = 283 // lowerBound[loopIdx] + blockCoord[loopIdx] * step[loopIdx] 284 SmallVector<Value> computeBlockInductionVars(op.getNumLoops()); 285 286 // We need to know if we are in the first or last iteration of the 287 // multi-dimensional loop for each loop in the nest, so we can decide what 288 // loop bounds should we use for the nested loops: bounds defined by compute 289 // block interval, or bounds defined by the parallel operation. 290 // 291 // Example: 2d parallel operation 292 // i j 293 // loop sizes: [50, 50] 294 // first coord: [25, 25] 295 // last coord: [30, 30] 296 // 297 // If `i` is equal to 25 then iteration over `j` should start at 25, when `i` 298 // is between 25 and 30 it should start at 0. The upper bound for `j` should 299 // be 50, except when `i` is equal to 30, then it should also be 30. 300 // 301 // Value at ith position specifies if all loops in [0, i) range of the loop 302 // nest are in the first/last iteration. 303 SmallVector<Value> isBlockFirstCoord(op.getNumLoops()); 304 SmallVector<Value> isBlockLastCoord(op.getNumLoops()); 305 306 // Builds inner loop nest inside async.execute operation that does all the 307 // work concurrently. 308 LoopNestBuilder workLoopBuilder = [&](size_t loopIdx) -> LoopBodyBuilder { 309 return [&, loopIdx](OpBuilder &nestedBuilder, Location loc, Value iv, 310 ValueRange args) { 311 ImplicitLocOpBuilder nb(loc, nestedBuilder); 312 313 // Compute induction variable for `loopIdx`. 314 computeBlockInductionVars[loopIdx] = nb.create<arith::AddIOp>( 315 lowerBound[loopIdx], nb.create<arith::MulIOp>(iv, step[loopIdx])); 316 317 // Check if we are inside first or last iteration of the loop. 318 isBlockFirstCoord[loopIdx] = nb.create<arith::CmpIOp>( 319 arith::CmpIPredicate::eq, iv, blockFirstCoord[loopIdx]); 320 isBlockLastCoord[loopIdx] = nb.create<arith::CmpIOp>( 321 arith::CmpIPredicate::eq, iv, blockLastCoord[loopIdx]); 322 323 // Check if the previous loop is in its first or last iteration. 324 if (loopIdx > 0) { 325 isBlockFirstCoord[loopIdx] = nb.create<arith::AndIOp>( 326 isBlockFirstCoord[loopIdx], isBlockFirstCoord[loopIdx - 1]); 327 isBlockLastCoord[loopIdx] = nb.create<arith::AndIOp>( 328 isBlockLastCoord[loopIdx], isBlockLastCoord[loopIdx - 1]); 329 } 330 331 // Keep building loop nest. 332 if (loopIdx < op.getNumLoops() - 1) { 333 // Select nested loop lower/upper bounds depending on our position in 334 // the multi-dimensional iteration space. 335 auto lb = nb.create<SelectOp>(isBlockFirstCoord[loopIdx], 336 blockFirstCoord[loopIdx + 1], c0); 337 338 auto ub = nb.create<SelectOp>(isBlockLastCoord[loopIdx], 339 blockEndCoord[loopIdx + 1], 340 tripCounts[loopIdx + 1]); 341 342 nb.create<scf::ForOp>(lb, ub, c1, ValueRange(), 343 workLoopBuilder(loopIdx + 1)); 344 nb.create<scf::YieldOp>(loc); 345 return; 346 } 347 348 // Copy the body of the parallel op into the inner-most loop. 349 BlockAndValueMapping mapping; 350 mapping.map(op.getInductionVars(), computeBlockInductionVars); 351 mapping.map(computeFuncType.captures, captures); 352 353 for (auto &bodyOp : op.getLoopBody().getOps()) 354 nb.clone(bodyOp, mapping); 355 }; 356 }; 357 358 b.create<scf::ForOp>(blockFirstCoord[0], blockEndCoord[0], c1, ValueRange(), 359 workLoopBuilder(0)); 360 b.create<ReturnOp>(ValueRange()); 361 362 return {func, std::move(computeFuncType.captures)}; 363 } 364 365 // Creates recursive async dispatch function for the given parallel compute 366 // function. Dispatch function keeps splitting block range into halves until it 367 // reaches a single block, and then excecutes it inline. 368 // 369 // Function pseudocode (mix of C++ and MLIR): 370 // 371 // func @async_dispatch(%block_start : index, %block_end : index, ...) { 372 // 373 // // Keep splitting block range until we reached a range of size 1. 374 // while (%block_end - %block_start > 1) { 375 // %mid_index = block_start + (block_end - block_start) / 2; 376 // async.execute { call @async_dispatch(%mid_index, %block_end); } 377 // %block_end = %mid_index 378 // } 379 // 380 // // Call parallel compute function for a single block. 381 // call @parallel_compute_fn(%block_start, %block_size, ...); 382 // } 383 // 384 static FuncOp createAsyncDispatchFunction(ParallelComputeFunction &computeFunc, 385 PatternRewriter &rewriter) { 386 OpBuilder::InsertionGuard guard(rewriter); 387 Location loc = computeFunc.func.getLoc(); 388 ImplicitLocOpBuilder b(loc, rewriter); 389 390 ModuleOp module = computeFunc.func->getParentOfType<ModuleOp>(); 391 392 ArrayRef<Type> computeFuncInputTypes = 393 computeFunc.func.type().cast<FunctionType>().getInputs(); 394 395 // Compared to the parallel compute function async dispatch function takes 396 // additional !async.group argument. Also instead of a single `blockIndex` it 397 // takes `blockStart` and `blockEnd` arguments to define the range of 398 // dispatched blocks. 399 SmallVector<Type> inputTypes; 400 inputTypes.push_back(async::GroupType::get(rewriter.getContext())); 401 inputTypes.push_back(rewriter.getIndexType()); // add blockStart argument 402 inputTypes.append(computeFuncInputTypes.begin(), computeFuncInputTypes.end()); 403 404 FunctionType type = rewriter.getFunctionType(inputTypes, TypeRange()); 405 FuncOp func = FuncOp::create(loc, "async_dispatch_fn", type); 406 func.setPrivate(); 407 408 // Insert function into the module symbol table and assign it unique name. 409 SymbolTable symbolTable(module); 410 symbolTable.insert(func); 411 rewriter.getListener()->notifyOperationInserted(func); 412 413 // Create function entry block. 414 Block *block = b.createBlock(&func.getBody(), func.begin(), type.getInputs()); 415 b.setInsertionPointToEnd(block); 416 417 Type indexTy = b.getIndexType(); 418 Value c1 = b.create<arith::ConstantIndexOp>(1); 419 Value c2 = b.create<arith::ConstantIndexOp>(2); 420 421 // Get the async group that will track async dispatch completion. 422 Value group = block->getArgument(0); 423 424 // Get the block iteration range: [blockStart, blockEnd) 425 Value blockStart = block->getArgument(1); 426 Value blockEnd = block->getArgument(2); 427 428 // Create a work splitting while loop for the [blockStart, blockEnd) range. 429 SmallVector<Type> types = {indexTy, indexTy}; 430 SmallVector<Value> operands = {blockStart, blockEnd}; 431 432 // Create a recursive dispatch loop. 433 scf::WhileOp whileOp = b.create<scf::WhileOp>(types, operands); 434 Block *before = b.createBlock(&whileOp.before(), {}, types); 435 Block *after = b.createBlock(&whileOp.after(), {}, types); 436 437 // Setup dispatch loop condition block: decide if we need to go into the 438 // `after` block and launch one more async dispatch. 439 { 440 b.setInsertionPointToEnd(before); 441 Value start = before->getArgument(0); 442 Value end = before->getArgument(1); 443 Value distance = b.create<arith::SubIOp>(end, start); 444 Value dispatch = 445 b.create<arith::CmpIOp>(arith::CmpIPredicate::sgt, distance, c1); 446 b.create<scf::ConditionOp>(dispatch, before->getArguments()); 447 } 448 449 // Setup the async dispatch loop body: recursively call dispatch function 450 // for the seconds half of the original range and go to the next iteration. 451 { 452 b.setInsertionPointToEnd(after); 453 Value start = after->getArgument(0); 454 Value end = after->getArgument(1); 455 Value distance = b.create<arith::SubIOp>(end, start); 456 Value halfDistance = b.create<arith::DivSIOp>(distance, c2); 457 Value midIndex = b.create<arith::AddIOp>(start, halfDistance); 458 459 // Call parallel compute function inside the async.execute region. 460 auto executeBodyBuilder = [&](OpBuilder &executeBuilder, 461 Location executeLoc, ValueRange executeArgs) { 462 // Update the original `blockStart` and `blockEnd` with new range. 463 SmallVector<Value> operands{block->getArguments().begin(), 464 block->getArguments().end()}; 465 operands[1] = midIndex; 466 operands[2] = end; 467 468 executeBuilder.create<CallOp>(executeLoc, func.sym_name(), 469 func.getCallableResults(), operands); 470 executeBuilder.create<async::YieldOp>(executeLoc, ValueRange()); 471 }; 472 473 // Create async.execute operation to dispatch half of the block range. 474 auto execute = b.create<ExecuteOp>(TypeRange(), ValueRange(), ValueRange(), 475 executeBodyBuilder); 476 b.create<AddToGroupOp>(indexTy, execute.token(), group); 477 b.create<scf::YieldOp>(ValueRange({start, midIndex})); 478 } 479 480 // After dispatching async operations to process the tail of the block range 481 // call the parallel compute function for the first block of the range. 482 b.setInsertionPointAfter(whileOp); 483 484 // Drop async dispatch specific arguments: async group, block start and end. 485 auto forwardedInputs = block->getArguments().drop_front(3); 486 SmallVector<Value> computeFuncOperands = {blockStart}; 487 computeFuncOperands.append(forwardedInputs.begin(), forwardedInputs.end()); 488 489 b.create<CallOp>(computeFunc.func.sym_name(), 490 computeFunc.func.getCallableResults(), computeFuncOperands); 491 b.create<ReturnOp>(ValueRange()); 492 493 return func; 494 } 495 496 // Launch async dispatch of the parallel compute function. 497 static void doAsyncDispatch(ImplicitLocOpBuilder &b, PatternRewriter &rewriter, 498 ParallelComputeFunction ¶llelComputeFunction, 499 scf::ParallelOp op, Value blockSize, 500 Value blockCount, 501 const SmallVector<Value> &tripCounts) { 502 MLIRContext *ctx = op->getContext(); 503 504 // Add one more level of indirection to dispatch parallel compute functions 505 // using async operations and recursive work splitting. 506 FuncOp asyncDispatchFunction = 507 createAsyncDispatchFunction(parallelComputeFunction, rewriter); 508 509 Value c0 = b.create<arith::ConstantIndexOp>(0); 510 Value c1 = b.create<arith::ConstantIndexOp>(1); 511 512 // Appends operands shared by async dispatch and parallel compute functions to 513 // the given operands vector. 514 auto appendBlockComputeOperands = [&](SmallVector<Value> &operands) { 515 operands.append(tripCounts); 516 operands.append(op.lowerBound().begin(), op.lowerBound().end()); 517 operands.append(op.upperBound().begin(), op.upperBound().end()); 518 operands.append(op.step().begin(), op.step().end()); 519 operands.append(parallelComputeFunction.captures); 520 }; 521 522 // Check if the block size is one, in this case we can skip the async dispatch 523 // completely. If this will be known statically, then canonicalization will 524 // erase async group operations. 525 Value isSingleBlock = 526 b.create<arith::CmpIOp>(arith::CmpIPredicate::eq, blockCount, c1); 527 528 auto syncDispatch = [&](OpBuilder &nestedBuilder, Location loc) { 529 ImplicitLocOpBuilder nb(loc, nestedBuilder); 530 531 // Call parallel compute function for the single block. 532 SmallVector<Value> operands = {c0, blockSize}; 533 appendBlockComputeOperands(operands); 534 535 nb.create<CallOp>(parallelComputeFunction.func.sym_name(), 536 parallelComputeFunction.func.getCallableResults(), 537 operands); 538 nb.create<scf::YieldOp>(); 539 }; 540 541 auto asyncDispatch = [&](OpBuilder &nestedBuilder, Location loc) { 542 // Create an async.group to wait on all async tokens from the concurrent 543 // execution of multiple parallel compute function. First block will be 544 // executed synchronously in the caller thread. 545 Value groupSize = b.create<arith::SubIOp>(blockCount, c1); 546 Value group = b.create<CreateGroupOp>(GroupType::get(ctx), groupSize); 547 548 ImplicitLocOpBuilder nb(loc, nestedBuilder); 549 550 // Launch async dispatch function for [0, blockCount) range. 551 SmallVector<Value> operands = {group, c0, blockCount, blockSize}; 552 appendBlockComputeOperands(operands); 553 554 nb.create<CallOp>(asyncDispatchFunction.sym_name(), 555 asyncDispatchFunction.getCallableResults(), operands); 556 557 // Wait for the completion of all parallel compute operations. 558 b.create<AwaitAllOp>(group); 559 560 nb.create<scf::YieldOp>(); 561 }; 562 563 // Dispatch either single block compute function, or launch async dispatch. 564 b.create<scf::IfOp>(TypeRange(), isSingleBlock, syncDispatch, asyncDispatch); 565 } 566 567 // Dispatch parallel compute functions by submitting all async compute tasks 568 // from a simple for loop in the caller thread. 569 static void 570 doSequentialDispatch(ImplicitLocOpBuilder &b, PatternRewriter &rewriter, 571 ParallelComputeFunction ¶llelComputeFunction, 572 scf::ParallelOp op, Value blockSize, Value blockCount, 573 const SmallVector<Value> &tripCounts) { 574 MLIRContext *ctx = op->getContext(); 575 576 FuncOp compute = parallelComputeFunction.func; 577 578 Value c0 = b.create<arith::ConstantIndexOp>(0); 579 Value c1 = b.create<arith::ConstantIndexOp>(1); 580 581 // Create an async.group to wait on all async tokens from the concurrent 582 // execution of multiple parallel compute function. First block will be 583 // executed synchronously in the caller thread. 584 Value groupSize = b.create<arith::SubIOp>(blockCount, c1); 585 Value group = b.create<CreateGroupOp>(GroupType::get(ctx), groupSize); 586 587 // Call parallel compute function for all blocks. 588 using LoopBodyBuilder = 589 std::function<void(OpBuilder &, Location, Value, ValueRange)>; 590 591 // Returns parallel compute function operands to process the given block. 592 auto computeFuncOperands = [&](Value blockIndex) -> SmallVector<Value> { 593 SmallVector<Value> computeFuncOperands = {blockIndex, blockSize}; 594 computeFuncOperands.append(tripCounts); 595 computeFuncOperands.append(op.lowerBound().begin(), op.lowerBound().end()); 596 computeFuncOperands.append(op.upperBound().begin(), op.upperBound().end()); 597 computeFuncOperands.append(op.step().begin(), op.step().end()); 598 computeFuncOperands.append(parallelComputeFunction.captures); 599 return computeFuncOperands; 600 }; 601 602 // Induction variable is the index of the block: [0, blockCount). 603 LoopBodyBuilder loopBuilder = [&](OpBuilder &loopBuilder, Location loc, 604 Value iv, ValueRange args) { 605 ImplicitLocOpBuilder nb(loc, loopBuilder); 606 607 // Call parallel compute function inside the async.execute region. 608 auto executeBodyBuilder = [&](OpBuilder &executeBuilder, 609 Location executeLoc, ValueRange executeArgs) { 610 executeBuilder.create<CallOp>(executeLoc, compute.sym_name(), 611 compute.getCallableResults(), 612 computeFuncOperands(iv)); 613 executeBuilder.create<async::YieldOp>(executeLoc, ValueRange()); 614 }; 615 616 // Create async.execute operation to launch parallel computate function. 617 auto execute = nb.create<ExecuteOp>(TypeRange(), ValueRange(), ValueRange(), 618 executeBodyBuilder); 619 nb.create<AddToGroupOp>(rewriter.getIndexType(), execute.token(), group); 620 nb.create<scf::YieldOp>(); 621 }; 622 623 // Iterate over all compute blocks and launch parallel compute operations. 624 b.create<scf::ForOp>(c1, blockCount, c1, ValueRange(), loopBuilder); 625 626 // Call parallel compute function for the first block in the caller thread. 627 b.create<CallOp>(compute.sym_name(), compute.getCallableResults(), 628 computeFuncOperands(c0)); 629 630 // Wait for the completion of all async compute operations. 631 b.create<AwaitAllOp>(group); 632 } 633 634 LogicalResult 635 AsyncParallelForRewrite::matchAndRewrite(scf::ParallelOp op, 636 PatternRewriter &rewriter) const { 637 // We do not currently support rewrite for parallel op with reductions. 638 if (op.getNumReductions() != 0) 639 return failure(); 640 641 ImplicitLocOpBuilder b(op.getLoc(), rewriter); 642 643 // Compute trip count for each loop induction variable: 644 // tripCount = ceil_div(upperBound - lowerBound, step); 645 SmallVector<Value> tripCounts(op.getNumLoops()); 646 for (size_t i = 0; i < op.getNumLoops(); ++i) { 647 auto lb = op.lowerBound()[i]; 648 auto ub = op.upperBound()[i]; 649 auto step = op.step()[i]; 650 auto range = b.create<arith::SubIOp>(ub, lb); 651 tripCounts[i] = b.create<arith::CeilDivSIOp>(range, step); 652 } 653 654 // Compute a product of trip counts to get the 1-dimensional iteration space 655 // for the scf.parallel operation. 656 Value tripCount = tripCounts[0]; 657 for (size_t i = 1; i < tripCounts.size(); ++i) 658 tripCount = b.create<arith::MulIOp>(tripCount, tripCounts[i]); 659 660 // Short circuit no-op parallel loops (zero iterations) that can arise from 661 // the memrefs with dynamic dimension(s) equal to zero. 662 Value c0 = b.create<arith::ConstantIndexOp>(0); 663 Value isZeroIterations = 664 b.create<arith::CmpIOp>(arith::CmpIPredicate::eq, tripCount, c0); 665 666 // Do absolutely nothing if the trip count is zero. 667 auto noOp = [&](OpBuilder &nestedBuilder, Location loc) { 668 nestedBuilder.create<scf::YieldOp>(loc); 669 }; 670 671 // Compute the parallel block size and dispatch concurrent tasks computing 672 // results for each block. 673 auto dispatch = [&](OpBuilder &nestedBuilder, Location loc) { 674 ImplicitLocOpBuilder nb(loc, nestedBuilder); 675 676 // With large number of threads the value of creating many compute blocks 677 // is reduced because the problem typically becomes memory bound. For small 678 // number of threads it helps with stragglers. 679 float overshardingFactor = numWorkerThreads <= 4 ? 8.0 680 : numWorkerThreads <= 8 ? 4.0 681 : numWorkerThreads <= 16 ? 2.0 682 : numWorkerThreads <= 32 ? 1.0 683 : numWorkerThreads <= 64 ? 0.8 684 : 0.6; 685 686 // Do not overload worker threads with too many compute blocks. 687 Value maxComputeBlocks = b.create<arith::ConstantIndexOp>( 688 std::max(1, static_cast<int>(numWorkerThreads * overshardingFactor))); 689 690 // Target block size from the pass parameters. 691 Value minTaskSizeCst = b.create<arith::ConstantIndexOp>(minTaskSize); 692 693 // Compute parallel block size from the parallel problem size: 694 // blockSize = min(tripCount, 695 // max(ceil_div(tripCount, maxComputeBlocks), 696 // ceil_div(minTaskSize, bodySize))) 697 Value bs0 = b.create<arith::CeilDivSIOp>(tripCount, maxComputeBlocks); 698 Value bs1 = b.create<arith::MaxSIOp>(bs0, minTaskSizeCst); 699 Value blockSize = b.create<arith::MinSIOp>(tripCount, bs1); 700 Value blockCount = b.create<arith::CeilDivSIOp>(tripCount, blockSize); 701 702 // Create a parallel compute function that takes a block id and computes the 703 // parallel operation body for a subset of iteration space. 704 ParallelComputeFunction parallelComputeFunction = 705 createParallelComputeFunction(op, rewriter); 706 707 // Dispatch parallel compute function using async recursive work splitting, 708 // or by submitting compute task sequentially from a caller thread. 709 if (asyncDispatch) { 710 doAsyncDispatch(b, rewriter, parallelComputeFunction, op, blockSize, 711 blockCount, tripCounts); 712 } else { 713 doSequentialDispatch(b, rewriter, parallelComputeFunction, op, blockSize, 714 blockCount, tripCounts); 715 } 716 717 nb.create<scf::YieldOp>(); 718 }; 719 720 // Replace the `scf.parallel` operation with the parallel compute function. 721 b.create<scf::IfOp>(TypeRange(), isZeroIterations, noOp, dispatch); 722 723 // Parallel operation was replaced with a block iteration loop. 724 rewriter.eraseOp(op); 725 726 return success(); 727 } 728 729 void AsyncParallelForPass::runOnOperation() { 730 MLIRContext *ctx = &getContext(); 731 732 RewritePatternSet patterns(ctx); 733 patterns.add<AsyncParallelForRewrite>(ctx, asyncDispatch, numWorkerThreads, 734 minTaskSize); 735 736 if (failed(applyPatternsAndFoldGreedily(getOperation(), std::move(patterns)))) 737 signalPassFailure(); 738 } 739 740 std::unique_ptr<Pass> mlir::createAsyncParallelForPass() { 741 return std::make_unique<AsyncParallelForPass>(); 742 } 743 744 std::unique_ptr<Pass> mlir::createAsyncParallelForPass(bool asyncDispatch, 745 int32_t numWorkerThreads, 746 int32_t minTaskSize) { 747 return std::make_unique<AsyncParallelForPass>(asyncDispatch, numWorkerThreads, 748 minTaskSize); 749 } 750