|
| 1 | +//===-- DecomposeTensorOperation.cpp - DESC ---------------------*- C++ -*-===// |
| 2 | +// |
| 3 | +// This file is 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 | +//===----------------------------------------------------------------------===// |
| 8 | +#include "gc/Transforms/Passes.h" |
| 9 | +#include "mlir/Dialect/Linalg/IR/Linalg.h" |
| 10 | +#include "mlir/Dialect/Tensor/IR/Tensor.h" |
| 11 | +#include "mlir/Dialect/Tensor/Transforms/Transforms.h" |
| 12 | +#include "mlir/IR/PatternMatch.h" |
| 13 | +#include "mlir/Transforms/GreedyPatternRewriteDriver.h" |
| 14 | +#include "llvm/Support/Casting.h" |
| 15 | + |
| 16 | +namespace mlir { |
| 17 | +namespace gc { |
| 18 | + |
| 19 | +#define GEN_PASS_DEF_DECOMPOSETENSOROPERATION |
| 20 | +#include "gc/Transforms/Passes.h.inc" |
| 21 | +namespace { |
| 22 | + |
| 23 | +/// Decompose `tensor.gather` into `linalg.generic`. |
| 24 | +/// |
| 25 | +/// %2 = tensor.gather %0[%1] gather_dims([0]) : (tensor<7x128xf16>, |
| 26 | +/// tensor<1x7x1xindex>) -> tensor<1x7x128xf16> |
| 27 | +/// |
| 28 | +/// Becomes |
| 29 | +/// |
| 30 | +/// %empty = tensor.empty() : tensor<1x7x128xf16> |
| 31 | +/// %14 = linalg.generic {indexing_maps = [affine_map<(d0, d1, d2) -> (d0, d1, |
| 32 | +/// 0)>, affine_map<(d0, d1, d2) -> (d0, d1, d2)>], iterator_types = |
| 33 | +/// ["parallel", "parallel", "parallel"]} ins(%expanded : tensor<1x7x1xindex>) |
| 34 | +/// outs(%13 : tensor<1x7x128xf16>) { |
| 35 | +/// ^bb0(%in: index, %out: f16): |
| 36 | +/// %17 = linalg.index 2 : index |
| 37 | +/// %extracted = tensor.extract %0[%in, %17] : tensor<7x128xf16> |
| 38 | +/// linalg.yield %extracted : f16 |
| 39 | +/// } -> tensor<1x7x128xf16> |
| 40 | +struct DecomposeGatherOp : public OpRewritePattern<tensor::GatherOp> { |
| 41 | + using OpRewritePattern<tensor::GatherOp>::OpRewritePattern; |
| 42 | + |
| 43 | + SmallVector<OpFoldResult> getDstMixedSizes(PatternRewriter &rewriter, |
| 44 | + Location loc, |
| 45 | + tensor::GatherOp gatherOp) const { |
| 46 | + SmallVector<OpFoldResult> dstSize = |
| 47 | + tensor::getMixedSizes(rewriter, loc, gatherOp.getResult()); |
| 48 | + SmallVector<OpFoldResult> indexSize = |
| 49 | + tensor::getMixedSizes(rewriter, loc, gatherOp.getIndices()); |
| 50 | + SmallVector<OpFoldResult> srcSize = |
| 51 | + tensor::getMixedSizes(rewriter, loc, gatherOp.getSource()); |
| 52 | + SmallVector<int64_t> gatherDims(gatherOp.getGatherDims()); |
| 53 | + bool isShrinkDst = (indexSize.size() - 1) + srcSize.size() == |
| 54 | + dstSize.size() + gatherDims.size(); |
| 55 | + for (size_t i = 0; i < indexSize.size() - 1; i++) { |
| 56 | + dstSize[i] = indexSize[i]; |
| 57 | + } |
| 58 | + auto cnt = 0; |
| 59 | + for (size_t i = indexSize.size() - 1; i < dstSize.size(); i++) { |
| 60 | + while (isShrinkDst && llvm::find(gatherDims, cnt) != gatherDims.end()) { |
| 61 | + cnt++; |
| 62 | + } |
| 63 | + dstSize[i] = llvm::find(gatherDims, cnt) == gatherDims.end() |
| 64 | + ? srcSize[cnt] |
| 65 | + : getAsIndexOpFoldResult(rewriter.getContext(), 1); |
| 66 | + cnt++; |
| 67 | + } |
| 68 | + return dstSize; |
| 69 | + } |
| 70 | + |
| 71 | + LogicalResult matchAndRewrite(tensor::GatherOp gatherOp, |
| 72 | + PatternRewriter &rewriter) const override { |
| 73 | + OpBuilder::InsertionGuard g(rewriter); |
| 74 | + rewriter.setInsertionPoint(gatherOp); |
| 75 | + Location loc = gatherOp.getLoc(); |
| 76 | + SmallVector<int64_t> gatherDims(gatherOp.getGatherDims()); |
| 77 | + |
| 78 | + // create destination tensor for linalg out |
| 79 | + RankedTensorType dstType = gatherOp.getResultType(); |
| 80 | + Value dstTensor = rewriter.create<tensor::EmptyOp>( |
| 81 | + loc, getDstMixedSizes(rewriter, loc, gatherOp), |
| 82 | + dstType.getElementType()); |
| 83 | + |
| 84 | + // split index tensor to create the linalg input |
| 85 | + SmallVector<Value> indexTensors; |
| 86 | + Value originIndexTensor = gatherOp.getIndices(); |
| 87 | + SmallVector<OpFoldResult> indexTensorSize = |
| 88 | + tensor::getMixedSizes(rewriter, loc, originIndexTensor); |
| 89 | + SmallVector<OpFoldResult> indexTensorStride( |
| 90 | + indexTensorSize.size(), |
| 91 | + getAsIndexOpFoldResult(rewriter.getContext(), 1)); |
| 92 | + SmallVector<OpFoldResult> indexTensorOffset( |
| 93 | + indexTensorSize.size(), |
| 94 | + getAsIndexOpFoldResult(rewriter.getContext(), 0)); |
| 95 | + indexTensorSize[indexTensorSize.size() - 1] = |
| 96 | + getAsIndexOpFoldResult(rewriter.getContext(), 1); |
| 97 | + |
| 98 | + for (size_t cnt = 0; cnt < gatherDims.size(); cnt++) { |
| 99 | + indexTensorOffset[indexTensorSize.size() - 1] = |
| 100 | + getAsIndexOpFoldResult(rewriter.getContext(), cnt); |
| 101 | + Value indexTensor = rewriter.create<tensor::ExtractSliceOp>( |
| 102 | + loc, originIndexTensor, indexTensorOffset, indexTensorSize, |
| 103 | + indexTensorStride); |
| 104 | + indexTensors.emplace_back(indexTensor); |
| 105 | + } |
| 106 | + |
| 107 | + // create the affine map |
| 108 | + SmallVector<AffineMap> affineMaps; |
| 109 | + SmallVector<AffineExpr> dimExprs; |
| 110 | + size_t dstRank = dstType.getShape().size(); |
| 111 | + for (unsigned i = 0; i < indexTensorSize.size() - 1; ++i) |
| 112 | + dimExprs.push_back(rewriter.getAffineDimExpr(i)); |
| 113 | + dimExprs.push_back(getAffineConstantExpr(0, rewriter.getContext())); |
| 114 | + |
| 115 | + for (size_t cnt = 0; cnt < gatherDims.size(); cnt++) { |
| 116 | + AffineMap currentMap = |
| 117 | + AffineMap::get(/*dimCount=*/dstRank, /*symbolCount=*/0, dimExprs, |
| 118 | + rewriter.getContext()); |
| 119 | + affineMaps.emplace_back(currentMap); |
| 120 | + } |
| 121 | + affineMaps.emplace_back(rewriter.getMultiDimIdentityMap(dstRank)); |
| 122 | + |
| 123 | + // create iterater types array |
| 124 | + SmallVector<utils::IteratorType> iteratorTypesArray( |
| 125 | + dstRank, utils::IteratorType::parallel); |
| 126 | + |
| 127 | + // check whether the gather op is valid |
| 128 | + size_t srcRank = gatherOp.getSourceType().getShape().size(); |
| 129 | + assert(((indexTensorSize.size() - 1) + srcRank == dstRank || |
| 130 | + (indexTensorSize.size() - 1) + srcRank == |
| 131 | + dstRank + gatherDims.size()) && |
| 132 | + "Expected: index_size - 1 + source_size == dst_size or dst_szie - " |
| 133 | + "gather_size. \n"); |
| 134 | + rewriter.replaceOpWithNewOp<linalg::GenericOp>( |
| 135 | + gatherOp, TypeRange(dstType), indexTensors, ValueRange{dstTensor}, |
| 136 | + affineMaps, iteratorTypesArray, |
| 137 | + [&](OpBuilder &b, Location loc, ValueRange args) { |
| 138 | + SmallVector<Value> indexValues(srcRank); |
| 139 | + bool isShrinkDst = (indexTensorSize.size() - 1) + srcRank == |
| 140 | + dstRank + gatherDims.size(); |
| 141 | + int cnt = 0; |
| 142 | + for (auto i = indexTensorSize.size() - 1; i < dstRank; i++) { |
| 143 | + while (isShrinkDst && |
| 144 | + llvm::find(gatherDims, cnt) != gatherDims.end()) { |
| 145 | + cnt++; |
| 146 | + } |
| 147 | + indexValues[cnt] = b.create<linalg::IndexOp>(loc, i); |
| 148 | + cnt++; |
| 149 | + } |
| 150 | + for (auto &&[i, dim] : llvm::enumerate(gatherDims)) { |
| 151 | + indexValues[dim] = args[i]; |
| 152 | + } |
| 153 | + |
| 154 | + Value extract = b.create<tensor::ExtractOp>(loc, gatherOp.getSource(), |
| 155 | + indexValues); |
| 156 | + b.create<linalg::YieldOp>(loc, extract); |
| 157 | + }); |
| 158 | + return success(); |
| 159 | + } |
| 160 | +}; |
| 161 | + |
| 162 | +/// DecomposeTensorOperationPass is a pass that decompose some tensor |
| 163 | +/// operations like tensor.gather, tensor.concat. |
| 164 | +struct DecomposeTensorOperationPass |
| 165 | + : public impl::DecomposeTensorOperationBase<DecomposeTensorOperationPass> { |
| 166 | + void runOnOperation() final { |
| 167 | + auto *ctx = &getContext(); |
| 168 | + RewritePatternSet patterns(ctx); |
| 169 | + |
| 170 | + patterns.add<DecomposeGatherOp>(patterns.getContext()); |
| 171 | + tensor::populateDecomposeTensorConcatPatterns(patterns); |
| 172 | + |
| 173 | + if (failed(applyPatternsAndFoldGreedily(getOperation(), |
| 174 | + std::move(patterns)))) { |
| 175 | + return signalPassFailure(); |
| 176 | + } |
| 177 | + } |
| 178 | +}; |
| 179 | +} // namespace |
| 180 | +} // namespace gc |
| 181 | +} // namespace mlir |
0 commit comments