1 /* Copyright 2018 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 "tensorflow/compiler/xla/service/hlo_domain_isolator.h"
17
18 #include "tensorflow/compiler/xla/map_util.h"
19 #include "tensorflow/compiler/xla/service/hlo_computation.h"
20 #include "tensorflow/compiler/xla/service/hlo_graph_dumper.h"
21 #include "tensorflow/compiler/xla/service/hlo_opcode.h"
22 #include "tensorflow/compiler/xla/types.h"
23
24 namespace xla {
25
26 namespace {
27
RunInternal(HloModule * module,HloDomainIsolator::DomainCreator * creator)28 StatusOr<bool> RunInternal(HloModule* module,
29 HloDomainIsolator::DomainCreator* creator) {
30 int64 added_domains = 0;
31 for (HloComputation* computation : module->computations()) {
32 // Walk in post order and place all the required kDomain instructions.
33 for (HloInstruction* instruction :
34 computation->MakeInstructionPostOrder()) {
35 if (instruction->opcode() == HloOpcode::kDomain) {
36 continue;
37 }
38 for (HloInstruction* operand : instruction->unique_operands()) {
39 // When applying multiple domains, we could end up stacking more than
40 // one in one edge, so here we want to build the effective
41 // (kDomain-less) instruction->operand edge.
42 HloInstruction* root = operand;
43 while (root->opcode() == HloOpcode::kDomain) {
44 root = root->mutable_operand(0);
45 }
46 // Check whether a kDomain is necessary between instruction and operand.
47 HloInstruction* domain = (*creator)(instruction, root, operand);
48 if (domain != nullptr) {
49 VLOG(4) << "New domain: " << domain->ToString();
50 TF_RETURN_IF_ERROR(operand->ReplaceUseWith(instruction, domain));
51 ++added_domains;
52 }
53 }
54 }
55 }
56 VLOG(3) << "Added " << added_domains << " kDomain instructions";
57 return added_domains > 0;
58 }
59
60 } // namespace
61
HloDomainIsolator(DomainCreatorFactory creator_factory)62 HloDomainIsolator::HloDomainIsolator(DomainCreatorFactory creator_factory)
63 : creator_factory_(std::move(creator_factory)) {}
64
Run(HloModule * module)65 StatusOr<bool> HloDomainIsolator::Run(HloModule* module) {
66 DomainCreator creator = creator_factory_();
67 return RunInternal(module, &creator);
68 }
69
70 } // namespace xla
71