-
Notifications
You must be signed in to change notification settings - Fork 497
/
Copy pathop_topk.cpp
209 lines (174 loc) · 5.48 KB
/
op_topk.cpp
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <cmath>
#include <tuple>
#include <executorch/runtime/kernel/kernel_includes.h>
namespace torch {
namespace executor {
namespace native {
namespace {
bool check_topk_args(
const Tensor& in,
int64_t k,
int64_t dim,
Tensor& values,
Tensor& indices) {
ET_LOG_AND_RETURN_IF_FALSE(tensors_have_same_dtype(in, values));
ET_LOG_AND_RETURN_IF_FALSE(indices.scalar_type() == ScalarType::Long);
ET_LOG_AND_RETURN_IF_FALSE(tensor_has_dim(in, dim));
if (dim < 0) {
dim += nonzero_dim(in);
}
ET_LOG_MSG_AND_RETURN_IF_FALSE(
k >= 0 && k <= nonempty_size(in, dim), "selected index k out of range");
return true;
}
bool get_topk_target_size(
const Tensor& in,
int64_t k,
int64_t dim,
Tensor::SizesType* target_size,
size_t* target_dim) {
*target_dim = in.dim();
for (size_t i = 0; i < *target_dim; ++i) {
if (i == dim) {
target_size[i] = k;
} else {
target_size[i] = in.size(i);
}
}
return true;
}
template <typename T>
bool float_less_than(T x, T y) {
if constexpr (std::is_integral_v<T>) {
return x < y;
}
return (!std::isnan(x) && std::isnan(y)) || x < y;
}
template <typename CTYPE, typename elem_t = std::pair<CTYPE, int64_t>>
void perform_topk(
const Tensor& in,
int64_t k,
int64_t dim,
bool largest,
bool sorted,
Tensor& values,
Tensor& indices,
elem_t* queue) {
const CTYPE* const in_data = in.const_data_ptr<CTYPE>();
CTYPE* values_data = values.mutable_data_ptr<CTYPE>();
long* indices_data = indices.mutable_data_ptr<long>();
if (in.dim() == 0) {
values_data[0] = in_data[0];
indices_data[0] = 0;
return;
}
if (k == 0) {
return;
}
const size_t outer_size = getLeadingDims(in, dim);
const size_t dim_size = in.size(dim);
const size_t dim_stride = in.strides()[dim];
const size_t outer_stride_in = dim_size * dim_stride;
const size_t outer_stride_out = k * dim_stride;
bool use_partial_sort = k * 64 <= dim_size;
// Loop through all outer dimensions
for (size_t outer_idx = 0; outer_idx < outer_size; ++outer_idx) {
size_t outer_in = outer_idx * outer_stride_in;
size_t outer_out = outer_idx * outer_stride_out;
// Loop through all inner dimensions
for (size_t inner_idx = 0; inner_idx < dim_stride; ++inner_idx) {
size_t base_in = outer_in + inner_idx;
size_t base_out = outer_out + inner_idx;
// Populate the queue with the values from the input tensor
for (size_t i = 0; i < dim_size; ++i) {
size_t in_ix = base_in + i * dim_stride;
queue[i].first = in_data[in_ix];
queue[i].second = i;
}
// Perform topk on the queue
const auto elem_greater = [](const elem_t& x, const elem_t& y) -> bool {
return float_less_than(y.first, x.first);
};
const auto elem_less = [](const elem_t& x, const elem_t& y) -> bool {
return float_less_than(x.first, y.first);
};
const auto cmp = largest ? elem_greater : elem_less;
if (use_partial_sort) {
std::partial_sort(queue, queue + k, queue + dim_size, cmp);
} else {
std::nth_element(queue, queue + k - 1, queue + dim_size, cmp);
if (sorted) {
std::sort(queue, queue + k - 1, cmp);
}
}
// Write the topk values and indices to the output tensors
for (size_t i = 0; i < k; ++i) {
size_t out_ix = base_out + i * dim_stride;
values_data[out_ix] = queue[i].first;
indices_data[out_ix] = queue[i].second;
}
}
}
}
void* allocate_temp_memory(KernelRuntimeContext& ctx, size_t size) {
Result<void*> temp_mem_res = ctx.allocate_temp(size);
return temp_mem_res.ok() ? temp_mem_res.get() : nullptr;
}
} // namespace
std::tuple<Tensor&, Tensor&> topk_values(
KernelRuntimeContext& ctx,
const Tensor& in,
int64_t k,
int64_t dim,
bool largest,
bool sorted,
Tensor& values,
Tensor& indices) {
auto out = std::tuple<Tensor&, Tensor&>({values, indices});
ET_KERNEL_CHECK(
ctx, check_topk_args(in, k, dim, values, indices), InvalidArgument, out);
if (dim < 0) {
dim += nonzero_dim(in);
}
// @lint-ignore CLANGTIDY facebook-hte-CArray
Tensor::SizesType target_size[kTensorDimensionLimit];
size_t target_dim = 0;
get_topk_target_size(in, k, dim, target_size, &target_dim);
ET_KERNEL_CHECK(
ctx,
resize_tensor(values, {target_size, target_dim}) == Error::Ok,
InvalidArgument,
out);
ET_KERNEL_CHECK(
ctx,
resize_tensor(indices, {target_size, target_dim}) == Error::Ok,
InvalidArgument,
out);
constexpr auto name = "topk.values";
if (in.numel() == 0 || (k == 0 && in.dim() > 0)) {
return out;
}
bool temp_mem_allocated = false;
ET_SWITCH_REALHBF16_TYPES(in.scalar_type(), ctx, name, CTYPE, [&]() {
using elem_t = std::pair<CTYPE, int64_t>;
size_t temp_mem_size = nonempty_size(in, dim) * sizeof(elem_t);
elem_t* queue = (elem_t*)allocate_temp_memory(ctx, temp_mem_size);
if (queue == nullptr) {
return;
}
temp_mem_allocated = true;
perform_topk<CTYPE>(in, k, dim, largest, sorted, values, indices, queue);
});
ET_KERNEL_CHECK(ctx, temp_mem_allocated, MemoryAllocationFailed, out);
return out;
}
} // namespace native
} // namespace executor
} // namespace torch