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 #include <climits>
17 #include <cstdint>
18 #include <numeric>
19 
20 #include "absl/memory/memory.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/Support/Casting.h"
25 #include "llvm/Support/Debug.h"
26 #include "mlir/Dialect/Affine/Analysis/LoopAnalysis.h"  // from @llvm-project
27 #include "mlir/Dialect/Func/IR/FuncOps.h"  // from @llvm-project
28 #include "mlir/IR/Attributes.h"  // from @llvm-project
29 #include "mlir/IR/BuiltinTypes.h"  // from @llvm-project
30 #include "mlir/IR/OpImplementation.h"  // from @llvm-project
31 #include "mlir/IR/PatternMatch.h"  // from @llvm-project
32 #include "mlir/Pass/Pass.h"  // from @llvm-project
33 #include "mlir/Support/LLVM.h"  // from @llvm-project
34 #include "mlir/Support/LogicalResult.h"  // from @llvm-project
35 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"  // from @llvm-project
36 #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
37 #include "tensorflow/compiler/mlir/tensorflow/transforms/passes_detail.h"
38 #include "tensorflow/core/util/matmul_bcast.h"
39 
40 namespace mlir {
41 namespace TF {
42 
43 namespace {
44 
45 // Replace TF BatchMatMul by TF Einsum op
46 template <typename BatchMatMulOpType>
47 class ConvertTFBatchMatMulToEinsumOp
48     : public OpRewritePattern<BatchMatMulOpType> {
49   using OpRewritePattern<BatchMatMulOpType>::OpRewritePattern;
50 
matchAndRewrite(BatchMatMulOpType op,PatternRewriter & rewriter) const51   LogicalResult matchAndRewrite(BatchMatMulOpType op,
52                                 PatternRewriter& rewriter) const override {
53     Value input_lhs = op.x();
54     Value input_rhs = op.y();
55 
56     // LHS and RHS must be a ranked tensor type
57     auto lhs_type = input_lhs.getType().dyn_cast<RankedTensorType>();
58     auto rhs_type = input_rhs.getType().dyn_cast<RankedTensorType>();
59 
60     if (!lhs_type || !rhs_type) return failure();
61 
62     auto lhs_shape = lhs_type.getShape();
63     auto rhs_shape = rhs_type.getShape();
64 
65     // Ensure that input ranks are at least 2.
66     const int dims_a = lhs_shape.size();
67     const int dims_b = rhs_shape.size();
68     if (dims_a < 2 || dims_b < 2) {
69       return failure();
70     }
71 
72     // einsum equation for batchmatmul
73     std::string equation("...mk,...kn->...mn");
74     if (op.adj_x()) std::swap(equation[3], equation[4]);
75     if (op.adj_y()) std::swap(equation[6 + 3], equation[6 + 4]);
76 
77     rewriter.replaceOpWithNewOp<TF::EinsumOp>(
78         op, op.getType(),
79         /*inputs=*/ValueRange({input_lhs, input_rhs}),
80         /*equation=*/equation);
81 
82     return success();
83   }
84 };
85 
86 struct BatchMatMulToEinsumPass
87     : public BatchMatMulToEinsumPassBase<BatchMatMulToEinsumPass> {
88   void runOnOperation() override;
89 };
90 
runOnOperation()91 void BatchMatMulToEinsumPass::runOnOperation() {
92   RewritePatternSet patterns(&getContext());
93   auto func = getOperation();
94 
95   patterns.add<ConvertTFBatchMatMulToEinsumOp<TF::BatchMatMulOp>,
96                ConvertTFBatchMatMulToEinsumOp<TF::BatchMatMulV2Op>>(
97       &getContext());
98   (void)applyPatternsAndFoldGreedily(func, std::move(patterns));
99 }
100 
101 }  // namespace
102 
CreateBatchMatMulToEinsumPass()103 std::unique_ptr<OperationPass<func::FuncOp>> CreateBatchMatMulToEinsumPass() {
104   return std::make_unique<BatchMatMulToEinsumPass>();
105 }
106 
107 }  // namespace TF
108 }  // namespace mlir
109