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 "mlir/IR/BuiltinOps.h" // from @llvm-project 17 #include "mlir/Pass/PassManager.h" // from @llvm-project 18 #include "mlir/Transforms/Passes.h" // from @llvm-project 19 #include "tensorflow/compiler/mlir/tensorflow/ir/tf_device.h" 20 #include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h" 21 #include "tensorflow/compiler/mlir/tensorflow/transforms/passes_detail.h" 22 #include "tensorflow/compiler/mlir/tensorflow/utils/tpu_rewrite_device_util.h" 23 24 namespace mlir { 25 namespace TFTPU { 26 27 namespace { 28 29 constexpr char kTPUReplicateAttr[] = "_tpu_replicate"; 30 constexpr char kDeviceAttr[] = "device"; 31 32 class TPUCleanupClusterAttributesPass 33 : public TF::TPUCleanupClusterAttributesPassBase< 34 TPUCleanupClusterAttributesPass> { 35 public: runOnOperation()36 void runOnOperation() override { 37 getOperation().walk([](tf_device::ClusterOp cluster) { 38 cluster.walk([](Operation *op) { 39 if (isa<tf_device::ClusterOp>(op)) return; 40 op->removeAttr(kTPUReplicateAttr); 41 if (auto attr = op->getAttrOfType<StringAttr>(kDeviceAttr)) { 42 // Preserve device attribute if the op is placed on a replicated core 43 // device. Device attribute is used to infer the appropriate sharding 44 // within TPUs for this op. 45 // TODO(b/183598857): Use explicit sharding ops from the front-end. 46 // For example, dequeue ops generated by 47 // tensorflow/python/tpu/tpu_feed.py 48 if (!tensorflow::IsTPUReplicatedCore(attr.getValue()) && 49 !isa<tf_device::LaunchOp>(op)) { 50 op->removeAttr(kDeviceAttr); 51 } 52 } 53 }); 54 }); 55 } 56 }; 57 58 } // namespace 59 60 std::unique_ptr<OperationPass<ModuleOp>> CreateTPUClusterCleanupAttributesPass()61CreateTPUClusterCleanupAttributesPass() { 62 return std::make_unique<TPUCleanupClusterAttributesPass>(); 63 } 64 65 } // namespace TFTPU 66 } // namespace mlir 67