1 /* Copyright 2021 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 #include "tensorflow/compiler/mlir/lite/utils/fake_quant_utils.h"
17
18 #include <string>
19
20 #include "mlir/Dialect/Quant/QuantTypes.h" // from @llvm-project
21 #include "mlir/IR/OperationSupport.h" // from @llvm-project
22 #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
23 #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops_a_m.h"
24
25 namespace mlir {
26 namespace TFL {
27
28 // Moves the TF operations out from the tfl.TFCustomOps wrappers inside the
29 // function. This is a no-op for the ops which are not wrapped.
UnwrapTFCustomOps(func::FuncOp fn,OpBuilder & builder)30 LogicalResult UnwrapTFCustomOps(func::FuncOp fn, OpBuilder& builder) {
31 llvm::SmallVector<Operation*, 4> wrapped_ops;
32 fn.walk([&](TFL::CustomTfOp custom_op) {
33 auto* real_op = &custom_op.body().front().front();
34 wrapped_ops.push_back(real_op);
35 });
36
37 for (auto* op : wrapped_ops) {
38 auto parent_op = op->getParentOfType<TFL::CustomTfOp>();
39 if (!parent_op) continue;
40 builder.setInsertionPoint(parent_op);
41
42 // Recreate the operation by using the wrapper's operands and return types.
43 // TODO(fengliuai): copy the regions.
44 OperationState state(op->getLoc(), op->getName().getStringRef(),
45 parent_op->getOperands(), parent_op->getResultTypes(),
46 op->getAttrs(), op->getSuccessors());
47 Operation* inlined = builder.create(state);
48
49 parent_op->replaceAllUsesWith(inlined);
50 parent_op->erase();
51 }
52 return success();
53 }
54
55 // Three instances of the rule to cover the three different types of
56 // TF::FakeQuant operators
57 using PreparePerTensorFakeQuant = InsertTFLQuantOpsAfterTFFakeQuantOp<
58 TF::FakeQuantWithMinMaxVarsOp, /*PerAxis=*/false,
59 FetchConstantMinMaxInputs<TF::FakeQuantWithMinMaxVarsOp>>;
60
61 using PreparePerChannelFakeQuant = InsertTFLQuantOpsAfterTFFakeQuantOp<
62 TF::FakeQuantWithMinMaxVarsPerChannelOp, /*PerAxis=*/true,
63 FetchConstantMinMaxInputs<TF::FakeQuantWithMinMaxVarsPerChannelOp>>;
64
65 using PreparePerTensorFakeQuantWithMinMaxArgs =
66 InsertTFLQuantOpsAfterTFFakeQuantOp<
67 TF::FakeQuantWithMinMaxArgsOp, /*PerAxis=*/false,
68 FetchMinMaxAttrs<TF::FakeQuantWithMinMaxArgsOp>>;
69
70 // Removes the wrapper of the tf.FakeQuant* ops and creates the tfl.quantize
71 // and tfl.dequantize pairs before tf.FakeQuant* being foled.
ConvertFakeQuantOps(func::FuncOp func,MLIRContext * ctx,bool use_fake_quant_num_bits)72 LogicalResult ConvertFakeQuantOps(func::FuncOp func, MLIRContext* ctx,
73 bool use_fake_quant_num_bits) {
74 OpBuilder builder(func);
75 if (failed(UnwrapTFCustomOps(func, builder))) {
76 return failure();
77 }
78
79 // Insert the tfl.quantize/tfl.dequantize ops after the tf.FakeQuant* ops to
80 // preserve the quantization parameters.
81 func.walk([&](Operation* op) {
82 if (auto fake_quant = llvm::dyn_cast<TF::FakeQuantWithMinMaxArgsOp>(op)) {
83 (void)PreparePerTensorFakeQuantWithMinMaxArgs(use_fake_quant_num_bits)
84 .matchAndRewrite(fake_quant, builder);
85 } else if (auto fake_quant =
86 llvm::dyn_cast<TF::FakeQuantWithMinMaxVarsOp>(op)) {
87 (void)PreparePerTensorFakeQuant(use_fake_quant_num_bits)
88 .matchAndRewrite(fake_quant, builder);
89 } else if (auto fake_quant =
90 llvm::dyn_cast<TF::FakeQuantWithMinMaxVarsPerChannelOp>(
91 op)) {
92 (void)PreparePerChannelFakeQuant(use_fake_quant_num_bits)
93 .matchAndRewrite(fake_quant, builder);
94 }
95 });
96
97 return success();
98 }
99
AllTfFakeQuantOps()100 std::vector<std::string> AllTfFakeQuantOps() {
101 return {
102 mlir::TF::FakeQuantWithMinMaxVarsOp::getOperationName().str(),
103 mlir::TF::FakeQuantWithMinMaxVarsPerChannelOp::getOperationName().str(),
104 mlir::TF::FakeQuantWithMinMaxArgsOp::getOperationName().str()};
105 }
106
107 } // end namespace TFL
108 } // end namespace mlir
109