|
| 1 | +// Copyright 2025 The IREE Authors |
| 2 | +// |
| 3 | +// Licensed 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 | +#include "iree/compiler/Codegen/Common/CPU/Passes.h" |
| 8 | +#include "iree/compiler/Codegen/Common/Transforms.h" |
| 9 | +#include "llvm/ADT/STLExtras.h" |
| 10 | +#include "llvm/Support/Casting.h" |
| 11 | +#include "llvm/Support/LogicalResult.h" |
| 12 | +#include "mlir/Dialect/Linalg/IR/Linalg.h" |
| 13 | +#include "mlir/Dialect/Linalg/Transforms/Transforms.h" |
| 14 | +#include "mlir/Dialect/Linalg/Utils/Utils.h" |
| 15 | +#include "mlir/Dialect/Tensor/IR/Tensor.h" |
| 16 | +#include "mlir/Dialect/Tensor/Transforms/Transforms.h" |
| 17 | +#include "mlir/Dialect/Utils/IndexingUtils.h" |
| 18 | +#include "mlir/Transforms/GreedyPatternRewriteDriver.h" |
| 19 | + |
| 20 | +namespace mlir::iree_compiler { |
| 21 | + |
| 22 | +#define GEN_PASS_DEF_CPUPROPAGATEDATALAYOUTPASS |
| 23 | +#include "iree/compiler/Codegen/Common/CPU/Passes.h.inc" |
| 24 | + |
| 25 | +namespace { |
| 26 | + |
| 27 | +/// Sinks down tensor.collapse_shape across linalg.unpack op, if the collapsing |
| 28 | +/// dims are two unit dims where one is outer dimension and the other is inner |
| 29 | +/// dimension. It implies that we swap two operations by adjusting the packing |
| 30 | +/// metadata in linalg.unpack op. |
| 31 | +/// Note that the pattern only supports the case where the destination tensor of |
| 32 | +/// linalg.unpack op is a tensor.empty op. The constraint can be removed by |
| 33 | +/// introducing tensor.expand_shape op on the destination tensor. However, it is |
| 34 | +/// not common in practice, so it is not supported now. |
| 35 | +struct SinkDownCollapsingUnitDimsAcrossUnpack final |
| 36 | + : public OpRewritePattern<linalg::UnPackOp> { |
| 37 | + using OpRewritePattern<linalg::UnPackOp>::OpRewritePattern; |
| 38 | + LogicalResult matchAndRewrite(linalg::UnPackOp op, |
| 39 | + PatternRewriter &rewriter) const override { |
| 40 | + if (!isIdentityPermutation(op.getOuterDimsPerm())) { |
| 41 | + return rewriter.notifyMatchFailure( |
| 42 | + op, "expected identity (or unset) outer permutation"); |
| 43 | + } |
| 44 | + if (op.getSourceRank() != op.getDestRank() + 1) { |
| 45 | + return rewriter.notifyMatchFailure( |
| 46 | + op, "expected unpacking exactly one dimension"); |
| 47 | + } |
| 48 | + auto emptyOp = op.getDest().getDefiningOp<tensor::EmptyOp>(); |
| 49 | + if (!emptyOp) { |
| 50 | + return rewriter.notifyMatchFailure( |
| 51 | + op, "expected destination to be a tensor.empty op"); |
| 52 | + } |
| 53 | + auto collapseOp = op.getSource().getDefiningOp<tensor::CollapseShapeOp>(); |
| 54 | + if (!collapseOp) { |
| 55 | + return rewriter.notifyMatchFailure( |
| 56 | + op, "expected the source to be a tensor.collapse_shape op"); |
| 57 | + } |
| 58 | + |
| 59 | + SmallVector<ReassociationIndices, 4> ri = |
| 60 | + collapseOp.getReassociationIndices(); |
| 61 | + ReassociationIndices outerRi, innerRi; |
| 62 | + for (ArrayRef<int64_t> indices : ri) { |
| 63 | + if (indices.size() == 1) { |
| 64 | + continue; |
| 65 | + } |
| 66 | + if (indices.size() > 2) { |
| 67 | + return rewriter.notifyMatchFailure( |
| 68 | + op, "expected re-association map to have two dimensions"); |
| 69 | + } |
| 70 | + if (outerRi.empty()) { |
| 71 | + outerRi.assign(indices.begin(), indices.end()); |
| 72 | + continue; |
| 73 | + } |
| 74 | + if (innerRi.empty()) { |
| 75 | + innerRi.assign(indices.begin(), indices.end()); |
| 76 | + continue; |
| 77 | + } |
| 78 | + return rewriter.notifyMatchFailure( |
| 79 | + op, "expected only two re-association maps to have two dimensions"); |
| 80 | + } |
| 81 | + if (outerRi.empty() || innerRi.empty()) { |
| 82 | + return rewriter.notifyMatchFailure( |
| 83 | + op, "expected only two re-association maps to have two dimensions"); |
| 84 | + } |
| 85 | + |
| 86 | + RankedTensorType srcType = collapseOp.getSrcType(); |
| 87 | + if (innerRi.back() != srcType.getRank() - 1) { |
| 88 | + return rewriter.notifyMatchFailure( |
| 89 | + op, "expected that the two innermost dimensions are collapsed"); |
| 90 | + } |
| 91 | + SmallVector<int64_t> innerDimPos(op.getInnerDimsPos()); |
| 92 | + if (!llvm::is_contained(outerRi, innerDimPos[0])) { |
| 93 | + return rewriter.notifyMatchFailure( |
| 94 | + op, "expected the packed dimension is collapsed"); |
| 95 | + } |
| 96 | + |
| 97 | + bool missLeadingUnitDim = srcType.getDimSize(outerRi[0]) == 1 && |
| 98 | + srcType.getDimSize(innerRi[0]) == 1; |
| 99 | + bool missTrailingUnitDim = srcType.getDimSize(outerRi[1]) == 1 && |
| 100 | + srcType.getDimSize(innerRi[1]) == 1; |
| 101 | + if (!missLeadingUnitDim && !missTrailingUnitDim) { |
| 102 | + return rewriter.notifyMatchFailure(op, |
| 103 | + "expected collapsing either leading " |
| 104 | + "unit dims or trailing outer dims"); |
| 105 | + } |
| 106 | + |
| 107 | + // We either add unit dims right before or after the packed dimensions. |
| 108 | + // E.g., AxBxNxCxDxn becomes AxBx1xNxCxDx1xn if `missLeadingUnitDim` is |
| 109 | + // true. It becomes AxBxNx1xCxDxnx1 if `missingTrailingUnitDim` is true. |
| 110 | + // If both are true, the former is prioritized because it does not matter in |
| 111 | + // practice. |
| 112 | + SmallVector<OpFoldResult> innerTiles(op.getMixedTiles()); |
| 113 | + SmallVector<OpFoldResult> destShape = emptyOp.getMixedSizes(); |
| 114 | + if (missLeadingUnitDim) { |
| 115 | + // The unit dim is inserted before the packed dimension, so we advance one |
| 116 | + // for innerDimPos[0]. |
| 117 | + innerDimPos[0]++; |
| 118 | + innerDimPos.insert(innerDimPos.begin(), outerRi[0]); |
| 119 | + innerTiles.insert(innerTiles.begin(), rewriter.getIndexAttr(1)); |
| 120 | + destShape.insert(destShape.begin() + outerRi[0], |
| 121 | + rewriter.getIndexAttr(1)); |
| 122 | + } else { |
| 123 | + innerDimPos.insert(innerDimPos.end(), outerRi[1]); |
| 124 | + innerTiles.insert(innerTiles.end(), rewriter.getIndexAttr(1)); |
| 125 | + destShape.insert(destShape.end(), rewriter.getIndexAttr(1)); |
| 126 | + } |
| 127 | + |
| 128 | + Location loc = op.getLoc(); |
| 129 | + auto newDestOp = rewriter.create<tensor::EmptyOp>( |
| 130 | + loc, destShape, emptyOp.getType().getElementType()); |
| 131 | + auto newUnpackOp = rewriter.create<linalg::UnPackOp>( |
| 132 | + loc, collapseOp.getSrc(), newDestOp, innerDimPos, innerTiles); |
| 133 | + SmallVector<ReassociationIndices> newRi; |
| 134 | + for (int64_t i = 0, e = op.getDestRank(); i < e; ++i) { |
| 135 | + if (i == outerRi[0]) { |
| 136 | + newRi.push_back(outerRi); |
| 137 | + ++i; |
| 138 | + } else { |
| 139 | + newRi.push_back({i}); |
| 140 | + } |
| 141 | + } |
| 142 | + rewriter.replaceOpWithNewOp<tensor::CollapseShapeOp>( |
| 143 | + op, newUnpackOp.getResult(), newRi); |
| 144 | + |
| 145 | + return success(); |
| 146 | + } |
| 147 | +}; |
| 148 | + |
| 149 | +struct CPUPropagateDataLayoutPass final |
| 150 | + : public impl::CPUPropagateDataLayoutPassBase<CPUPropagateDataLayoutPass> { |
| 151 | + void getDependentDialects(DialectRegistry ®istry) const override { |
| 152 | + registry.insert<linalg::LinalgDialect, tensor::TensorDialect>(); |
| 153 | + } |
| 154 | + |
| 155 | + void runOnOperation() override; |
| 156 | +}; |
| 157 | + |
| 158 | +} // namespace |
| 159 | + |
| 160 | +void CPUPropagateDataLayoutPass::runOnOperation() { |
| 161 | + MLIRContext *ctx = &getContext(); |
| 162 | + FunctionOpInterface funcOp = getOperation(); |
| 163 | + RewritePatternSet patterns(ctx); |
| 164 | + patterns.insert<SinkDownCollapsingUnitDimsAcrossUnpack>(ctx); |
| 165 | + populateReshapeToInterfaceTensorPatterns(patterns); |
| 166 | + tensor::populateFoldTensorEmptyPatterns(patterns, /*foldSingleUseOnly=*/1); |
| 167 | + linalg::populateFoldReshapeOpsByExpansionPatterns( |
| 168 | + patterns, [](OpOperand *fusedOperand) -> bool { |
| 169 | + Operation *producer = fusedOperand->get().getDefiningOp(); |
| 170 | + auto consumerGenericOp = |
| 171 | + dyn_cast_if_present<linalg::GenericOp>(fusedOperand->getOwner()); |
| 172 | + if (!isa<tensor::CollapseShapeOp>(producer) || !consumerGenericOp) { |
| 173 | + return false; |
| 174 | + } |
| 175 | + return true; |
| 176 | + }); |
| 177 | + if (failed(applyPatternsGreedily(funcOp, std::move(patterns)))) { |
| 178 | + return signalPassFailure(); |
| 179 | + } |
| 180 | +} |
| 181 | + |
| 182 | +} // namespace mlir::iree_compiler |
0 commit comments