30 template <
typename DataType,
typename IndexType = index_t>
43 assert(dim == -1 || dim <
rank);
49 assert(k <= topk_src_len);
55 auto f = [&](
auto i_element) {
56 std::vector<size_t> topk_coord = [&](){
57 std::vector<size_t> t_(
rank, 0);
60 if(i == topk_dim)
continue;
61 t_[i] = r % x_len[i]; r = r / x_len[i];
66 using elem_t = std::pair<DataType, IndexType>;
67 std::vector<elem_t> q = [&](){
68 std::vector<elem_t> t_(topk_src_len);
69 for(
index_t i = 0; i < topk_src_len; i++) {
70 auto c_ = topk_coord; c_[topk_dim] = i;
71 t_[i].first = x(c_); t_[i].second = i;
78 std::nth_element(q.begin(), q.begin() + k - 1, q.end(),
79 [](
const elem_t& lhs,
const elem_t& rhs) ->
bool { return lhs.first > rhs.first; });
81 std::sort(q.begin(), q.begin() + k - 1,
82 [](
const elem_t& lhs,
const elem_t& rhs) ->
bool { return lhs.first > rhs.first; });
85 std::nth_element(q.begin(), q.begin() + k - 1, q.end(),
86 [](
const elem_t& lhs,
const elem_t& rhs) ->
bool { return lhs.first < rhs.first; });
88 std::sort(q.begin(), q.begin() + k - 1,
89 [](
const elem_t& lhs,
const elem_t& rhs) ->
bool { return lhs.first < rhs.first; });
94 for(
index_t i = 0; i < k; i++) {
95 auto c_ = topk_coord; c_[topk_dim] = i;
96 y_values(c_) = q[i].first; y_indices(c_) = q[i].second;
105 template <
typename DataType,
typename IndexType = index_t>
113 index_t target_dim = (dim == -1) ? (lens.size() - 1) : dim;
114 assert(target_dim < lens.size());
115 assert(k <= lens[target_dim]);
116 lens[target_dim] = k;
120 reference_topk<DataType, IndexType>(x, y_values, y_indices, k, dim, largest, sorted);
#define CK_TILE_HOST
Definition: config.hpp:39
__host__ constexpr __device__ auto rank([[maybe_unused]] const Layout< Shape, UnrolledDescriptorType > &layout)
Get layout rank (num elements in shape).
Definition: layout_utils.hpp:310
Definition: cluster_descriptor.hpp:13
CK_TILE_HOST auto make_ParallelTensorFunctor(F f, Xs... xs)
Definition: host_tensor.hpp:272
int32_t index_t
Definition: integer.hpp:9
CK_TILE_HOST void reference_topk(const HostTensor< DataType > &x, HostTensor< DataType > &y_values, HostTensor< IndexType > &y_indices, index_t k, index_t dim=-1, bool largest=true, bool sorted=true)
Definition: reference_topk.hpp:31
constexpr CK_TILE_HOST_DEVICE auto make_tuple(Xs &&... xs)
Definition: tuple.hpp:337
Definition: host_tensor.hpp:279
decltype(auto) get_lengths() const
Definition: host_tensor.hpp:333
std::size_t get_num_of_dimension() const
Definition: host_tensor.hpp:339
std::size_t get_length(std::size_t dim) const
Definition: host_tensor.hpp:331
std::size_t get_element_size() const
Definition: host_tensor.hpp:341