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/client/lib/sorting.h"
17 #include "tensorflow/compiler/xla/client/lib/comparators.h"
18 #include "tensorflow/compiler/xla/client/xla_builder.h"
19 #include "tensorflow/compiler/xla/shape_util.h"
20 #include "tensorflow/compiler/xla/util.h"
21
22 namespace xla {
23
TopK(XlaOp input,int64 k)24 XlaOp TopK(XlaOp input, int64 k) {
25 XlaBuilder* const builder = input.builder();
26 return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> {
27 TF_ASSIGN_OR_RETURN(Shape input_shape, builder->GetShape(input));
28 int last_dim = input_shape.dimensions_size() - 1;
29
30 Shape iota_shape =
31 ShapeUtil::MakeShape(S32, AsInt64Slice(input_shape.dimensions()));
32 XlaOp iota_s32 = Iota(builder, iota_shape, last_dim);
33 auto input_dims = input_shape.dimensions();
34 // TODO(b/122298745): Get rid of Neg() and use CreateScalarGtComputation
35 // once the TPU backend supports the comparison computations.
36 XlaOp sort_result =
37 Sort({Neg(input), iota_s32},
38 CreateScalarLtComputation({input_shape.element_type(), S32},
39 iota_s32.builder()),
40 last_dim, /*is_stable=*/true);
41 std::vector<int64> start_indices(input_shape.dimensions_size(), 0);
42 std::vector<int64> limit_indices(input_dims.begin(), input_dims.end());
43 limit_indices[last_dim] = k;
44 std::vector<int64> strides(input_shape.dimensions_size(), 1);
45
46 XlaOp values = Neg(Slice(GetTupleElement(sort_result, 0), start_indices,
47 limit_indices, strides));
48 XlaOp indices = Slice(GetTupleElement(sort_result, 1), start_indices,
49 limit_indices, strides);
50 return Tuple(builder, {values, indices});
51 });
52 }
53
54 } // namespace xla
55