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