array_sort.cu 1.77 KB
Newer Older
1
/**
2
 *  Copyright (c) 2020 by Contributors
3
4
 * @file array/cpu/array_sort.cu
 * @brief Array sort GPU implementation
5
6
 */
#include <dgl/array.h>
7

8
9
#include <cub/cub.cuh>

10
#include "../../runtime/cuda/cuda_common.h"
11
#include "./utils.h"
12
13
14
15
16
17

namespace dgl {
using runtime::NDArray;
namespace aten {
namespace impl {

18
template <DGLDeviceType XPU, typename IdType>
19
std::pair<IdArray, IdArray> Sort(IdArray array, int num_bits) {
20
21
22
23
24
25
26
27
28
29
30
31
  const auto& ctx = array->ctx;
  auto device = runtime::DeviceAPI::Get(ctx);
  const int64_t nitems = array->shape[0];
  IdArray orig_idx = Range(0, nitems, 64, ctx);
  IdArray sorted_array = NewIdArray(nitems, ctx, array->dtype.bits);
  IdArray sorted_idx = NewIdArray(nitems, ctx, 64);

  const IdType* keys_in = array.Ptr<IdType>();
  const int64_t* values_in = orig_idx.Ptr<int64_t>();
  IdType* keys_out = sorted_array.Ptr<IdType>();
  int64_t* values_out = sorted_idx.Ptr<int64_t>();

32
  cudaStream_t stream = runtime::getCurrentCUDAStream();
33
  if (num_bits == 0) {
34
    num_bits = sizeof(IdType) * 8;
35
36
  }

37
38
  // Allocate workspace
  size_t workspace_size = 0;
39
40
41
  CUDA_CALL(cub::DeviceRadixSort::SortPairs(
      nullptr, workspace_size, keys_in, keys_out, values_in, values_out, nitems,
      0, num_bits, stream));
42
43
44
  void* workspace = device->AllocWorkspace(ctx, workspace_size);

  // Compute
45
46
47
  CUDA_CALL(cub::DeviceRadixSort::SortPairs(
      workspace, workspace_size, keys_in, keys_out, values_in, values_out,
      nitems, 0, num_bits, stream));
48
49
50
51
52
53

  device->FreeWorkspace(ctx, workspace);

  return std::make_pair(sorted_array, sorted_idx);
}

54
55
56
57
template std::pair<IdArray, IdArray> Sort<kDGLCUDA, int32_t>(
    IdArray, int num_bits);
template std::pair<IdArray, IdArray> Sort<kDGLCUDA, int64_t>(
    IdArray, int num_bits);
58
59
60
61

}  // namespace impl
}  // namespace aten
}  // namespace dgl