1 /* Copyright 2022 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 pass sets the device ordinal attribute of the required op using
17 // the replica id attribute.
18 
19 #include <memory>
20 #include <utility>
21 
22 #include "llvm/Support/Casting.h"
23 #include "mlir/Pass/Pass.h"  // from @llvm-project
24 #include "tensorflow/compiler/mlir/tensorflow/ir/tf_device.h"
25 #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
26 #include "tensorflow/compiler/mlir/tensorflow/transforms/passes_detail.h"
27 #include "tensorflow/compiler/mlir/tensorflow/utils/device_util.h"
28 
29 namespace mlir {
30 namespace TFDevice {
31 namespace {
32 constexpr char kReplicaIdAttr[] = "_xla_replica_id";
33 constexpr char kDeviceOrdinalAttr[] = "device_ordinal";
34 
35 struct ReplicaIDToDeviceOrdinalPass
36     : public TF::ReplicaIDToDeviceOrdinalPassBase<
37           ReplicaIDToDeviceOrdinalPass> {
38   void runOnOperation() override;
39 };
40 
41 // Returns whether op requires `device_ordinal` attribute.
RequiresDeviceOrdinalAttribute(Operation * op)42 bool RequiresDeviceOrdinalAttribute(Operation* op) {
43   return (llvm::isa<TF::EnqueueTPUEmbeddingSparseTensorBatchOp,
44                     TF::EnqueueTPUEmbeddingRaggedTensorBatchOp,
45                     TF::EnqueueTPUEmbeddingArbitraryTensorBatchOp>(op) &&
46           op->hasAttr(kDeviceOrdinalAttr) && op->hasAttr(kReplicaIdAttr));
47 }
48 
runOnOperation()49 void ReplicaIDToDeviceOrdinalPass::runOnOperation() {
50   const Dialect* tf_dialect = getContext().getLoadedDialect("tf");
51   if (!tf_dialect) {
52     getOperation().emitError() << "'tf' dialect is not registered";
53     return signalPassFailure();
54   }
55 
56   // Get the number of devices per host.
57   int device_num = 0;
58   mlir::TF::RuntimeDevices devices;
59   if (failed(tensorflow::GetDevicesFromOp(
60           getOperation()->getParentOfType<ModuleOp>(), &devices)))
61     return signalPassFailure();
62   for (const auto& device_name : devices.device_names()) {
63     if (device_name.has_type && device_name.type == "TPU") ++device_num;
64   }
65 
66   if (device_num == 0) return;
67 
68   llvm::SmallVector<Operation*, 4> require_device_ordinal_ops;
69   getOperation().walk([&](Operation* op) {
70     if (RequiresDeviceOrdinalAttribute(op)) {
71       require_device_ordinal_ops.push_back(op);
72     }
73   });
74 
75   if (require_device_ordinal_ops.size() == 1) {
76     // If there is only one op which requires the device ordinal being set,
77     // set the device ordinal to 0. Note: This is for single device use case
78     // (eg. pf megacore) for which `_xla_replica_id` isn't set via the
79     // replicate_to_islands pass.
80     Operation* op = require_device_ordinal_ops.front();
81     if (op->getAttrOfType<IntegerAttr>(kDeviceOrdinalAttr).getInt() == -1) {
82       OpBuilder builder(op);
83       op->setAttr(kDeviceOrdinalAttr, builder.getI64IntegerAttr(0));
84     }
85   } else {
86     // If the device ordinal attribute is -1, set it with the replica id
87     // attribute modulo the number of TPU cores in the system.
88     for (auto op : require_device_ordinal_ops) {
89       if (op->getAttrOfType<IntegerAttr>(kDeviceOrdinalAttr).getInt() == -1) {
90         OpBuilder builder(op);
91         int device_ordinal =
92             op->getAttrOfType<IntegerAttr>(kReplicaIdAttr).getInt() %
93             device_num;
94         op->setAttr(kDeviceOrdinalAttr,
95                     builder.getI64IntegerAttr(device_ordinal));
96       }
97     }
98   }
99 }
100 }  // namespace
101 
102 std::unique_ptr<OperationPass<func::FuncOp>>
CreateReplicaIDToDeviceOrdinalPass()103 CreateReplicaIDToDeviceOrdinalPass() {
104   return std::make_unique<ReplicaIDToDeviceOrdinalPass>();
105 }
106 
107 }  // namespace TFDevice
108 }  // namespace mlir
109