array_nonzero.cu 1.98 KB
Newer Older
1
2
/*!
 *  Copyright (c) 2020 by Contributors
3
4
 * @file array/cpu/array_nonzero.cc
 * @brief Array nonzero CPU implementation
5
 */
6

7
#include <dgl/array.h>
8

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

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

template <typename IdType>
19
struct IsNonZeroIndex {
20
  explicit IsNonZeroIndex(const IdType* array) : array_(array) {}
21

22
  __device__ bool operator()(const int64_t index) { return array_[index] != 0; }
23

24
  const IdType* array_;
25
26
};

27
template <DGLDeviceType XPU, typename IdType>
28
IdArray NonZero(IdArray array) {
29
30
31
  const auto& ctx = array->ctx;
  auto device = runtime::DeviceAPI::Get(ctx);

32
  const int64_t len = array->shape[0];
33
34
  IdArray ret = NewIdArray(len, ctx, 64);

35
  cudaStream_t stream = runtime::getCurrentCUDAStream();
36

37
38
  const IdType* const in_data = static_cast<const IdType*>(array->data);
  int64_t* const out_data = static_cast<int64_t*>(ret->data);
39
40
41
42
43

  IsNonZeroIndex<IdType> comp(in_data);
  cub::CountingInputIterator<int64_t> counter(0);

  // room for cub to output on GPU
44
45
  int64_t* d_num_nonzeros =
      static_cast<int64_t*>(device->AllocWorkspace(ctx, sizeof(int64_t)));
46
47

  size_t temp_size = 0;
48
49
50
51
52
53
  CUDA_CALL(cub::DeviceSelect::If(
      nullptr, temp_size, counter, out_data, d_num_nonzeros, len, comp,
      stream));
  void* temp = device->AllocWorkspace(ctx, temp_size);
  CUDA_CALL(cub::DeviceSelect::If(
      temp, temp_size, counter, out_data, d_num_nonzeros, len, comp, stream));
54
55
56
  device->FreeWorkspace(ctx, temp);

  // copy number of selected elements from GPU to CPU
57
  int64_t num_nonzeros = cuda::GetCUDAScalar(device, ctx, d_num_nonzeros);
58
59
60
61
  device->FreeWorkspace(ctx, d_num_nonzeros);
  device->StreamSync(ctx, stream);

  // truncate array to size
62
63
64
  return ret.CreateView({num_nonzeros}, ret->dtype, 0);
}

65
66
template IdArray NonZero<kDGLCUDA, int32_t>(IdArray);
template IdArray NonZero<kDGLCUDA, int64_t>(IdArray);
67
68
69
70

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