ndarray.cc 15.5 KB
Newer Older
1
/**
2
 *  Copyright (c) 2017-2022 by Contributors
3
4
 * @file ndarray.cc
 * @brief NDArray container infratructure.
Minjie Wang's avatar
Minjie Wang committed
5
6
7
 */
#include <dgl/runtime/c_runtime_api.h>
#include <dgl/runtime/device_api.h>
8
#include <dgl/runtime/ndarray.h>
9
#include <dgl/runtime/shared_mem.h>
10
#include <dgl/runtime/tensordispatch.h>
11
12
13
14
#include <dgl/zerocopy_serializer.h>
#include <dmlc/logging.h>
#include <string.h>

Minjie Wang's avatar
Minjie Wang committed
15
16
#include "runtime_base.h"

17
namespace dgl {
18

19
constexpr DGLDataType DGLDataTypeTraits<int8_t>::dtype;
20
constexpr DGLDataType DGLDataTypeTraits<uint8_t>::dtype;
21
22
23
24
25
constexpr DGLDataType DGLDataTypeTraits<int16_t>::dtype;
constexpr DGLDataType DGLDataTypeTraits<int32_t>::dtype;
constexpr DGLDataType DGLDataTypeTraits<int64_t>::dtype;
constexpr DGLDataType DGLDataTypeTraits<uint32_t>::dtype;
constexpr DGLDataType DGLDataTypeTraits<uint64_t>::dtype;
26
#ifdef DGL_USE_CUDA
27
constexpr DGLDataType DGLDataTypeTraits<__half>::dtype;
28
29
30
31
#if BF16_ENABLED
constexpr DGLDataType DGLDataTypeTraits<__nv_bfloat16>::dtype;
#endif  // BF16_ENABLED
#endif  // DGL_USE_CUDA
32
33
constexpr DGLDataType DGLDataTypeTraits<float>::dtype;
constexpr DGLDataType DGLDataTypeTraits<double>::dtype;
34

Minjie Wang's avatar
Minjie Wang committed
35
36
namespace runtime {

37
inline void VerifyDataType(DGLDataType dtype) {
Minjie Wang's avatar
Minjie Wang committed
38
  CHECK_GE(dtype.lanes, 1);
39
  if (dtype.code == kDGLFloat) {
Minjie Wang's avatar
Minjie Wang committed
40
41
42
43
44
45
46
    CHECK_EQ(dtype.bits % 8, 0);
  } else {
    CHECK_EQ(dtype.bits % 8, 0);
  }
  CHECK_EQ(dtype.bits & (dtype.bits - 1), 0);
}

47
inline size_t GetDataSize(const DGLArray& arr) {
Minjie Wang's avatar
Minjie Wang committed
48
  size_t size = 1;
49
  for (dgl_index_t i = 0; i < arr.ndim; ++i) {
Minjie Wang's avatar
Minjie Wang committed
50
51
52
53
54
55
    size *= arr.shape[i];
  }
  size *= (arr.dtype.bits * arr.dtype.lanes + 7) / 8;
  return size;
}

56
inline size_t GetDataAlignment(const DGLArray& arr) {
Minjie Wang's avatar
Minjie Wang committed
57
58
59
60
61
  size_t align = (arr.dtype.bits / 8) * arr.dtype.lanes;
  if (align < kAllocAlignment) return kAllocAlignment;
  return align;
}

62
63
64
65
66
67
68
69
void NDArray::Internal::DefaultDeleter(NDArray::Container* ptr) {
  using dgl::runtime::NDArray;
  if (ptr->manager_ctx != nullptr) {
    static_cast<NDArray::Container*>(ptr->manager_ctx)->DecRef();
  } else if (ptr->mem) {
    ptr->mem = nullptr;
  } else if (ptr->dl_tensor.data != nullptr) {
    // if the array is still pinned before freeing, unpin it.
70
71
72
    if (ptr->pinned_by_dgl_) UnpinContainer(ptr);
    dgl::runtime::DeviceAPI::Get(ptr->dl_tensor.ctx)
        ->FreeDataSpace(ptr->dl_tensor.ctx, ptr->dl_tensor.data);
Minjie Wang's avatar
Minjie Wang committed
73
  }
74
75
76
  delete ptr;
}

77
78
NDArray NDArray::Internal::Create(
    std::vector<int64_t> shape, DGLDataType dtype, DGLContext ctx) {
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
  VerifyDataType(dtype);
  // critical zone
  NDArray::Container* data = new NDArray::Container();
  data->deleter = DefaultDeleter;
  NDArray ret(data);
  ret.data_ = data;
  // RAII now in effect
  // setup shape
  data->shape_ = std::move(shape);
  data->dl_tensor.shape = dmlc::BeginPtr(data->shape_);
  data->dl_tensor.ndim = static_cast<int>(data->shape_.size());
  // setup stride (this should be optional, but some framework
  //   does not support NULL stride and thus will crash the program).
  data->stride_.resize(data->dl_tensor.ndim, 1);
  for (int i = data->dl_tensor.ndim - 2; i >= 0; --i) {
94
    data->stride_[i] = data->shape_[i + 1] * data->stride_[i + 1];
Minjie Wang's avatar
Minjie Wang committed
95
  }
96
97
98
99
100
101
102
103
104
105
106
107
108
109
  data->dl_tensor.strides = dmlc::BeginPtr(data->stride_);
  // setup dtype
  data->dl_tensor.dtype = dtype;
  // setup ctx
  data->dl_tensor.ctx = ctx;
  return ret;
}

DGLArray* NDArray::Internal::MoveAsDGLArray(NDArray arr) {
  DGLArray* tensor = reinterpret_cast<DGLArray*>(arr.data_);
  CHECK(tensor == const_cast<DGLArray*>(arr.operator->()));
  arr.data_ = nullptr;
  return tensor;
}
Minjie Wang's avatar
Minjie Wang committed
110

111
size_t NDArray::GetSize() const { return GetDataSize(data_->dl_tensor); }
112

113
int64_t NDArray::NumElements() const {
114
  if (data_->dl_tensor.ndim == 0) return 0;
115
116
117
118
119
120
121
  int64_t size = 1;
  for (int i = 0; i < data_->dl_tensor.ndim; ++i) {
    size *= data_->dl_tensor.shape[i];
  }
  return size;
}

122
123
bool NDArray::IsContiguous() const {
  CHECK(data_ != nullptr);
124
  if (data_->dl_tensor.strides == nullptr) return true;
125

126
127
  // See https://github.com/dmlc/dgl/issues/2118 and PyTorch's
  // compute_contiguous() implementation
128
129
130
131
132
133
134
135
  int64_t z = 1;
  for (int64_t i = data_->dl_tensor.ndim - 1; i >= 0; --i) {
    if (data_->dl_tensor.shape[i] != 1) {
      if (data_->dl_tensor.strides[i] == z)
        z *= data_->dl_tensor.shape[i];
      else
        return false;
    }
136
  }
137
  return true;
138
139
}

140
141
NDArray NDArray::CreateView(
    std::vector<int64_t> shape, DGLDataType dtype, int64_t offset) {
Minjie Wang's avatar
Minjie Wang committed
142
  CHECK(data_ != nullptr);
143
  CHECK(IsContiguous()) << "Can only create view for compact tensor";
Minjie Wang's avatar
Minjie Wang committed
144
  NDArray ret = Internal::Create(shape, dtype, data_->dl_tensor.ctx);
145
  ret.data_->dl_tensor.byte_offset = this->data_->dl_tensor.byte_offset;
Minjie Wang's avatar
Minjie Wang committed
146
147
148
149
150
151
152
  size_t curr_size = GetDataSize(this->data_->dl_tensor);
  size_t view_size = GetDataSize(ret.data_->dl_tensor);
  CHECK_LE(view_size, curr_size)
      << "Tries to create a view that has bigger memory than current one";
  // increase ref count
  this->data_->IncRef();
  ret.data_->manager_ctx = this->data_;
153
  ret.data_->dl_tensor.data =
154
      static_cast<char*>(this->data_->dl_tensor.data) + offset;
Minjie Wang's avatar
Minjie Wang committed
155
156
157
  return ret;
}

158
159
160
NDArray NDArray::EmptyShared(
    const std::string& name, std::vector<int64_t> shape, DGLDataType dtype,
    DGLContext ctx, bool is_create) {
161
162
163
164
165
  NDArray ret = Internal::Create(shape, dtype, ctx);
  // setup memory content
  size_t size = GetDataSize(ret.data_->dl_tensor);
  auto mem = std::make_shared<SharedMemory>(name);
  if (is_create) {
166
    ret.data_->dl_tensor.data = mem->CreateNew(size);
167
  } else {
168
    ret.data_->dl_tensor.data = mem->Open(size);
169
170
171
172
173
174
  }

  ret.data_->mem = mem;
  return ret;
}

175
176
NDArray NDArray::Empty(
    std::vector<int64_t> shape, DGLDataType dtype, DGLContext ctx) {
177
  NDArray ret = Internal::Create(shape, dtype, ctx);
Minjie Wang's avatar
Minjie Wang committed
178
179
180
  // setup memory content
  size_t size = GetDataSize(ret.data_->dl_tensor);
  size_t alignment = GetDataAlignment(ret.data_->dl_tensor);
181
  if (size > 0)
182
183
    ret.data_->dl_tensor.data = DeviceAPI::Get(ret->ctx)->AllocDataSpace(
        ret->ctx, size, alignment, ret->dtype);
Minjie Wang's avatar
Minjie Wang committed
184
185
186
  return ret;
}

187
void NDArray::CopyFromTo(DGLArray* from, DGLArray* to) {
Minjie Wang's avatar
Minjie Wang committed
188
189
190
  size_t from_size = GetDataSize(*from);
  size_t to_size = GetDataSize(*to);
  CHECK_EQ(from_size, to_size)
191
      << "DGLArrayCopyFromTo: The size must exactly match";
Minjie Wang's avatar
Minjie Wang committed
192

193
194
195
196
  CHECK(
      from->ctx.device_type == to->ctx.device_type ||
      from->ctx.device_type == kDGLCPU || to->ctx.device_type == kDGLCPU)
      << "Can not copy across different ctx types directly";
Minjie Wang's avatar
Minjie Wang committed
197
198
199

  // Use the context that is *not* a cpu context to get the correct device
  // api manager.
200
  DGLContext ctx = from->ctx.device_type != kDGLCPU ? from->ctx : to->ctx;
Minjie Wang's avatar
Minjie Wang committed
201

202
  // default: local current cuda stream
Minjie Wang's avatar
Minjie Wang committed
203
  DeviceAPI::Get(ctx)->CopyDataFromTo(
204
205
206
      from->data, static_cast<size_t>(from->byte_offset), to->data,
      static_cast<size_t>(to->byte_offset), from_size, from->ctx, to->ctx,
      from->dtype);
Minjie Wang's avatar
Minjie Wang committed
207
208
}

209
210
211
void NDArray::PinContainer(NDArray::Container* ptr) {
  if (IsContainerPinned(ptr)) return;
  auto* tensor = &(ptr->dl_tensor);
212
  CHECK_EQ(tensor->ctx.device_type, kDGLCPU)
213
      << "Only NDArray on CPU can be pinned";
214
215
  ptr->pinned_by_dgl_ =
      DeviceAPI::Get(kDGLCUDA)->PinData(tensor->data, GetDataSize(*tensor));
216
217
}

218
219
220
221
222
void NDArray::UnpinContainer(NDArray::Container* ptr) {
  auto container_is_pinned = IsContainerPinned(ptr);
  // The tensor may be pinned outside of DGL via a different CUDA API,
  // so we cannot unpin it with cudaHostUnregister.
  CHECK(ptr->pinned_by_dgl_ || !container_is_pinned)
223
      << "Cannot unpin a tensor that is pinned outside of DGL.";
224
225
226
  // 1. not pinned, do nothing
  if (!container_is_pinned) return;
  // 2. pinned by DGL, unpin it
227
  DeviceAPI::Get(kDGLCUDA)->UnpinData(ptr->dl_tensor.data);
228
  ptr->pinned_by_dgl_ = false;
229
230
}

231
232
void NDArray::RecordStream(DGLArray* tensor, DGLStreamHandle stream) {
  TensorDispatcher* td = TensorDispatcher::Global();
233
234
  CHECK(td->IsAvailable())
      << "RecordStream only works when TensorAdaptor is available.";
235
  CHECK_EQ(tensor->ctx.device_type, kDGLCUDA)
236
      << "RecordStream only works with GPU tensors.";
237
238
239
240

  td->RecordStream(tensor->data, stream, tensor->ctx.device_id);
}

241
template <typename T>
242
243
NDArray NDArray::FromVector(const std::vector<T>& vec, DGLContext ctx) {
  const DGLDataType dtype = DGLDataTypeTraits<T>::dtype;
244
  int64_t size = static_cast<int64_t>(vec.size());
245
  NDArray ret = NDArray::Empty({size}, dtype, ctx);
246
  DeviceAPI::Get(ctx)->CopyDataFromTo(
247
248
      vec.data(), 0, static_cast<T*>(ret->data), 0, size * sizeof(T),
      DGLContext{kDGLCPU, 0}, ctx, dtype);
249
250
251
  return ret;
}

252
253
254
NDArray NDArray::CreateFromRaw(
    const std::vector<int64_t>& shape, DGLDataType dtype, DGLContext ctx,
    void* raw, bool auto_free) {
255
256
  NDArray ret = Internal::Create(shape, dtype, ctx);
  ret.data_->dl_tensor.data = raw;
257
  if (!auto_free) ret.data_->deleter = nullptr;
258
259
260
  return ret;
}

261
// export specializations
262
263
264
265
266
267
268
269
270
271
272
273
274
275
template NDArray NDArray::FromVector<int32_t>(
    const std::vector<int32_t>&, DGLContext);
template NDArray NDArray::FromVector<int64_t>(
    const std::vector<int64_t>&, DGLContext);
template NDArray NDArray::FromVector<uint32_t>(
    const std::vector<uint32_t>&, DGLContext);
template NDArray NDArray::FromVector<uint64_t>(
    const std::vector<uint64_t>&, DGLContext);
template NDArray NDArray::FromVector<float>(
    const std::vector<float>&, DGLContext);
template NDArray NDArray::FromVector<double>(
    const std::vector<double>&, DGLContext);

template <typename T>
276
std::vector<T> NDArray::ToVector() const {
277
  const DGLDataType dtype = DGLDataTypeTraits<T>::dtype;
278
279
  CHECK(data_->dl_tensor.ndim == 1)
      << "ToVector() only supported for 1D arrays";
280
281
282
283
  CHECK(data_->dl_tensor.dtype == dtype) << "dtype mismatch";

  int64_t size = data_->dl_tensor.shape[0];
  std::vector<T> vec(size);
284
  const DGLContext& ctx = data_->dl_tensor.ctx;
285
  DeviceAPI::Get(ctx)->CopyDataFromTo(
286
287
      static_cast<T*>(data_->dl_tensor.data), 0, vec.data(), 0,
      size * sizeof(T), ctx, DGLContext{kDGLCPU, 0}, dtype);
288
289
290
291
292
293
294
295
296
  return vec;
}

template std::vector<int32_t> NDArray::ToVector<int32_t>() const;
template std::vector<int64_t> NDArray::ToVector<int64_t>() const;
template std::vector<uint32_t> NDArray::ToVector<uint32_t>() const;
template std::vector<uint64_t> NDArray::ToVector<uint64_t>() const;
template std::vector<float> NDArray::ToVector<float>() const;
template std::vector<double> NDArray::ToVector<double>() const;
297

298
299
300
301
std::shared_ptr<SharedMemory> NDArray::GetSharedMem() const {
  return this->data_->mem;
}

302
bool NDArray::IsContainerPinned(NDArray::Container* ptr) {
303
  if (ptr->pinned_by_dgl_) return true;
304
  auto* tensor = &(ptr->dl_tensor);
305
  // Can only be pinned if on CPU...
306
307
308
  if (tensor->ctx.device_type != kDGLCPU) return false;
  // ... and CUDA device API is enabled, and the tensor is indeed in pinned
  // memory.
309
  auto device = DeviceAPI::Get(kDGLCUDA, true);
310
311
  return device && device->IsPinned(tensor->data);
}
312
313

void NDArray::Save(dmlc::Stream* strm) const {
314
  auto zc_strm = dynamic_cast<StreamWithBuffer*>(strm);
315
316
317
318
  if (zc_strm) {
    zc_strm->PushNDArray(*this);
    return;
  }
319
  SaveDGLArray(strm, const_cast<DGLArray*>(operator->()));
320
321
322
}

bool NDArray::Load(dmlc::Stream* strm) {
323
  auto zc_strm = dynamic_cast<StreamWithBuffer*>(strm);
324
325
326
327
328
  if (zc_strm) {
    *this = zc_strm->PopNDArray();
    return true;
  }
  uint64_t header, reserved;
329
330
331
  CHECK(strm->Read(&header)) << "Invalid DGLArray file format";
  CHECK(strm->Read(&reserved)) << "Invalid DGLArray file format";
  CHECK(header == kDGLNDArrayMagic) << "Invalid DGLArray file format";
332
  DGLContext ctx;
333
  int ndim;
334
  DGLDataType dtype;
335
336
337
  CHECK(strm->Read(&ctx)) << "Invalid DGLArray file format";
  CHECK(strm->Read(&ndim)) << "Invalid DGLArray file format";
  CHECK(strm->Read(&dtype)) << "Invalid DGLArray file format";
338
339
  CHECK_EQ(ctx.device_type, kDGLCPU)
      << "Invalid DGLArray context: can only save as CPU tensor";
340
341
  std::vector<int64_t> shape(ndim);
  if (ndim != 0) {
342
    CHECK(strm->ReadArray(&shape[0], ndim)) << "Invalid DGLArray file format";
343
344
345
346
347
348
349
350
  }
  NDArray ret = NDArray::Empty(shape, dtype, ctx);
  int64_t num_elems = 1;
  int elem_bytes = (ret->dtype.bits + 7) / 8;
  for (int i = 0; i < ret->ndim; ++i) {
    num_elems *= ret->shape[i];
  }
  int64_t data_byte_size;
351
  CHECK(strm->Read(&data_byte_size)) << "Invalid DGLArray file format";
352
  CHECK(data_byte_size == num_elems * elem_bytes)
353
      << "Invalid DGLArray file format";
354
  if (data_byte_size != 0) {
355
356
357
    // strm->Read will return the total number of elements successfully read.
    // Therefore if data_byte_size is zero, the CHECK below would fail.
    CHECK(strm->Read(ret->data, data_byte_size))
358
        << "Invalid DGLArray file format";
359
360
361
362
363
364
365
366
  }
  if (!DMLC_IO_NO_ENDIAN_SWAP) {
    dmlc::ByteSwap(ret->data, elem_bytes, num_elems);
  }
  *this = ret;
  return true;
}

Minjie Wang's avatar
Minjie Wang committed
367
}  // namespace runtime
368
}  // namespace dgl
Minjie Wang's avatar
Minjie Wang committed
369

