aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/compiler/xla/index_util.cc
blob: 3fadabcf5207097aa875d654320b930b1ed94ad3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/xla/index_util.h"

#include <algorithm>
#include <string>

#include "absl/strings/str_join.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/platform/logging.h"

namespace xla {

/* static */ int64 IndexUtil::MultidimensionalIndexToLinearIndex(
    const Shape& shape, absl::Span<const int64> multi_index) {
  DCHECK_EQ(shape.dimensions_size(), multi_index.size());
  // Padding and nested layouts not supported yet.
  DCHECK_EQ(0, shape.layout().padded_dimensions_size());

  for (size_t i = 0; i < multi_index.size(); ++i) {
    DCHECK_GE(multi_index[i], 0);
    DCHECK_LT(multi_index[i], shape.dimensions(i))
        << "indexing beyond extent in dimension " << i << ":"
        << "\n\tindex: " << absl::StrJoin(multi_index, ",")
        << "\n\tshape: " << ShapeUtil::HumanString(shape);
  }

  // Let the array be sized like so for dimensions i from 0 to n-1:
  //
  //   [D{n-1} x D{n-2} x .. x D{0}]
  //
  // Let the order of the dimensions in the minor_to_major field in
  // Layout be:
  //
  //   L(0), L(1), ... , L(n-1)
  //
  // where L(0) is the most-minor dimension and L(n-1) the most-major. The
  // multidimensional index:
  //
  //   [I{0}, I{1}, ... , I{n-1}]
  //
  // then corresponds to the following linear index:
  //
  // linear_index =
  //   (((  ... + I{L(2)}) * D{L(1)} + I{L(1)}) * D{L(0)} + I{L(0)}
  //
  // or equivalently:
  //
  // linear_index =
  //   I{L(n-1)} * (D{L(n-2)} * D{L(n-3)} * D{L(n-4)} *     ....    D{L(0)}) +
  //   I{L(n-2)} *             (D{L(n-3)} * D{L(n-4)} *     ....    D{L(0)}) +
  //   I{L(n-3)} *                         (D{L(n-4)} *     ....    D{L(0)}) +
  //                                   ...                                   +
  //   I{L(2)} *                                         (D{L(1)} * D{L(0)}) +
  //   I{L(1)} *                                                    D{L(0)}  +
  //   I{L(0)}
  //
  // We compute the linear index value by accumulating the terms above from
  // I{L(0)} up to I{L(n-1)}. Scale accumulates the product term D{L(0}} *
  // D{L(1)} * ...

  // Scale factor holding the growing product of D{L(i)} terms.
  int64 scale = 1;
  int64 linear_index = 0;
  bool first = true;
  for (auto dimension : LayoutUtil::MinorToMajor(shape)) {
    if (first) {
      // Avoid two multiplies on the first loop iteration
      linear_index = multi_index[dimension];
      scale = shape.dimensions(dimension);
      first = false;
    } else {
      linear_index += scale * multi_index[dimension];
      scale *= shape.dimensions(dimension);
    }
  }
  return linear_index;
}

/* static */ std::vector<int64> IndexUtil::LinearIndexToMultidimensionalIndex(
    const Shape& shape, int64 linear_index) {
  // Padding and nested layouts not supported yet.
  DCHECK_EQ(0, shape.layout().padded_dimensions_size());
  DCHECK_GE(linear_index, 0);
  DCHECK_LT(linear_index, ShapeUtil::ElementsIn(shape));

  // The following formula computes each element of the multidimensional index
  // (See comments in MultidimensionalIndexToLinearIndex for notation):
  //
  // I{L(0)} = linear_index % D{L(0)}
  // I{L(1)} = (linear_index / D{L(0)}) % D{L(1)}
  // I{L(2)} = (linear_index / (D{L(0)} * D{L(1)})) % D{L(2)}
  // ...
  std::vector<int64> multi_index(shape.dimensions_size());

  // Accumulated product D{L(0)} * D{L(1)} * ...
  int64 divisor = 1;
  for (auto dimension : LayoutUtil::MinorToMajor(shape)) {
    multi_index[dimension] =
        (linear_index / divisor) % shape.dimensions(dimension);
    divisor *= shape.dimensions(dimension);
  }
  return multi_index;
}

/* static */ bool IndexUtil::BumpIndices(const Shape& shape,
                                         absl::Span<int64> indices) {
  for (int64 dimno = indices.size() - 1; dimno >= 0; --dimno) {
    int64 limit = shape.dimensions(dimno);
    if (indices[dimno] + 1 < limit) {
      indices[dimno]++;
      std::fill(indices.begin() + dimno + 1, indices.end(), 0);
      return true;
    }
  }
  return false;
}

/* static */ int64 IndexUtil::GetDimensionStride(const Shape& shape,
                                                 int64 dimension) {
  int64 pdim_size = LayoutUtil::PaddedDimensions(shape).size();
  int64 stride = 1;
  DCHECK(pdim_size == 0 || pdim_size == shape.dimensions_size());
  for (auto dim : LayoutUtil::MinorToMajor(shape)) {
    if (dim == dimension) {
      break;
    }
    if (pdim_size == 0) {
      stride *= shape.dimensions(dim);
    } else {
      stride *= LayoutUtil::PaddedDimension(shape, dim);
    }
  }
  return stride;
}

/* static */ bool IndexUtil::IndexInBounds(const Shape& shape,
                                           absl::Span<const int64> index) {
  int64 rank = ShapeUtil::Rank(shape);
  if (rank != index.size()) {
    return false;
  }
  for (int64 d = 0; d < rank; ++d) {
    if (index[d] >= shape.dimensions(d)) {
      return false;
    }
  }
  return true;
}

/* static */ int IndexUtil::CompareIndices(absl::Span<const int64> lhs,
                                           absl::Span<const int64> rhs) {
  int64 rank = lhs.size();
  CHECK_EQ(rhs.size(), rank);
  for (int64 dim = 0; dim < rank; ++dim) {
    if (lhs[dim] < rhs[dim]) {
      return -1;
    } else if (lhs[dim] > rhs[dim]) {
      return 1;
    }
  }
  return 0;
}

}  // namespace xla