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/IR/PatternMatch.h" 24 #include "mlir/Support/LLVM.h" 25 #include "mlir/Transforms/FoldUtils.h" 26 #include "llvm/Support/CommandLine.h" 27 #include "llvm/Support/Debug.h" 28 29 #define DEBUG_TYPE "linalg-drop-unit-dims" 30 31 using namespace mlir; 32 using namespace mlir::edsc; 33 using namespace mlir::edsc::intrinsics; 34 using namespace mlir::linalg; 35 36 /// Implements a pass that canonicalizes the uses of unit-extent dimensions for 37 /// broadcasting. For example, 38 /// 39 /// ```mlir 40 /// #accesses = [ 41 /// affine_map<(d0, d1) -> (0, d1)>, 42 /// affine_map<(d0, d1) -> (d0, 0)>, 43 /// affine_map<(d0, d1) -> (d0, d1)> 44 /// ] 45 /// 46 /// #trait = { 47 /// args_in = 2, 48 /// args_out = 1, 49 /// indexing_maps = #accesses, 50 /// iterator_types = ["parallel", "parallel"], 51 /// library_call = "some_external_fn" 52 /// } 53 /// 54 /// func @broadcast_test(%arg0 : tensor<5xf32>, %arg1 : tensor<5xf32>) -> 55 /// tensor<5x5xf32> 56 /// { 57 /// %0 = linalg.tensor_reshape %arg0 [affine_map<(d0, d1) -> (d0, d1)>] : 58 /// tensor<5xf32> into tensor<1x5xf32> 59 /// %1 = linalg.tensor_reshape %arg1 [affine_map<(d0, d1) -> (d0, d1)>] : 60 /// tensor<5xf32> into tensor<5x1xf32> 61 /// %2 = linalg.generic #trait %0, %1 { 62 /// ^bb0(%arg2: f32, %arg3: f32): 63 /// %3 = addf %arg2, %arg3 : f32 64 /// linalg.yield %3 : f32 65 /// } : tensor<1x5xf32>, tensor<5x1xf32> -> tensor<5x5xf32> 66 /// return %2 : tensor<5x5xf32> 67 /// } 68 /// 69 /// would canonicalize to 70 /// 71 /// ```mlir 72 /// #accesses = [ 73 /// affine_map<(d0, d1) -> (d1)>, 74 /// affine_map<(d0, d1) -> (d0)>, 75 /// affine_map<(d0, d1) -> (d0, d1)> 76 /// ] 77 /// 78 /// #trait = { 79 /// args_in = 2, 80 /// args_out = 1, 81 /// indexing_maps = #accesses, 82 /// iterator_types = ["parallel", "parallel"], 83 /// library_call = "some_external_fn" 84 /// } 85 /// 86 /// func @broadcast_test(%arg0 : tensor<5xf32>, %arg1 : tensor<5xf32>) -> 87 /// tensor<5x5xf32> 88 /// { 89 /// %0 = linalg.generic #trait %arg0, %arg1 { 90 /// ^bb0(%arg2: f32, %arg3: f32): 91 /// %3 = addf %arg2, %arg3 : f32 92 /// linalg.yield %3 : f32 93 /// } : tensor<5xf32>, tensor<5xf32> -> tensor<5x5xf32> 94 /// return %0 : tensor<5x5xf32> 95 /// } 96 97 /// Given dims of the iteration space of a structured op that are known to be 98 /// single trip count (`unitDims`), return the indexing maps to use in the 99 /// canonicalized op with these dims removed, given the original `indexingMaps`. 100 static ArrayAttr replaceUnitDims(DenseSet<unsigned> &unitDims, 101 ArrayRef<AffineMap> indexingMaps, 102 MLIRContext *context) { 103 if (indexingMaps.empty()) 104 return nullptr; 105 unsigned numIterationDims = indexingMaps.front().getNumDims(); 106 unsigned numSymbols = indexingMaps.front().getNumSymbols(); 107 108 // Compute the replacement for each dim expr. 109 SmallVector<AffineExpr, 4> dimReplacements; 110 dimReplacements.reserve(numIterationDims); 111 unsigned numKeptDims = 0; 112 for (unsigned dim : llvm::seq<unsigned>(0, numIterationDims)) { 113 if (unitDims.count(dim)) 114 dimReplacements.push_back(getAffineConstantExpr(0, context)); 115 else 116 dimReplacements.push_back(getAffineDimExpr(numKeptDims++, context)); 117 } 118 119 // Symbols remain the same. 120 SmallVector<AffineExpr, 4> symReplacements; 121 symReplacements.reserve(numSymbols); 122 for (unsigned symbol : llvm::seq<unsigned>(0, numSymbols)) 123 symReplacements.push_back(getAffineSymbolExpr(symbol, context)); 124 125 SmallVector<AffineMap, 4> newIndexingMaps; 126 newIndexingMaps.reserve(indexingMaps.size()); 127 for (AffineMap operandMap : indexingMaps) { 128 // Expected indexing maps to have no symbols. 129 if (operandMap.getNumSymbols()) 130 return nullptr; 131 newIndexingMaps.push_back(simplifyAffineMap( 132 operandMap.replaceDimsAndSymbols(dimReplacements, symReplacements, 133 numIterationDims - unitDims.size(), 134 numSymbols))); 135 } 136 137 // Check that the new index maps are invertible. If not, something went 138 // wrong, so abort. 139 if (!inversePermutation(concatAffineMaps(newIndexingMaps))) 140 return nullptr; 141 return ArrayAttr::get( 142 llvm::to_vector<4>(llvm::map_range( 143 newIndexingMaps, 144 [](AffineMap map) -> Attribute { return AffineMapAttr::get(map); })), 145 context); 146 } 147 148 namespace { 149 /// Pattern to fold unit-trip count loops in GenericOps. 150 // TODO: Generalize this to indexed-generic as well by modifying the region args 151 // as well. 152 struct FoldUnitDimLoops : public OpRewritePattern<GenericOp> { 153 using OpRewritePattern<GenericOp>::OpRewritePattern; 154 LogicalResult matchAndRewrite(GenericOp genericOp, 155 PatternRewriter &rewriter) const override { 156 SmallVector<AffineMap, 4> indexingMaps = genericOp.getIndexingMaps(); 157 if (indexingMaps.empty()) 158 return failure(); 159 160 // Check if any of the iteration dimensions are unit-trip count. They will 161 // end up being unit-trip count if they are used to index into a unit-dim 162 // tensor/memref. 163 AffineMap invertedMap = inversePermutation(concatAffineMaps(indexingMaps)); 164 if (!invertedMap) 165 return failure(); 166 SmallVector<int64_t, 4> dims; 167 for (ShapedType shapedType : genericOp.getInputOutputShapedTypes()) 168 dims.append(shapedType.getShape().begin(), shapedType.getShape().end()); 169 DenseSet<unsigned> unitDims; 170 ArrayAttr iteratorTypes = genericOp.iterator_types(); 171 for (auto expr : enumerate(invertedMap.getResults())) { 172 if (AffineDimExpr dimExpr = expr.value().dyn_cast<AffineDimExpr>()) 173 if (dims[dimExpr.getPosition()] == 1 && 174 iteratorTypes[expr.index()].dyn_cast<StringAttr>().getValue() == 175 getParallelIteratorTypeName()) 176 unitDims.insert(expr.index()); 177 } 178 if (unitDims.empty()) 179 return failure(); 180 181 // Compute the modified indexing maps. 182 MLIRContext *context = rewriter.getContext(); 183 ArrayAttr newIndexingMapAttr = 184 replaceUnitDims(unitDims, indexingMaps, context); 185 if (!newIndexingMapAttr) 186 return genericOp.emitError("unable to compute modified indexing_maps"); 187 188 // Compute the iterator types of the modified op by dropping the one-trip 189 // count loops. 190 SmallVector<Attribute, 4> newIteratorTypes; 191 for (auto attr : llvm::enumerate(iteratorTypes)) { 192 if (!unitDims.count(attr.index())) 193 newIteratorTypes.push_back(attr.value()); 194 } 195 196 rewriter.startRootUpdate(genericOp); 197 genericOp.indexing_mapsAttr(newIndexingMapAttr); 198 genericOp.iterator_typesAttr(ArrayAttr::get(newIteratorTypes, context)); 199 rewriter.finalizeRootUpdate(genericOp); 200 return success(); 201 } 202 }; 203 204 struct UnitExtentReplacementInfo { 205 RankedTensorType type; 206 AffineMap indexMap; 207 ArrayAttr reassociation; 208 }; 209 } // namespace 210 211 /// Utility function for replacing operands/results to a linalg generic 212 /// operation on tensors with unit-extent dimensions. These can be replaced with 213 /// an operand/result with the unit-extent dimension removed. This is only done 214 /// if the indexing map used to access that didimensionmension has a 215 /// AffineConstantExpr of value 0. Given the `type` of an result/operand of a 216 /// Linalg op, and its `indexMap` the utility function returns: 217 /// - the new type with dimensions of size 1 removed. 218 /// - modified index map that can be used to access the replaced result/operand 219 /// - the reassociation that converts from the original tensor type to the 220 /// modified tensor type. 221 static UnitExtentReplacementInfo replaceUnitExtents(AffineMap indexMap, 222 RankedTensorType type, 223 MLIRContext *context) { 224 ArrayRef<int64_t> shape = type.getShape(); 225 ArrayRef<AffineExpr> exprs = indexMap.getResults(); 226 SmallVector<AffineExpr, 2> reassociations; 227 SmallVector<Attribute, 4> reassociationMaps; 228 SmallVector<AffineExpr, 4> newIndexExprs; 229 SmallVector<int64_t, 4> newShape; 230 231 int64_t origRank = type.getRank(); 232 AffineExpr zeroExpr = getAffineConstantExpr(0, context); 233 auto isUnitExtent = [&](int64_t dim) -> bool { 234 return shape[dim] == 1 && exprs[dim] == zeroExpr; 235 }; 236 237 unsigned dim = 0; 238 // Fold dimensions that are unit-extent at the beginning of the tensor. 239 while (dim < origRank && isUnitExtent(dim)) 240 reassociations.push_back(getAffineDimExpr(dim++, context)); 241 while (dim < origRank) { 242 reassociations.push_back(getAffineDimExpr(dim, context)); 243 newIndexExprs.push_back(exprs[dim]); 244 newShape.push_back(shape[dim]); 245 // Fold all following dimensions that are unit-extent. 246 while (dim + 1 < origRank && isUnitExtent(dim + 1)) { 247 ++dim; 248 reassociations.push_back(getAffineDimExpr(dim, context)); 249 } 250 reassociationMaps.push_back(AffineMapAttr::get(AffineMap::get( 251 origRank, /*numSymbols = */ 0, reassociations, context))); 252 reassociations.clear(); 253 ++dim; 254 } 255 UnitExtentReplacementInfo info = { 256 RankedTensorType::get(newShape, type.getElementType()), 257 AffineMap::get(indexMap.getNumDims(), indexMap.getNumSymbols(), 258 newIndexExprs, context), 259 ArrayAttr::get(reassociationMaps, context)}; 260 return info; 261 } 262 263 namespace { 264 /// Pattern to replace tensors operands/results that are unit extents. 265 struct ReplaceUnitExtentTensors : public OpRewritePattern<GenericOp> { 266 using OpRewritePattern<GenericOp>::OpRewritePattern; 267 LogicalResult matchAndRewrite(GenericOp genericOp, 268 PatternRewriter &rewriter) const override { 269 if (!genericOp.hasTensorSemantics()) 270 return failure(); 271 272 MLIRContext *context = rewriter.getContext(); 273 Location loc = genericOp.getLoc(); 274 275 SmallVector<AffineMap, 4> newIndexingMaps; 276 SmallVector<ArrayAttr, 4> reassociationMaps; 277 SmallVector<ShapedType, 4> newInputOutputTypes; 278 bool doCanonicalization = false; 279 for (auto it : llvm::zip(genericOp.getIndexingMaps(), 280 genericOp.getInputOutputShapedTypes())) { 281 auto replacementInfo = replaceUnitExtents( 282 std::get<0>(it), std::get<1>(it).cast<RankedTensorType>(), context); 283 reassociationMaps.push_back(replacementInfo.reassociation); 284 newIndexingMaps.push_back(replacementInfo.indexMap); 285 newInputOutputTypes.push_back(replacementInfo.type); 286 doCanonicalization = 287 doCanonicalization || replacementInfo.type != std::get<1>(it); 288 } 289 290 // If the indexing maps of the result operation are not invertible (i.e. not 291 // legal), abort. 292 if (!doCanonicalization || 293 !inversePermutation(concatAffineMaps(newIndexingMaps))) 294 return failure(); 295 296 // If any operand type change, insert a reshape to convert from the original 297 // type to the new type. 298 SmallVector<Value, 4> newOperands; 299 newOperands.reserve(genericOp.getNumOperands()); 300 for (auto operand : llvm::enumerate(genericOp.getOperands())) { 301 if (operand.value().getType() == newInputOutputTypes[operand.index()]) { 302 newOperands.push_back(operand.value()); 303 } else { 304 newOperands.push_back(rewriter.create<linalg::TensorReshapeOp>( 305 loc, newInputOutputTypes[operand.index()], operand.value(), 306 reassociationMaps[operand.index()])); 307 } 308 } 309 310 // If any result type change, insert a reshape to convert from the original 311 // type to the new type. 312 SmallVector<Type, 4> resultTypes; 313 resultTypes.reserve(genericOp.getNumResults()); 314 for (unsigned i : llvm::seq<unsigned>(0, genericOp.getNumResults())) 315 resultTypes.push_back( 316 newInputOutputTypes[i + genericOp.getNumOperands()]); 317 GenericOp replacementOp = rewriter.create<GenericOp>( 318 loc, resultTypes, newOperands, genericOp.args_in(), 319 genericOp.args_out(), rewriter.getAffineMapArrayAttr(newIndexingMaps), 320 genericOp.iterator_types(), 321 /*doc = */ nullptr, 322 /*library_call = */ nullptr, 323 /*symbol_source = */ nullptr); 324 rewriter.inlineRegionBefore(genericOp.region(), replacementOp.region(), 325 replacementOp.region().begin()); 326 327 // If any result tensor has a modified shape, then add reshape to recover 328 // the original shape. 329 SmallVector<Value, 4> resultReplacements; 330 for (auto result : llvm::enumerate(replacementOp.getResults())) { 331 unsigned index = result.index() + replacementOp.getNumOperands(); 332 RankedTensorType origResultType = genericOp.getResult(result.index()) 333 .getType() 334 .cast<RankedTensorType>(); 335 if (origResultType != result.value().getType()) { 336 resultReplacements.push_back(rewriter.create<linalg::TensorReshapeOp>( 337 loc, origResultType, result.value(), reassociationMaps[index])); 338 } else { 339 resultReplacements.push_back(result.value()); 340 } 341 } 342 rewriter.replaceOp(genericOp, resultReplacements); 343 return success(); 344 } 345 }; 346 } // namespace 347 348 /// Patterns that are used to canonicalize the use of unit-extent dims for 349 /// broadcasting. 350 void mlir::populateLinalgFoldUnitExtentDimsPatterns( 351 MLIRContext *context, OwningRewritePatternList &patterns) { 352 patterns.insert<FoldUnitDimLoops, ReplaceUnitExtentTensors>(context); 353 TensorReshapeOp::getCanonicalizationPatterns(patterns, context); 354 } 355 356 namespace { 357 /// Pass that removes unit-extent dims within generic ops. 358 struct LinalgFoldUnitExtentDimsPass 359 : public LinalgFoldUnitExtentDimsBase<LinalgFoldUnitExtentDimsPass> { 360 void runOnFunction() override { 361 OwningRewritePatternList patterns; 362 FuncOp funcOp = getFunction(); 363 MLIRContext *context = funcOp.getContext(); 364 if (foldOneTripLoopsOnly) 365 patterns.insert<FoldUnitDimLoops>(context); 366 else 367 populateLinalgFoldUnitExtentDimsPatterns(context, patterns); 368 applyPatternsAndFoldGreedily(funcOp.getBody(), patterns); 369 } 370 }; 371 } // namespace 372 373 std::unique_ptr<OperationPass<FuncOp>> 374 mlir::createLinalgFoldUnitExtentDimsPass() { 375 return std::make_unique<LinalgFoldUnitExtentDimsPass>(); 376 } 377