1//===- TransposeConv2D.cpp - Convolution transposition -------------------===//
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#include "mlir/Dialect/Func/IR/FuncOps.h"
10#include "mlir/Dialect/Linalg/IR/Linalg.h"
11#include "mlir/Dialect/MemRef/IR/MemRef.h"
12#include "mlir/Dialect/Tensor/IR/Tensor.h"
13#include "mlir/IR/BuiltinTypes.h"
14#include "mlir/IR/PatternMatch.h"
15#include "mlir/Transforms/DialectConversion.h"
16#include "llvm/ADT/SmallVector.h"
17
18namespace mlir {
19namespace linalg {
20namespace {
21// clang-format off
22/// Convolution converter that applies the following rewrite:
23///
24/// Before:
25///
26/// %0 = linalg.conv_2d_nhwc_fhwc {dilations = dense<1> : tensor<2xi64>,
27/// strides = dense<2> : tensor<2xi64>}
28/// ins (%input, %filter: tensor<1x4x4x6xf32>, tensor<8x2x2x6xf32>)
29/// outs (%init: tensor<1x2x2x8xf32>) -> tensor<1x2x2x8xf32>
30///
31/// After:
32///
33/// %cst = arith.constant 0.000000e+00 : f32
34/// %0 = tensor.empty() : tensor<2x2x6x8xf32>
35/// %1 = linalg.fill ins(%cst : f32) outs(%0 : tensor<2x2x6x8xf32>) -> tensor<2x2x6x8xf32>
36/// %transposed = linalg.transpose ins(%arg1 : tensor<8x2x2x6xf32>) outs(%1 : tensor<2x2x6x8xf32>)
37/// permutation = [1, 2, 3, 0]
38/// %2 = linalg.conv_2d_nhwc_hwcf {dilations = dense<1> : tensor<2xi64>, strides = dense<2> : tensor<2xi64>}
39/// ins(%arg0, %transposed : tensor<1x4x4x6xf32>, tensor<2x2x6x8xf32>) outs(%arg2 : tensor<1x2x2x8xf32>)
40/// -> tensor<1x2x2x8xf32>
41///
42/// with an analogous example for the quantized case.
43// clang-format on
44template <typename FHWCConvOp, typename HWCFConvOp>
45FailureOr<Operation *> transposeConv2DHelper(RewriterBase &rewriter,
46 FHWCConvOp op) {
47 // Construct a permutation of the filter tensor dimensions. For a 2D
48 // convolution this will be known statically as [1, 2, 3, 0].
49 SmallVector<int64_t> filterPerm = {1, 2, 3, 0};
50
51 // Create the type for the transposed filter tensor.
52 auto filter = op->getOperand(1);
53 auto filterTy = cast<ShapedType>(filter.getType());
54 SmallVector<int64_t> newFilterShape(filterPerm.size());
55 std::generate(std::begin(cont&: newFilterShape), std::end(cont&: newFilterShape),
56 [dim = 0, &filterTy, &filterPerm]() mutable {
57 return filterTy.getShape()[filterPerm[dim++]];
58 });
59
60 // Because linalg.transpose expects an "out" parameter we need to pass it a
61 // tensor of zeros of the result type so here we construct that tensor.
62 auto inputType = op->getOperand(0).getType();
63 auto elementTy = cast<ShapedType>(inputType).getElementType();
64 auto loc = op->getLoc();
65
66 const auto isTensorOp = isa<TensorType>(inputType);
67 Value input;
68 if (isTensorOp) {
69
70 input = rewriter.create<tensor::EmptyOp>(loc, newFilterShape, elementTy)
71 .getResult();
72 } else {
73 input = rewriter
74 .create<memref::AllocOp>(
75 loc, MemRefType::get(newFilterShape, elementTy))
76 .getResult();
77 }
78
79 // We can then construct the transposition on our filter.
80 auto transpose =
81 rewriter.create<linalg::TransposeOp>(loc, filter, input, filterPerm);
82
83 Value newFilter;
84 if (isTensorOp) {
85 newFilter = transpose.getResult()[0];
86 } else {
87 newFilter = input;
88 }
89
90 SmallVector<Value> newInputs{op.getInputs()};
91 // The filter is always the second input argument, the other inputs can be
92 // left as they are.
93 newInputs[1] = newFilter;
94 // It is possible the convolution doesn't define any results and its
95 // out argument is just used instead.
96 SmallVector<Type> resultTy;
97 if (op.getNumResults()) {
98 resultTy.push_back(Elt: op->getResult(0).getType());
99 }
100 auto newConv =
101 rewriter.create<HWCFConvOp>(loc, resultTy, newInputs, op.getOutputs(),
102 op.getStrides(), op.getDilations());
103 rewriter.replaceOp(op, newConv);
104 return newConv.getOperation();
105}
106
107template <typename FHWCConvOp, typename HWCFConvOp>
108class ConvConverter : public OpRewritePattern<FHWCConvOp> {
109public:
110 using OpRewritePattern<FHWCConvOp>::OpRewritePattern;
111 LogicalResult matchAndRewrite(FHWCConvOp op,
112 PatternRewriter &rewriter) const final {
113 if (failed(transposeConv2DHelper<FHWCConvOp, HWCFConvOp>(rewriter, op))) {
114 return failure();
115 }
116 return success();
117 }
118};
119} // namespace
120
121FailureOr<Operation *> transposeConv2D(RewriterBase &rewriter,
122 linalg::Conv2DNhwcFhwcOp op) {
123
124 return transposeConv2DHelper<linalg::Conv2DNhwcFhwcOp,
125 linalg::Conv2DNhwcHwcfOp>(rewriter, op);
126}
127
128FailureOr<Operation *> transposeConv2D(RewriterBase &rewriter,
129 linalg::Conv2DNhwcFhwcQOp op) {
130
131 return transposeConv2DHelper<linalg::Conv2DNhwcFhwcQOp,
132 linalg::Conv2DNhwcHwcfQOp>(rewriter, op);
133}
134
135void populateTransposeConv2DPatterns(RewritePatternSet &patterns) {
136 MLIRContext *context = patterns.getContext();
137 patterns.insert<
138 ConvConverter<linalg::Conv2DNhwcFhwcOp, linalg::Conv2DNhwcHwcfOp>,
139 ConvConverter<linalg::Conv2DNhwcFhwcQOp, linalg::Conv2DNhwcHwcfQOp>>(
140 arg&: context);
141}
142} // namespace linalg
143} // namespace mlir
144

source code of mlir/lib/Dialect/Linalg/Transforms/TransposeConv2D.cpp