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 // This file implements device assignment in TF dialect.
17 #include "mlir/IR/Builders.h"
18 #include "mlir/Pass/Pass.h"
19 #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
20 #include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
21
22 namespace mlir {
23 namespace TF {
24 namespace {
25
26 class SimpleTFDeviceAssignmentPass
27 : public PassWrapper<SimpleTFDeviceAssignmentPass, FunctionPass> {
28 public:
29 SimpleTFDeviceAssignmentPass() = default;
SimpleTFDeviceAssignmentPass(const SimpleTFDeviceAssignmentPass &)30 SimpleTFDeviceAssignmentPass(const SimpleTFDeviceAssignmentPass&) {}
SimpleTFDeviceAssignmentPass(llvm::StringRef default_device)31 explicit SimpleTFDeviceAssignmentPass(llvm::StringRef default_device) {
32 default_device_ = std::string(default_device);
33 }
34
runOnFunction()35 void runOnFunction() override {
36 Builder builder(&getContext());
37 Dialect* tf = getContext().getLoadedDialect<TensorFlowDialect>();
38 getFunction().walk([&](Operation* op) {
39 if (auto device_attr = op->getAttrOfType<StringAttr>("device")) {
40 // We assign default device to ops with device attribute that is empty.
41 if (device_attr.getValue().empty()) {
42 op->setAttr("device", builder.getStringAttr(default_device_));
43 }
44 } else if (op->getDialect() == tf) {
45 // Assign default device to all ops in Tensorflow dialect that do not
46 // have device attribute.
47 op->setAttr("device", builder.getStringAttr(default_device_));
48 }
49 });
50 }
51
getArgument() const52 StringRef getArgument() const final { return "tf-simple-device-assignment"; }
53
getDescription() const54 StringRef getDescription() const final {
55 return "Simple device assignment in TF dialect.";
56 }
57
58 private:
59 Option<std::string> default_device_{
60 *this, "default-device", llvm::cl::desc("The default device to assign."),
61 llvm::cl::init("cpu")};
62 };
63
64 } // namespace
65
CreateSimpleTFDeviceAssignmentPass(llvm::StringRef default_device)66 std::unique_ptr<OperationPass<FuncOp>> CreateSimpleTFDeviceAssignmentPass(
67 llvm::StringRef default_device) {
68 return std::make_unique<SimpleTFDeviceAssignmentPass>(default_device);
69 }
70
71 static PassRegistration<SimpleTFDeviceAssignmentPass> register_pass;
72
73 } // namespace TF
74 } // namespace mlir
75