1 /* Copyright 2019 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 "mlir/IR/PatternMatch.h" // from @llvm-project
17 #include "mlir/Pass/Pass.h" // from @llvm-project
18 #include "mlir/Transforms/GreedyPatternRewriteDriver.h" // from @llvm-project
19 #include "tensorflow/compiler/mlir/tensorflow/transforms/decompose_resource_ops.h"
20 #include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
21
22 namespace mlir {
23 namespace TFDevice {
24 namespace {
25
26 // A pass that decomposes composite resource operations into primitive ones like
27 // ReadVariableOp, AssignVariableOp and other computations to facilitate
28 // transformations like resource op lifting.
29 //
30 // For example:
31 //
32 // tf.AssignAddVariableOp(%res, %0)
33 //
34 // Becomes
35 //
36 // %res_val = tf.ReadVariableOp(%res)
37 // %1 = tf.AddV2(%res_val, %0)
38 // tf.AssignVariableOp(%res, %1)
39 // NOTE: This pass does not support `use_locking=true` for a lot of resource
40 // operations. So decomposition may not be correct outside of backends like XLA,
41 // which automatically locks all resource variables.
42 struct DecomposeResourceOps
43 : public PassWrapper<DecomposeResourceOps, FunctionPass> {
runOnFunctionmlir::TFDevice::__anon46bc9c2a0111::DecomposeResourceOps44 void runOnFunction() override {
45 // Add lowering patterns to the list.
46 OwningRewritePatternList patterns;
47 mlir::TF::PopulateDecomposeResourceOpsPatterns(&getContext(), &patterns);
48
49 (void)applyPatternsAndFoldGreedily(getFunction(), std::move(patterns));
50 }
51 };
52
53 } // namespace
54
CreateDecomposeResourceOpsPass()55 std::unique_ptr<OperationPass<FuncOp>> CreateDecomposeResourceOpsPass() {
56 return std::make_unique<DecomposeResourceOps>();
57 }
58
59 } // namespace TFDevice
60 } // namespace mlir
61
62 static mlir::PassRegistration<mlir::TFDevice::DecomposeResourceOps> pass(
63 "tf-device-decompose-resource-ops",
64 "Decompose composite resource variable operations into primitive "
65 "Read/AssignVariableOp and raw computation");
66