370
using namespace dgl::runtime;
Minjie Wang's avatar
Minjie Wang committed
371

372
373
374
int DGLArrayAlloc(
    const dgl_index_t* shape, int ndim, int dtype_code, int dtype_bits,
    int dtype_lanes, int device_type, int device_id, DGLArrayHandle* out) {
Minjie Wang's avatar
Minjie Wang committed
375
  API_BEGIN();
376
  DGLDataType dtype;
Minjie Wang's avatar
Minjie Wang committed
377
378
379
  dtype.code = static_cast<uint8_t>(dtype_code);
  dtype.bits = static_cast<uint8_t>(dtype_bits);
  dtype.lanes = static_cast<uint16_t>(dtype_lanes);
380
381
  DGLContext ctx;
  ctx.device_type = static_cast<DGLDeviceType>(device_type);
Minjie Wang's avatar
Minjie Wang committed
382
  ctx.device_id = device_id;
383
  *out = NDArray::Internal::MoveAsDGLArray(
Minjie Wang's avatar
Minjie Wang committed
384
385
386
387
      NDArray::Empty(std::vector<int64_t>(shape, shape + ndim), dtype, ctx));
  API_END();
}

388
389
390
int DGLArrayAllocSharedMem(
    const char* mem_name, const dgl_index_t* shape, int ndim, int dtype_code,
    int dtype_bits, int dtype_lanes, bool is_create, DGLArrayHandle* out) {
391
  API_BEGIN();
392
  DGLDataType dtype;
393
394
395
396
  dtype.code = static_cast<uint8_t>(dtype_code);
  dtype.bits = static_cast<uint8_t>(dtype_bits);
  dtype.lanes = static_cast<uint16_t>(dtype_lanes);
  std::vector<int64_t> shape_vec(shape, shape + ndim);
397
398
  NDArray arr = NDArray::EmptyShared(
      mem_name, shape_vec, dtype, DGLContext{kDGLCPU, 0}, is_create);
399
  *out = NDArray::Internal::MoveAsDGLArray(arr);
400
401
402
  API_END();
}

