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 #include "tensorflow/compiler/xla/service/broadcast_canonicalizer.h"
17
18 #include "tensorflow/compiler/xla/service/hlo_creation_utils.h"
19
20 namespace xla {
21
BroadcastCanonicalizer()22 BroadcastCanonicalizer::BroadcastCanonicalizer() {}
23
Run(HloModule * module,const absl::flat_hash_set<absl::string_view> & execution_threads)24 StatusOr<bool> BroadcastCanonicalizer::Run(
25 HloModule* module,
26 const absl::flat_hash_set<absl::string_view>& execution_threads) {
27 bool changed = false;
28
29 // Sort broadcast dims. Then insert a transpose on the broadcast to get the
30 // original shape back.
31 for (const auto& computation :
32 module->MakeNonfusionComputations(execution_threads)) {
33 for (HloInstruction* hlo : computation->MakeInstructionPostOrder()) {
34 if (hlo->opcode() != HloOpcode::kBroadcast) {
35 continue;
36 }
37 if (absl::c_is_sorted(hlo->dimensions())) {
38 continue;
39 }
40 std::vector<int64_t> new_dims(hlo->dimensions().begin(),
41 hlo->dimensions().end());
42 std::vector<int64_t> original_dims(hlo->dimensions().begin(),
43 hlo->dimensions().end());
44
45 std::vector<int64_t> new_broadcast_dims(hlo->shape().dimensions().begin(),
46 hlo->shape().dimensions().end());
47 absl::c_sort(new_dims);
48 const int64_t rank = hlo->shape().rank();
49 for (int i = 0; i < new_dims.size(); ++i) {
50 new_broadcast_dims[new_dims[i]] =
51 hlo->operand(0)->shape().dimensions(i);
52 }
53
54 auto new_broadcast = MakeBroadcastHlo(hlo->mutable_operand(0), new_dims,
55 new_broadcast_dims);
56 std::vector<int64_t> transpose_dims(rank);
57 absl::c_iota(transpose_dims, 0);
58 for (int i = 0; i < new_dims.size(); ++i) {
59 transpose_dims[new_dims[i]] = new_dims[std::distance(
60 original_dims.begin(), absl::c_find(original_dims, new_dims[i]))];
61 }
62 TF_ASSIGN_OR_RETURN(new_broadcast,
63 MakeTransposeHlo(new_broadcast, transpose_dims));
64 TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, new_broadcast));
65 changed = true;
66 }
67 }
68 return changed;
69 }
70
71 } // namespace xla
72