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

7
8
9
#include <dgl/array.h>
#include "../../runtime/cuda/cuda_common.h"
#include "./utils.h"
10
#include "./dgl_cub.cuh"
11
12
13
14
15
16
17

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

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

  __device__ bool operator() (const int64_t index) {
    return array_[index] != 0;
24
  }
25
26

  const IdType * array_;
27
28
};

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

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

37
  cudaStream_t stream = runtime::getCurrentCUDAStream();
38
39
40
41
42
43
44
45
46
47
48
49

  const IdType * const in_data = static_cast<const IdType*>(array->data);
  int64_t * const out_data = static_cast<int64_t*>(ret->data);

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

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

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

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

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

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

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