1 /* Copyright 2021 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/all_reduce_key.h"
17
18 #include "tensorflow/compiler/xla/service/hlo_casting_utils.h"
19 #include "tensorflow/compiler/xla/service/hlo_instructions.h"
20
21 namespace xla {
22
23 // Returns a key that will be equal for all-reduce instructions that are
24 // compatible with each other, and hence might be combined, or different if not.
GetAllReduceKey(const HloInstruction * instruction,const HloDomainMap * domain_map,bool ignore_replica_groups)25 std::optional<AllReduceKey> GetAllReduceKey(const HloInstruction* instruction,
26 const HloDomainMap* domain_map,
27 bool ignore_replica_groups) {
28 if (instruction->opcode() != HloOpcode::kAllReduce &&
29 instruction->opcode() != HloOpcode::kReduceScatter) {
30 return std::nullopt;
31 }
32
33 if (instruction->to_apply()->instruction_count() != 3 ||
34 instruction->to_apply()->num_parameters() != 2) {
35 VLOG(1) << "Skipping due to non-trivial reduction function.";
36 return std::nullopt;
37 }
38
39 const auto* ar = Cast<HloAllReduceInstructionBase>(instruction);
40
41 std::vector<std::vector<int64_t>> replica_groups;
42 if (!ignore_replica_groups) {
43 replica_groups.reserve(ar->replica_groups().size());
44 for (const ReplicaGroup& replica_group : ar->replica_groups()) {
45 replica_groups.push_back(
46 std::vector<int64_t>(replica_group.replica_ids().begin(),
47 replica_group.replica_ids().end()));
48 }
49 }
50
51 const HloInstruction* to_apply_root = ar->to_apply()->root_instruction();
52 // Domain metadata id returned by `GetDomainMetadataId` is guaranteed to be >=
53 // 0, so use -1 when we don't need to track domain metadata id.
54 int64_t domain_metadata_id =
55 domain_map ? domain_map->GetDomainMetadataId(ar) : -1;
56 return AllReduceKey{
57 to_apply_root->opcode(), to_apply_root->shape().element_type(),
58 domain_metadata_id, ar->channel_id().has_value(),
59 ar->use_global_device_ids(), replica_groups};
60 }
61
62 } // namespace xla
63