1 /* Copyright 2017 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/permutation_util.h"
17
18 #include "absl/algorithm/container.h"
19 #include "absl/container/inlined_vector.h"
20
21 namespace xla {
22
IsPermutation(absl::Span<const int64> permutation)23 bool IsPermutation(absl::Span<const int64> permutation) {
24 absl::InlinedVector<bool, 8> seen(permutation.size(), false);
25 for (int64_t p : permutation) {
26 if (p < 0 || p >= permutation.size() || seen[p]) {
27 return false;
28 }
29 seen[p] = true;
30 }
31 return true;
32 }
33
InversePermutation(absl::Span<const int64> input_permutation)34 std::vector<int64> InversePermutation(
35 absl::Span<const int64> input_permutation) {
36 DCHECK(IsPermutation(input_permutation));
37 std::vector<int64> output_permutation(input_permutation.size(), -1);
38 for (size_t i = 0; i < input_permutation.size(); ++i) {
39 output_permutation.at(input_permutation.at(i)) = i;
40 }
41 return output_permutation;
42 }
43
ComposePermutations(absl::Span<const int64> p1,absl::Span<const int64> p2)44 std::vector<int64> ComposePermutations(absl::Span<const int64> p1,
45 absl::Span<const int64> p2) {
46 CHECK_EQ(p1.size(), p2.size());
47 std::vector<int64> output;
48 output.reserve(p1.size());
49 for (size_t i = 0; i < p1.size(); ++i) {
50 output.push_back(p1.at(p2.at(i)));
51 }
52 return output;
53 }
54
IsIdentityPermutation(absl::Span<const int64> permutation)55 bool IsIdentityPermutation(absl::Span<const int64> permutation) {
56 for (int64_t i = 0; i < permutation.size(); ++i) {
57 if (permutation[i] != i) {
58 return false;
59 }
60 }
61 return true;
62 }
63
64 } // namespace xla
65