• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/Analysis/LoopAnalysis.h"  // from @llvm-project
27 #include "mlir/Dialect/StandardOps/IR/Ops.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/core/util/matmul_bcast.h"
38 
39 namespace mlir {
40 namespace TF {
41 
42 namespace {
43 
44 // Replace TF BatchMatMul by TF Einsum op
45 template <typename BatchMatMulOpType>
46 class ConvertTFBatchMatMulToEinsumOp
47     : public OpRewritePattern<BatchMatMulOpType> {
48   using OpRewritePattern<BatchMatMulOpType>::OpRewritePattern;
49 
matchAndRewrite(BatchMatMulOpType op,PatternRewriter & rewriter) const50   LogicalResult matchAndRewrite(BatchMatMulOpType op,
51                                 PatternRewriter& rewriter) const override {
52     Value input_lhs = op.x();
53     Value input_rhs = op.y();
54 
55     // LHS and RHS must be a ranked tensor type
56     auto lhs_type = input_lhs.getType().dyn_cast<RankedTensorType>();
57     auto rhs_type = input_rhs.getType().dyn_cast<RankedTensorType>();
58 
59     if (!lhs_type || !rhs_type) return failure();
60 
61     auto lhs_shape = lhs_type.getShape();
62     auto rhs_shape = rhs_type.getShape();
63 
64     // Ensure that input ranks are at least 2.
65     const int dims_a = lhs_shape.size();
66     const int dims_b = rhs_shape.size();
67     if (dims_a < 2 || dims_b < 2) {
68       return failure();
69     }
70 
71     // einsum equation for batchmatmul
72     std::string equation("...mk,...kn->...mn");
73     if (op.adj_x()) std::swap(equation[3], equation[4]);
74     if (op.adj_y()) std::swap(equation[6 + 3], equation[6 + 4]);
75 
76     rewriter.replaceOpWithNewOp<TF::EinsumOp>(
77         op, op.getType(),
78         /*inputs=*/ValueRange({input_lhs, input_rhs}),
79         /*equation=*/equation);
80 
81     return success();
82   }
83 };
84 
85 struct BatchMatMulToEinsumPass
86     : public PassWrapper<BatchMatMulToEinsumPass, FunctionPass> {
getArgumentmlir::TF::__anoncbcc07e60111::BatchMatMulToEinsumPass87   StringRef getArgument() const final { return "tf-batch-matmul-to-tf-einsum"; }
88 
getDescriptionmlir::TF::__anoncbcc07e60111::BatchMatMulToEinsumPass89   StringRef getDescription() const final {
90     return "Replace TF BatchMatMul op by TF Einsum op.";
91   }
92 
93   void runOnFunction() override;
94 };
95 
runOnFunction()96 void BatchMatMulToEinsumPass::runOnFunction() {
97   OwningRewritePatternList patterns(&getContext());
98   auto func = getFunction();
99 
100   patterns.insert<ConvertTFBatchMatMulToEinsumOp<TF::BatchMatMulOp>,
101                   ConvertTFBatchMatMulToEinsumOp<TF::BatchMatMulV2Op>>(
102       &getContext());
103   (void)applyPatternsAndFoldGreedily(func, std::move(patterns));
104 }
105 
106 PassRegistration<BatchMatMulToEinsumPass> pass;
107 }  // namespace
108 
CreateBatchMatMulToEinsumPass()109 std::unique_ptr<OperationPass<FuncOp>> CreateBatchMatMulToEinsumPass() {
110   return std::make_unique<BatchMatMulToEinsumPass>();
111 }
112 
113 }  // namespace TF
114 }  // namespace mlir
115