403
int DGLArrayFree(DGLArrayHandle handle) {
Minjie Wang's avatar
Minjie Wang committed
404
405
406
407
408
  API_BEGIN();
  reinterpret_cast<NDArray::Container*>(handle)->DecRef();
  API_END();
}

409
int DGLArrayCopyFromTo(DGLArrayHandle from, DGLArrayHandle to) {
Minjie Wang's avatar
Minjie Wang committed
410
  API_BEGIN();
411
  NDArray::CopyFromTo(from, to);
Minjie Wang's avatar
Minjie Wang committed
412
413
414
  API_END();
}

415
int DGLArrayCopyFromBytes(DGLArrayHandle handle, void* data, size_t nbytes) {
Minjie Wang's avatar
Minjie Wang committed
416
  API_BEGIN();
417
  DGLContext cpu_ctx;
418
  cpu_ctx.device_type = kDGLCPU;
Minjie Wang's avatar
Minjie Wang committed
419
420
  cpu_ctx.device_id = 0;
  size_t arr_size = GetDataSize(*handle);
421
422
423
424
425
  CHECK_EQ(arr_size, nbytes) << "DGLArrayCopyFromBytes: size mismatch";
  DeviceAPI::Get(handle->ctx)
      ->CopyDataFromTo(
          data, 0, handle->data, static_cast<size_t>(handle->byte_offset),
          nbytes, cpu_ctx, handle->ctx, handle->dtype);
Minjie Wang's avatar
Minjie Wang committed
426
427
428
  API_END();
}

