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