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

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

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

17
template <DGLDeviceType XPU, typename IdType>
18
19
20
IdArray CumSum(IdArray array, bool prepend_zero) {
  const int64_t len = array.NumElements();
  if (len == 0)
21
22
    return !prepend_zero ? array
                         : aten::Full(0, 1, array->dtype.bits, array->ctx);
23

24
  auto device = runtime::DeviceAPI::Get(array->ctx);
25
  cudaStream_t stream = runtime::getCurrentCUDAStream();
26
27
28
29
30
31
32
33
34
35
36
37
  const IdType* in_d = array.Ptr<IdType>();
  IdArray ret;
  IdType* out_d = nullptr;
  if (prepend_zero) {
    ret = aten::Full(0, len + 1, array->dtype.bits, array->ctx);
    out_d = ret.Ptr<IdType>() + 1;
  } else {
    ret = aten::NewIdArray(len, array->ctx, array->dtype.bits);
    out_d = ret.Ptr<IdType>();
  }
  // Allocate workspace
  size_t workspace_size = 0;
38
  CUDA_CALL(cub::DeviceScan::InclusiveSum(
39
      nullptr, workspace_size, in_d, out_d, len, stream));
40
41
42
  void* workspace = device->AllocWorkspace(array->ctx, workspace_size);

  // Compute cumsum
43
  CUDA_CALL(cub::DeviceScan::InclusiveSum(
44
      workspace, workspace_size, in_d, out_d, len, stream));
45
46
47
48
49
50

  device->FreeWorkspace(array->ctx, workspace);

  return ret;
}

51
52
template IdArray CumSum<kDGLCUDA, int32_t>(IdArray, bool);
template IdArray CumSum<kDGLCUDA, int64_t>(IdArray, bool);
53
54
55
56

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