429
int DGLArrayCopyToBytes(DGLArrayHandle handle, void* data, size_t nbytes) {
Minjie Wang's avatar
Minjie Wang committed
430
  API_BEGIN();
431
  DGLContext cpu_ctx;
432
  cpu_ctx.device_type = kDGLCPU;
Minjie Wang's avatar
Minjie Wang committed
433
434
  cpu_ctx.device_id = 0;
  size_t arr_size = GetDataSize(*handle);
435
436
437
438
439
  CHECK_EQ(arr_size, nbytes) << "DGLArrayCopyToBytes: size mismatch";
  DeviceAPI::Get(handle->ctx)
      ->CopyDataFromTo(
          handle->data, static_cast<size_t>(handle->byte_offset), data, 0,
          nbytes, handle->ctx, cpu_ctx, handle->dtype);
Minjie Wang's avatar
Minjie Wang committed
440
441
  API_END();
}
442

443
int DGLArrayPinData(DGLArrayHandle handle, DGLContext ctx) {
444
  API_BEGIN();
445
446
  auto* nd_container = reinterpret_cast<NDArray::Container*>(handle);
  NDArray::PinContainer(nd_container);
447
448
449
  API_END();
}

450
int DGLArrayUnpinData(DGLArrayHandle handle, DGLContext ctx) {
451
  API_BEGIN();
452
453
  auto* nd_container = reinterpret_cast<NDArray::Container*>(handle);
  NDArray::UnpinContainer(nd_container);
454
455
  API_END();
}
456
457
458
459
460
461

int DGLArrayRecordStream(DGLArrayHandle handle, DGLStreamHandle stream) {
  API_BEGIN();
  NDArray::RecordStream(handle, stream);
  API_END();
}