1 //===- DropUnitDims.cpp - Pass to drop use of unit-extent for broadcasting ===// 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 patterns/pass to remove usage of unit-extent dimensions 10 // to specify broadcasting in favor of more canonical representation of the 11 // computation 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "PassDetail.h" 16 #include "mlir/Dialect/Linalg/IR/LinalgOps.h" 17 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h" 18 #include "mlir/Dialect/Linalg/Passes.h" 19 #include "mlir/Dialect/Linalg/Utils/Utils.h" 20 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h" 21 #include "mlir/IR/AffineExpr.h" 22 #include "mlir/IR/AffineMap.h" 23 #include "mlir/Transforms/FoldUtils.h" 24 #include "mlir/Transforms/GreedyPatternRewriteDriver.h" 25 #include "llvm/Support/CommandLine.h" 26 #include "llvm/Support/Debug.h" 27 28 #define DEBUG_TYPE "linalg-drop-unit-dims" 29 30 using namespace mlir; 31 using namespace mlir::edsc; 32 using namespace mlir::edsc::intrinsics; 33 using namespace mlir::linalg; 34 35 /// Implements a pass that canonicalizes the uses of unit-extent dimensions for 36 /// broadcasting. For example, 37 /// 38 /// ```mlir 39 /// #accesses = [ 40 /// affine_map<(d0, d1) -> (0, d1)>, 41 /// affine_map<(d0, d1) -> (d0, 0)>, 42 /// affine_map<(d0, d1) -> (d0, d1)> 43 /// ] 44 /// 45 /// #trait = { 46 /// args_in = 2, 47 /// args_out = 1, 48 /// indexing_maps = #accesses, 49 /// iterator_types = ["parallel", "parallel"], 50 /// library_call = "some_external_fn" 51 /// } 52 /// 53 /// func @broadcast_test(%arg0 : tensor<5xf32>, %arg1 : tensor<5xf32>) -> 54 /// tensor<5x5xf32> 55 /// { 56 /// %0 = linalg.tensor_reshape %arg0 [affine_map<(d0, d1) -> (d0, d1)>] : 57 /// tensor<5xf32> into tensor<1x5xf32> 58 /// %1 = linalg.tensor_reshape %arg1 [affine_map<(d0, d1) -> (d0, d1)>] : 59 /// tensor<5xf32> into tensor<5x1xf32> 60 /// %2 = linalg.generic #trait %0, %1 { 61 /// ^bb0(%arg2: f32, %arg3: f32): 62 /// %3 = addf %arg2, %arg3 : f32 63 /// linalg.yield %3 : f32 64 /// } : tensor<1x5xf32>, tensor<5x1xf32> -> tensor<5x5xf32> 65 /// return %2 : tensor<5x5xf32> 66 /// } 67 /// 68 /// would canonicalize to 69 /// 70 /// ```mlir 71 /// #accesses = [ 72 /// affine_map<(d0, d1) -> (d1)>, 73 /// affine_map<(d0, d1) -> (d0)>, 74 /// affine_map<(d0, d1) -> (d0, d1)> 75 /// ] 76 /// 77 /// #trait = { 78 /// args_in = 2, 79 /// args_out = 1, 80 /// indexing_maps = #accesses, 81 /// iterator_types = ["parallel", "parallel"], 82 /// library_call = "some_external_fn" 83 /// } 84 /// 85 /// func @broadcast_test(%arg0 : tensor<5xf32>, %arg1 : tensor<5xf32>) -> 86 /// tensor<5x5xf32> 87 /// { 88 /// %0 = linalg.generic #trait %arg0, %arg1 { 89 /// ^bb0(%arg2: f32, %arg3: f32): 90 /// %3 = addf %arg2, %arg3 : f32 91 /// linalg.yield %3 : f32 92 /// } : tensor<5xf32>, tensor<5xf32> -> tensor<5x5xf32> 93 /// return %0 : tensor<5x5xf32> 94 /// } 95 96 /// Given dims of the iteration space of a structured op that are known to be 97 /// single trip count (`unitDims`), return the indexing maps to use in the 98 /// canonicalized op with these dims removed, given the original `indexingMaps`. 99 static ArrayAttr replaceUnitDims(DenseSet<unsigned> &unitDims, 100 ArrayRef<AffineMap> indexingMaps, 101 MLIRContext *context) { 102 if (indexingMaps.empty()) 103 return nullptr; 104 unsigned numIterationDims = indexingMaps.front().getNumDims(); 105 unsigned numSymbols = indexingMaps.front().getNumSymbols(); 106 107 // Compute the replacement for each dim expr. 108 SmallVector<AffineExpr, 4> dimReplacements; 109 dimReplacements.reserve(numIterationDims); 110 unsigned numKeptDims = 0; 111 for (unsigned dim : llvm::seq<unsigned>(0, numIterationDims)) { 112 if (unitDims.count(dim)) 113 dimReplacements.push_back(getAffineConstantExpr(0, context)); 114 else 115 dimReplacements.push_back(getAffineDimExpr(numKeptDims++, context)); 116 } 117 118 // Symbols remain the same. 119 SmallVector<AffineExpr, 4> symReplacements; 120 symReplacements.reserve(numSymbols); 121 for (unsigned symbol : llvm::seq<unsigned>(0, numSymbols)) 122 symReplacements.push_back(getAffineSymbolExpr(symbol, context)); 123 124 SmallVector<AffineMap, 4> newIndexingMaps; 125 newIndexingMaps.reserve(indexingMaps.size()); 126 for (AffineMap operandMap : indexingMaps) { 127 // Expected indexing maps to have no symbols. 128 if (operandMap.getNumSymbols()) 129 return nullptr; 130 newIndexingMaps.push_back(simplifyAffineMap( 131 operandMap.replaceDimsAndSymbols(dimReplacements, symReplacements, 132 numIterationDims - unitDims.size(), 133 numSymbols))); 134 } 135 136 // Check that the new index maps are invertible. If not, something went 137 // wrong, so abort. 138 if (!inversePermutation(concatAffineMaps(newIndexingMaps))) 139 return nullptr; 140 return ArrayAttr::get(context, 141 llvm::to_vector<4>(llvm::map_range( 142 newIndexingMaps, [](AffineMap map) -> Attribute { 143 return AffineMapAttr::get(map); 144 }))); 145 } 146 147 /// Modify the region of indexed generic op to drop arguments corresponding to 148 /// loops that are unit trip count. 149 template <typename OpTy> 150 static LogicalResult 151 replaceBlockArgForUnitDimLoops(OpTy op, const DenseSet<unsigned> &unitDims, 152 PatternRewriter &rewriterp) { 153 return success(); 154 } 155 156 template <> 157 LogicalResult replaceBlockArgForUnitDimLoops<IndexedGenericOp>( 158 IndexedGenericOp op, const DenseSet<unsigned> &unitDims, 159 PatternRewriter &rewriter) { 160 OpBuilder::InsertionGuard guard(rewriter); 161 Block *entryBlock = &op->getRegion(0).front(); 162 rewriter.setInsertionPointToStart(entryBlock); 163 Value zero = rewriter.create<ConstantIndexOp>(op.getLoc(), 0); 164 for (unsigned unitDimLoop : unitDims) { 165 entryBlock->getArgument(unitDimLoop).replaceAllUsesWith(zero); 166 } 167 SmallVector<unsigned, 8> unitDimsToErase(unitDims.begin(), unitDims.end()); 168 entryBlock->eraseArguments(unitDimsToErase); 169 return success(); 170 } 171 172 namespace { 173 /// Pattern to fold unit-trip count loops in GenericOps. 174 // TODO: Generalize this to indexed-generic as well by modifying the region args 175 // as well. 176 template <typename GenericOpTy> 177 struct FoldUnitDimLoops : public OpRewritePattern<GenericOpTy> { 178 using OpRewritePattern<GenericOpTy>::OpRewritePattern; 179 LogicalResult matchAndRewrite(GenericOpTy op, 180 PatternRewriter &rewriter) const override { 181 SmallVector<AffineMap, 4> indexingMaps = op.getIndexingMaps(); 182 if (indexingMaps.empty()) 183 return failure(); 184 185 // Check if any of the iteration dimensions are unit-trip count. They will 186 // end up being unit-trip count if they are used to index into a unit-dim 187 // tensor/memref. 188 AffineMap invertedMap = inversePermutation(concatAffineMaps(indexingMaps)); 189 if (!invertedMap) 190 return failure(); 191 SmallVector<int64_t, 4> dims; 192 for (ShapedType shapedType : op.getShapedOperandTypes()) 193 dims.append(shapedType.getShape().begin(), shapedType.getShape().end()); 194 DenseSet<unsigned> unitDims; 195 ArrayAttr iteratorTypes = op.iterator_types(); 196 for (auto expr : enumerate(invertedMap.getResults())) { 197 if (AffineDimExpr dimExpr = expr.value().dyn_cast<AffineDimExpr>()) 198 if (dims[dimExpr.getPosition()] == 1 && 199 iteratorTypes[expr.index()].dyn_cast<StringAttr>().getValue() == 200 getParallelIteratorTypeName()) 201 unitDims.insert(expr.index()); 202 } 203 if (unitDims.empty()) 204 return failure(); 205 206 // Compute the modified indexing maps. 207 MLIRContext *context = rewriter.getContext(); 208 ArrayAttr newIndexingMapAttr = 209 replaceUnitDims(unitDims, indexingMaps, context); 210 if (!newIndexingMapAttr) 211 return op.emitError("unable to compute modified indexing_maps"); 212 213 // Compute the iterator types of the modified op by dropping the one-trip 214 // count loops. 215 SmallVector<Attribute, 4> newIteratorTypes; 216 for (auto attr : llvm::enumerate(iteratorTypes)) { 217 if (!unitDims.count(attr.index())) 218 newIteratorTypes.push_back(attr.value()); 219 } 220 221 rewriter.startRootUpdate(op); 222 op.indexing_mapsAttr(newIndexingMapAttr); 223 op.iterator_typesAttr(ArrayAttr::get(context, newIteratorTypes)); 224 (void)replaceBlockArgForUnitDimLoops(op, unitDims, rewriter); 225 rewriter.finalizeRootUpdate(op); 226 return success(); 227 } 228 }; 229 230 struct UnitExtentReplacementInfo { 231 RankedTensorType type; 232 AffineMap indexMap; 233 ArrayAttr reassociation; 234 }; 235 } // namespace 236 237 /// Utility function for replacing operands/results to a linalg generic 238 /// operation on tensors with unit-extent dimensions. These can be replaced with 239 /// an operand/result with the unit-extent dimension removed. This is only done 240 /// if the indexing map used to access that didimensionmension has a 241 /// AffineConstantExpr of value 0. Given the `type` of an result/operand of a 242 /// Linalg op, and its `indexMap` the utility function returns: 243 /// - the new type with dimensions of size 1 removed. 244 /// - modified index map that can be used to access the replaced result/operand 245 /// - the reassociation that converts from the original tensor type to the 246 /// modified tensor type. 247 static UnitExtentReplacementInfo replaceUnitExtents(AffineMap indexMap, 248 RankedTensorType type, 249 MLIRContext *context) { 250 ArrayRef<int64_t> shape = type.getShape(); 251 ArrayRef<AffineExpr> exprs = indexMap.getResults(); 252 SmallVector<AffineExpr, 2> reassociations; 253 SmallVector<Attribute, 4> reassociationMaps; 254 SmallVector<AffineExpr, 4> newIndexExprs; 255 SmallVector<int64_t, 4> newShape; 256 257 int64_t origRank = type.getRank(); 258 AffineExpr zeroExpr = getAffineConstantExpr(0, context); 259 auto isUnitExtent = [&](int64_t dim) -> bool { 260 return shape[dim] == 1 && exprs[dim] == zeroExpr; 261 }; 262 263 unsigned dim = 0; 264 // Fold dimensions that are unit-extent at the beginning of the tensor. 265 while (dim < origRank && isUnitExtent(dim)) 266 reassociations.push_back(getAffineDimExpr(dim++, context)); 267 while (dim < origRank) { 268 reassociations.push_back(getAffineDimExpr(dim, context)); 269 newIndexExprs.push_back(exprs[dim]); 270 newShape.push_back(shape[dim]); 271 // Fold all following dimensions that are unit-extent. 272 while (dim + 1 < origRank && isUnitExtent(dim + 1)) { 273 ++dim; 274 reassociations.push_back(getAffineDimExpr(dim, context)); 275 } 276 reassociationMaps.push_back(AffineMapAttr::get(AffineMap::get( 277 origRank, /*numSymbols = */ 0, reassociations, context))); 278 reassociations.clear(); 279 ++dim; 280 } 281 UnitExtentReplacementInfo info = { 282 RankedTensorType::get(newShape, type.getElementType()), 283 AffineMap::get(indexMap.getNumDims(), indexMap.getNumSymbols(), 284 newIndexExprs, context), 285 ArrayAttr::get(context, reassociationMaps)}; 286 return info; 287 } 288 289 namespace { 290 291 /// Pattern to replace tensors operands/results that are unit extents. 292 template <typename GenericOpTy> 293 struct ReplaceUnitExtentTensors : public OpRewritePattern<GenericOpTy> { 294 using OpRewritePattern<GenericOpTy>::OpRewritePattern; 295 LogicalResult matchAndRewrite(GenericOpTy op, 296 PatternRewriter &rewriter) const override { 297 // TODO: support init_tensors and reductions. 298 if (!op.hasTensorSemantics() || op.getNumInitTensors() != 0) 299 return failure(); 300 301 MLIRContext *context = rewriter.getContext(); 302 Location loc = op.getLoc(); 303 304 SmallVector<AffineMap, 4> newIndexingMaps; 305 SmallVector<ArrayAttr, 4> reassociationMaps; 306 SmallVector<ShapedType, 4> newInputOutputTypes; 307 bool doCanonicalization = false; 308 for (auto it : 309 llvm::zip(op.getIndexingMaps(), op.getShapedOperandTypes())) { 310 auto replacementInfo = replaceUnitExtents( 311 std::get<0>(it), std::get<1>(it).template cast<RankedTensorType>(), 312 context); 313 reassociationMaps.push_back(replacementInfo.reassociation); 314 newIndexingMaps.push_back(replacementInfo.indexMap); 315 newInputOutputTypes.push_back(replacementInfo.type); 316 doCanonicalization |= replacementInfo.type != std::get<1>(it); 317 } 318 319 // If the indexing maps of the result operation are not invertible (i.e. not 320 // legal), abort. 321 if (!doCanonicalization || 322 !inversePermutation(concatAffineMaps(newIndexingMaps))) 323 return failure(); 324 325 // If any operand type change, insert a reshape to convert from the original 326 // type to the new type. 327 // TODO: get rid of flattenedIdx which assumes operand order and contiguity. 328 unsigned flattenedIdx = 0; 329 auto insertReshapes = [&](ValueRange values) { 330 SmallVector<Value, 4> res; 331 res.reserve(values.size()); 332 for (auto operand : llvm::enumerate(values)) { 333 if (operand.value().getType() == newInputOutputTypes[flattenedIdx]) 334 res.push_back(operand.value()); 335 else 336 res.push_back(rewriter.create<linalg::TensorReshapeOp>( 337 loc, newInputOutputTypes[flattenedIdx], operand.value(), 338 reassociationMaps[flattenedIdx])); 339 ++flattenedIdx; 340 } 341 return res; 342 }; 343 344 SmallVector<Value, 4> newInputs = insertReshapes(op.inputs()); 345 SmallVector<Value, 4> newOutputs = insertReshapes(op.outputs()); 346 347 // If any result type changes, insert a reshape to convert from the original 348 // type to the new type. 349 SmallVector<Type, 4> resultTypes; 350 resultTypes.reserve(op.getNumResults()); 351 for (unsigned i : llvm::seq<unsigned>(0, op.getNumResults())) 352 resultTypes.push_back(newInputOutputTypes[i + op.getNumInputs()]); 353 GenericOpTy replacementOp = rewriter.create<GenericOpTy>( 354 loc, resultTypes, newInputs, newOutputs, newIndexingMaps, 355 llvm::to_vector<4>( 356 op.iterator_types().template getAsValueRange<StringAttr>())); 357 rewriter.inlineRegionBefore(op.region(), replacementOp.region(), 358 replacementOp.region().begin()); 359 360 // If any result tensor has a modified shape, then add reshape to recover 361 // the original shape. 362 SmallVector<Value, 4> resultReplacements; 363 for (auto result : llvm::enumerate(replacementOp.getResults())) { 364 unsigned index = result.index() + replacementOp.getNumInputs(); 365 RankedTensorType origResultType = op.getResult(result.index()) 366 .getType() 367 .template cast<RankedTensorType>(); 368 if (origResultType != result.value().getType()) 369 resultReplacements.push_back(rewriter.create<linalg::TensorReshapeOp>( 370 loc, origResultType, result.value(), reassociationMaps[index])); 371 else 372 resultReplacements.push_back(result.value()); 373 } 374 rewriter.replaceOp(op, resultReplacements); 375 return success(); 376 } 377 }; 378 } // namespace 379 380 namespace { 381 /// Pattern to fold pair of reshape ops where the intermediate has unit-dims for 382 /// example: 383 /// 384 /// %0 = linalg.tensor_reshape %arg0 385 /// [affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>] 386 /// : tensor<2048xf32> into tensor<1x4x1x512xf32> 387 /// %1 = linalg.tensor_reshape %0 388 /// [affine_map<(d0, d1, d2, d3) -> (d0, d1, d2)>, 389 /// affine_map<(d0, d1, d2, d3) -> (d3)>] 390 /// : tensor<1x4x1x512xf32> into tensor<4x512xf32> 391 /// 392 /// can be replaced with 393 /// 394 /// %0 = linalg.tensor_reshape %arg0 [affine_map<(d0, d1) -> (d0, d1)>] 395 /// : tensor<2048xf32> into tensor<4x512xf32> 396 /// 397 /// Similarly, 398 /// 399 /// %0 = linalg.tensor_reshape %arg0 400 /// [affine_map<(d0, d1, d2, d3) -> (d0, d1, d2)>, 401 /// affine_map<(d0, d1, d2, d3) -> (d3)>] 402 /// : tensor<4x512xf32> into tensor<1x4x1x512xf32> 403 /// %1 = linalg.tensor_reshape %0 404 /// [affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>] 405 /// : tensor<1x4x1x512xf32> into tensor<2048xf32> 406 /// 407 /// can be replaced with 408 /// 409 /// %0 = linalg.tensor_reshape %arg0 [affine_map<(d0, d1) -> (d0, d1)>] 410 /// : tensor<4x512xf32> into tensor<2048xf32> 411 struct FoldReshapeOpWithUnitExtent : OpRewritePattern<TensorReshapeOp> { 412 using OpRewritePattern<TensorReshapeOp>::OpRewritePattern; 413 414 LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp, 415 PatternRewriter &rewriter) const override { 416 // Check that the source operand is created from a reshape as well. 417 TensorReshapeOp parentReshapeOp = 418 reshapeOp.src().getDefiningOp<TensorReshapeOp>(); 419 if (!parentReshapeOp) 420 return failure(); 421 422 RankedTensorType srcType = reshapeOp.getSrcType(), 423 dstType = reshapeOp.getResultType(), 424 parentSrcType = parentReshapeOp.getSrcType(); 425 if (!srcType.hasStaticShape() || !dstType.hasStaticShape() || 426 !parentSrcType.hasStaticShape() || 427 srcType.getRank() < dstType.getRank() || 428 parentSrcType.getRank() == dstType.getRank()) 429 return failure(); 430 431 // Check if the result tensor_reshape after folding the reshapeOp and 432 // parentReshapeOp are combined. 433 // If the final tensor_reshape is folding, the parentReshapeOp is 434 // introducing unit-dims, and the reshapeOp does an actual reshape. 435 // If the final tensor_reshape op is expanding, the reshapeOp is 436 // introducing unit-dims, and the parentReshapeOp does an actual reshape. 437 bool isFoldingPattern = parentSrcType.getRank() > dstType.getRank(); 438 ArrayRef<int64_t> expandedShape = 439 isFoldingPattern ? parentSrcType.getShape() : dstType.getShape(); 440 ArrayRef<int64_t> foldedShape = 441 isFoldingPattern ? dstType.getShape() : parentSrcType.getShape(); 442 443 unsigned expandedDim = 0, foldedDim = 0; 444 SmallVector<SmallVector<AffineExpr, 4>, 4> reassociationExprs( 445 foldedShape.size()); 446 while (expandedDim < expandedShape.size() && 447 foldedDim < foldedShape.size()) { 448 int64_t dstSize = foldedShape[foldedDim]; 449 int64_t srcSize = expandedShape[expandedDim]; 450 while (srcSize < dstSize && expandedDim < expandedShape.size()) { 451 reassociationExprs[foldedDim].push_back( 452 rewriter.getAffineDimExpr(expandedDim++)); 453 srcSize *= expandedShape[expandedDim]; 454 } 455 if (srcSize == dstSize) { 456 reassociationExprs[foldedDim].push_back( 457 rewriter.getAffineDimExpr(expandedDim++)); 458 // If the next dim in foldedShape is not 1, treat subsequent dims in 459 // expandedShape which are 1 to be collapsed. 460 if (foldedDim == foldedShape.size() - 1 || 461 foldedShape[foldedDim + 1] != 1) { 462 while (expandedDim < expandedShape.size() && 463 expandedShape[expandedDim] == 1) { 464 reassociationExprs[foldedDim].push_back( 465 rewriter.getAffineDimExpr(expandedDim++)); 466 } 467 } 468 } else { 469 return failure(); 470 } 471 foldedDim++; 472 } 473 if (expandedDim != expandedShape.size()) 474 return failure(); 475 476 SmallVector<AffineMap, 4> reassociationMaps = 477 llvm::to_vector<4>(llvm::map_range( 478 reassociationExprs, [&](ArrayRef<AffineExpr> exprs) -> AffineMap { 479 return AffineMap::get(expandedShape.size(), 0, exprs, 480 rewriter.getContext()); 481 })); 482 rewriter.replaceOpWithNewOp<TensorReshapeOp>( 483 reshapeOp, dstType, parentReshapeOp.src(), 484 rewriter.getAffineMapArrayAttr(reassociationMaps)); 485 return success(); 486 } 487 }; 488 } // namespace 489 490 /// Patterns that are used to canonicalize the use of unit-extent dims for 491 /// broadcasting. 492 void mlir::populateLinalgFoldUnitExtentDimsPatterns( 493 MLIRContext *context, OwningRewritePatternList &patterns) { 494 patterns 495 .insert<FoldUnitDimLoops<GenericOp>, FoldUnitDimLoops<IndexedGenericOp>, 496 ReplaceUnitExtentTensors<GenericOp>, 497 ReplaceUnitExtentTensors<IndexedGenericOp>>(context); 498 TensorReshapeOp::getCanonicalizationPatterns(patterns, context); 499 patterns.insert<FoldReshapeOpWithUnitExtent>(context); 500 populateFoldUnitDimsReshapeOpsByLinearizationPatterns(context, patterns); 501 } 502 503 namespace { 504 /// Pass that removes unit-extent dims within generic ops. 505 struct LinalgFoldUnitExtentDimsPass 506 : public LinalgFoldUnitExtentDimsBase<LinalgFoldUnitExtentDimsPass> { 507 void runOnFunction() override { 508 OwningRewritePatternList patterns; 509 FuncOp funcOp = getFunction(); 510 MLIRContext *context = funcOp.getContext(); 511 if (foldOneTripLoopsOnly) 512 patterns.insert<FoldUnitDimLoops<GenericOp>, 513 FoldUnitDimLoops<IndexedGenericOp>>(context); 514 else 515 populateLinalgFoldUnitExtentDimsPatterns(context, patterns); 516 (void)applyPatternsAndFoldGreedily(funcOp.getBody(), std::move(patterns)); 517 } 518 }; 519 } // namespace 520 521 std::unique_ptr<OperationPass<FuncOp>> 522 mlir::createLinalgFoldUnitExtentDimsPass() { 523 return std::make_unique<LinalgFoldUnitExtentDimsPass>(); 524 } 525