xref: /aosp_15_r20/external/tensorflow/tensorflow/compiler/mlir/tosa/transforms/fuse_bias_tf.cc (revision b6fb3261f9314811a0f4371741dbb8839866f948)
1 /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 // Fuse tf.Op + tf.BiasAdd and legalized to TOSA
17 
18 #include <climits>
19 #include <cstddef>
20 #include <cstdint>
21 #include <iterator>
22 #include <numeric>
23 
24 #include "mlir/Dialect/Tosa/IR/TosaOps.h"  // from @llvm-project
25 #include "mlir/IR/MLIRContext.h"  // from @llvm-project
26 #include "mlir/Pass/Pass.h"  // from @llvm-project
27 #include "mlir/Support/LogicalResult.h"  // from @llvm-project
28 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"  // from @llvm-project
29 #include "tensorflow/compiler/mlir/lite/quantization/ir/QuantOps.h"
30 #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
31 #include "tensorflow/compiler/mlir/tosa/transforms/legalize_common.h"
32 #include "tensorflow/compiler/mlir/tosa/transforms/passes.h"
33 
34 #define PASS_NAME "tosa-fuse-bias-tf"
35 #define DEBUG_TYPE PASS_NAME
36 
37 namespace mlir {
38 namespace tosa {
39 namespace {
40 
41 class FuseBiasTF : public TosaFusebiasTFPassBase<FuseBiasTF> {
42  public:
FuseBiasTF()43   explicit FuseBiasTF() {}
44   void runOnOperation() override;
45 };
46 
47 struct ConvertTFBiasAddOp : public RewritePattern {
ConvertTFBiasAddOpmlir::tosa::__anon750d0cda0111::ConvertTFBiasAddOp48   explicit ConvertTFBiasAddOp(MLIRContext* context)
49       : RewritePattern(TF::BiasAddOp::getOperationName(), 1, context) {}
50   LogicalResult matchAndRewrite(Operation* op,
51                                 PatternRewriter& rewriter) const override;
52 };
53 
54 // Replaces the following pattern:
55 //   %1 = tf.Conv2D (%ifm, %filter)
56 //   %2 = tf.BiasAdd(%1, %bias)
57 //   with
58 //   %1 = tosa.conv2d(%ifm, %filter, %bias)
59 //   This can also be done using the pair ot Pat<> options in
60 //   tf_optimize_patterns.td
61 //   However, this explicit code can handle both when the LHS or RHS is the
62 //   defining conv2d op.
63 // TODO: support other pattern. e.g. tf.DepthwiseConv2DNative
64 
matchAndRewrite(Operation * op,PatternRewriter & rewriter) const65 LogicalResult ConvertTFBiasAddOp::matchAndRewrite(
66     Operation* op, PatternRewriter& rewriter) const {
67   auto tf_biasadd_op = cast<TF::BiasAddOp>(op);
68 
69   auto output_type =
70       tf_biasadd_op.getResult().getType().dyn_cast<RankedTensorType>();
71   // Not a ranked tensor output
72   if (!output_type) return failure();
73 
74   auto value = tf_biasadd_op.value();
75   auto bias = tf_biasadd_op.bias();
76 
77   TF::Conv2DOp tf_conv2d_op =
78       dyn_cast_or_null<TF::Conv2DOp>(value.getDefiningOp());
79 
80   if (!tf_conv2d_op) {
81     return failure();
82   }
83 
84   // Sanity check to confirm rhs() has the expected shape of bias
85   auto filter_shape =
86       tf_conv2d_op.filter().getType().dyn_cast<RankedTensorType>().getShape();
87 
88   auto bias_shape = bias.getType().dyn_cast<RankedTensorType>().getShape();
89 
90   // Bias dimension must match filter output channels, where tf.conv2d's filter
91   // is [H, W, I, O]
92   if (filter_shape.back() != bias_shape.back()) return failure();
93 
94   // Bias tensor that feeds into tosa.conv2d must be rank 1
95   if (bias_shape.size() != 1) return failure();
96 
97   auto result = convertTFConv2DCommon(
98       rewriter, op, output_type, tf_conv2d_op.input(), tf_conv2d_op.filter(),
99       bias, tf_conv2d_op.strides(), tf_conv2d_op.dilations(),
100       tf_conv2d_op.explicit_paddings(), tf_conv2d_op.padding(),
101       tf_conv2d_op.data_format());
102 
103   if (!result) return failure();
104 
105   rewriter.replaceOp(op, {result.getValue()});
106 
107   return success();
108 }
109 
runOnOperation()110 void FuseBiasTF::runOnOperation() {
111   RewritePatternSet patterns(&getContext());
112   auto* ctx = &getContext();
113   auto func = getOperation();
114 
115   // Add the generated patterns to the list.
116   patterns.add<ConvertTFBiasAddOp>(ctx);
117   (void)applyPatternsAndFoldGreedily(func, std::move(patterns));
118 }
119 
120 }  // anonymous namespace
121 
createFuseBiasTFPass()122 std::unique_ptr<OperationPass<func::FuncOp>> createFuseBiasTFPass() {
123   return std::make_unique<FuseBiasTF>();
124 }
125 
126 }  // namespace tosa
127 
128 }  // namespace mlir
129