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

// deleter for arrays used by DLPack exporter
extern "C" void NDArrayDLPackDeleter(DLManagedTensor* tensor);

19
namespace dgl {
20

21
22
constexpr DLDataType DLDataTypeTraits<int8_t>::dtype;
constexpr DLDataType DLDataTypeTraits<int16_t>::dtype;
23
24
25
26
constexpr DLDataType DLDataTypeTraits<int32_t>::dtype;
constexpr DLDataType DLDataTypeTraits<int64_t>::dtype;
constexpr DLDataType DLDataTypeTraits<uint32_t>::dtype;
constexpr DLDataType DLDataTypeTraits<uint64_t>::dtype;
27
28
29
#ifdef USE_FP16
constexpr DLDataType DLDataTypeTraits<__half>::dtype;
#endif
30
31
32
constexpr DLDataType DLDataTypeTraits<float>::dtype;
constexpr DLDataType DLDataTypeTraits<double>::dtype;

Minjie Wang's avatar
Minjie Wang committed
33
34
35
36
37
38
39
40
41
42
43
44
45
46
namespace runtime {

inline void VerifyDataType(DLDataType dtype) {
  CHECK_GE(dtype.lanes, 1);
  if (dtype.code == kDLFloat) {
    CHECK_EQ(dtype.bits % 8, 0);
  } else {
    CHECK_EQ(dtype.bits % 8, 0);
  }
  CHECK_EQ(dtype.bits & (dtype.bits - 1), 0);
}

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

inline size_t GetDataAlignment(const DLTensor& arr) {
  size_t align = (arr.dtype.bits / 8) * arr.dtype.lanes;
  if (align < kAllocAlignment) return kAllocAlignment;
  return align;
}

struct NDArray::Internal {
  // Default deleter for the container
  static void DefaultDeleter(NDArray::Container* ptr) {
63
    using dgl::runtime::NDArray;
Minjie Wang's avatar
Minjie Wang committed
64
65
    if (ptr->manager_ctx != nullptr) {
      static_cast<NDArray::Container*>(ptr->manager_ctx)->DecRef();
66
67
    } else if (ptr->mem) {
      ptr->mem = nullptr;
Minjie Wang's avatar
Minjie Wang committed
68
    } else if (ptr->dl_tensor.data != nullptr) {
69
      // if the array is still pinned before freeing, unpin it.
70
71
      if (ptr->pinned_by_dgl_)
        UnpinContainer(ptr);
72
      dgl::runtime::DeviceAPI::Get(ptr->dl_tensor.ctx)->FreeDataSpace(
Minjie Wang's avatar
Minjie Wang committed
73
74
75
76
77
78
          ptr->dl_tensor.ctx, ptr->dl_tensor.data);
    }
    delete ptr;
  }
  // Deleter for NDArray converted from DLPack
  // This is used from data which is passed from external DLPack(DLManagedTensor)
79
  // that are not allocated inside of DGL.
Minjie Wang's avatar
Minjie Wang committed
80
81
82
  // This enables us to create NDArray from memory allocated by other
  // frameworks that are DLPack compatible
  static void DLPackDeleter(NDArray::Container* ptr) {
83
84
85
    // if the array is pinned by dgl, unpin it before freeing
    if (ptr->pinned_by_dgl_)
      UnpinContainer(ptr);
Minjie Wang's avatar
Minjie Wang committed
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
    DLManagedTensor* tensor = static_cast<DLManagedTensor*>(ptr->manager_ctx);
    if (tensor->deleter != nullptr) {
      (*tensor->deleter)(tensor);
    }
    delete ptr;
  }
  // Local create function which allocates tensor metadata
  // but does not allocate space for the data.
  static NDArray Create(std::vector<int64_t> shape,
                        DLDataType dtype,
                        DLContext ctx) {
    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());
108
109
110
111
112
113
114
    // 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) {
      data->stride_[i] = data->shape_[i+1] * data->stride_[i+1];
    }
    data->dl_tensor.strides = dmlc::BeginPtr(data->stride_);
Minjie Wang's avatar
Minjie Wang committed
115
116
117
118
119
120
121
122
    // setup dtype
    data->dl_tensor.dtype = dtype;
    // setup ctx
    data->dl_tensor.ctx = ctx;
    return ret;
  }
  // Implementation of API function
  static DLTensor* MoveAsDLTensor(NDArray arr) {
123
124
    DLTensor* tensor = reinterpret_cast<DLTensor*>(arr.data_);
    CHECK(tensor == const_cast<DLTensor*>(arr.operator->()));
Minjie Wang's avatar
Minjie Wang committed
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
    arr.data_ = nullptr;
    return tensor;
  }
  // Container to DLManagedTensor
  static DLManagedTensor* ToDLPack(NDArray::Container* from) {
    CHECK(from != nullptr);
    DLManagedTensor* ret = new DLManagedTensor();
    ret->dl_tensor = from->dl_tensor;
    ret->manager_ctx = from;
    from->IncRef();
    ret->deleter = NDArrayDLPackDeleter;
    return ret;
  }
};

140
141
142
143
size_t NDArray::GetSize() const {
  return GetDataSize(data_->dl_tensor);
}

144
int64_t NDArray::NumElements() const {
145
146
  if (data_->dl_tensor.ndim == 0)
    return 0;
147
148
149
150
151
152
153
  int64_t size = 1;
  for (int i = 0; i < data_->dl_tensor.ndim; ++i) {
    size *= data_->dl_tensor.shape[i];
  }
  return size;
}

154
155
156
157
bool NDArray::IsContiguous() const {
  CHECK(data_ != nullptr);
  if (data_->dl_tensor.strides == nullptr)
    return true;
158
159
160
161
162
163
164
165
166
167

  // See https://github.com/dmlc/dgl/issues/2118 and PyTorch's compute_contiguous() implementation
  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;
    }
168
  }
169
  return true;
170
171
}

Minjie Wang's avatar
Minjie Wang committed
172
NDArray NDArray::CreateView(std::vector<int64_t> shape,
173
174
                            DLDataType dtype,
                            int64_t offset) {
Minjie Wang's avatar
Minjie Wang committed
175
  CHECK(data_ != nullptr);
176
  CHECK(IsContiguous()) << "Can only create view for compact tensor";
Minjie Wang's avatar
Minjie Wang committed
177
178
179
180
181
182
183
184
185
186
  NDArray ret = Internal::Create(shape, dtype, data_->dl_tensor.ctx);
  ret.data_->dl_tensor.byte_offset =
      this->data_->dl_tensor.byte_offset;
  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_;
187
188
  ret.data_->dl_tensor.data =
    static_cast<char*>(this->data_->dl_tensor.data) + offset;
Minjie Wang's avatar
Minjie Wang committed
189
190
191
192
193
194
195
  return ret;
}

DLManagedTensor* NDArray::ToDLPack() const {
  return Internal::ToDLPack(data_);
}

196
197
198
199
200
201
202
203
204
NDArray NDArray::EmptyShared(const std::string &name,
                       std::vector<int64_t> shape,
                       DLDataType dtype,
                       DLContext ctx, bool is_create) {
  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) {
205
    ret.data_->dl_tensor.data = mem->CreateNew(size);
206
  } else {
207
    ret.data_->dl_tensor.data = mem->Open(size);
208
209
210
211
212
213
  }

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

Minjie Wang's avatar
Minjie Wang committed
214
NDArray NDArray::Empty(std::vector<int64_t> shape,
215
216
                       DLDataType dtype,
                       DLContext ctx) {
217
  NDArray ret = Internal::Create(shape, dtype, ctx);
Minjie Wang's avatar
Minjie Wang committed
218
219
220
  // setup memory content
  size_t size = GetDataSize(ret.data_->dl_tensor);
  size_t alignment = GetDataAlignment(ret.data_->dl_tensor);
221
222
223
224
  if (size > 0)
    ret.data_->dl_tensor.data =
        DeviceAPI::Get(ret->ctx)->AllocDataSpace(
            ret->ctx, size, alignment, ret->dtype);
Minjie Wang's avatar
Minjie Wang committed
225
226
227
228
229
230
231
232
  return ret;
}

NDArray NDArray::FromDLPack(DLManagedTensor* tensor) {
  NDArray::Container* data = new NDArray::Container();
  data->deleter = Internal::DLPackDeleter;
  data->manager_ctx = tensor;
  data->dl_tensor = tensor->dl_tensor;
233

Minjie Wang's avatar
Minjie Wang committed
234
235
236
237
238
  return NDArray(data);
}

void NDArray::CopyFromTo(DLTensor* from,
                         DLTensor* to,
239
                         DGLStreamHandle stream) {
Minjie Wang's avatar
Minjie Wang committed
240
241
242
  size_t from_size = GetDataSize(*from);
  size_t to_size = GetDataSize(*to);
  CHECK_EQ(from_size, to_size)
243
    << "DGLArrayCopyFromTo: The size must exactly match";
Minjie Wang's avatar
Minjie Wang committed
244
245
246
247
248
249
250
251

  CHECK(from->ctx.device_type == to->ctx.device_type
        || from->ctx.device_type == kDLCPU
        || to->ctx.device_type == kDLCPU)
    << "Can not copy across different ctx types directly";

  // Use the context that is *not* a cpu context to get the correct device
  // api manager.
252
  DGLContext ctx = from->ctx.device_type != kDLCPU ? from->ctx : to->ctx;
Minjie Wang's avatar
Minjie Wang committed
253
254
255
256
257
258
259

  DeviceAPI::Get(ctx)->CopyDataFromTo(
    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, stream);
}

260
261
262
void NDArray::PinContainer(NDArray::Container* ptr) {
  if (IsContainerPinned(ptr)) return;
  auto* tensor = &(ptr->dl_tensor);
263
264
265
  CHECK_EQ(tensor->ctx.device_type, kDLCPU)
    << "Only NDArray on CPU can be pinned";
  DeviceAPI::Get(kDLGPU)->PinData(tensor->data, GetDataSize(*tensor));
266
  ptr->pinned_by_dgl_ = true;
267
268
}

269
270
271
272
273
274
275
276
277
278
279
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)
    << "Cannot unpin a tensor that is pinned outside of DGL.";
  // 1. not pinned, do nothing
  if (!container_is_pinned) return;
  // 2. pinned by DGL, unpin it
  DeviceAPI::Get(kDLGPU)->UnpinData(ptr->dl_tensor.data);
  ptr->pinned_by_dgl_ = false;
280
281
}

282
template<typename T>
283
284
NDArray NDArray::FromVector(const std::vector<T>& vec, DLContext ctx) {
  const DLDataType dtype = DLDataTypeTraits<T>::dtype;
285
  int64_t size = static_cast<int64_t>(vec.size());
286
  NDArray ret = NDArray::Empty({size}, dtype, ctx);
287
288
289
290
291
292
293
294
295
296
297
298
299
300
  DeviceAPI::Get(ctx)->CopyDataFromTo(
      vec.data(),
      0,
      static_cast<T*>(ret->data),
      0,
      size * sizeof(T),
      DLContext{kDLCPU, 0},
      ctx,
      dtype,
      nullptr);
  return ret;
}

// export specializations
301
302
303
304
305
306
template NDArray NDArray::FromVector<int32_t>(const std::vector<int32_t>&, DLContext);
template NDArray NDArray::FromVector<int64_t>(const std::vector<int64_t>&, DLContext);
template NDArray NDArray::FromVector<uint32_t>(const std::vector<uint32_t>&, DLContext);
template NDArray NDArray::FromVector<uint64_t>(const std::vector<uint64_t>&, DLContext);
template NDArray NDArray::FromVector<float>(const std::vector<float>&, DLContext);
template NDArray NDArray::FromVector<double>(const std::vector<double>&, DLContext);
307

308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
template<typename T>
std::vector<T> NDArray::ToVector() const {
  const DLDataType dtype = DLDataTypeTraits<T>::dtype;
  CHECK(data_->dl_tensor.ndim == 1) << "ToVector() only supported for 1D arrays";
  CHECK(data_->dl_tensor.dtype == dtype) << "dtype mismatch";

  int64_t size = data_->dl_tensor.shape[0];
  std::vector<T> vec(size);
  const DLContext &ctx = data_->dl_tensor.ctx;
  DeviceAPI::Get(ctx)->CopyDataFromTo(
      static_cast<T*>(data_->dl_tensor.data),
      0,
      vec.data(),
      0,
      size * sizeof(T),
      ctx,
      DLContext{kDLCPU, 0},
      dtype,
      nullptr);
  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;
336

337
338
339
340
std::shared_ptr<SharedMemory> NDArray::GetSharedMem() const {
  return this->data_->mem;
}

341
342
343
344
bool NDArray::IsContainerPinned(NDArray::Container* ptr) {
  if (ptr->pinned_by_dgl_)
    return true;
  auto* tensor = &(ptr->dl_tensor);
345
346
347
348
349
350
351
  // Can only be pinned if on CPU...
  if (tensor->ctx.device_type != kDLCPU)
    return false;
  // ... and CUDA device API is enabled, and the tensor is indeed in pinned memory.
  auto device = DeviceAPI::Get(kDLGPU, true);
  return device && device->IsPinned(tensor->data);
}
352
353

void NDArray::Save(dmlc::Stream* strm) const {
354
  auto zc_strm = dynamic_cast<StreamWithBuffer*>(strm);
355
356
357
358
359
360
361
362
  if (zc_strm) {
    zc_strm->PushNDArray(*this);
    return;
  }
  SaveDLTensor(strm, const_cast<DLTensor*>(operator->()));
}

bool NDArray::Load(dmlc::Stream* strm) {
363
  auto zc_strm = dynamic_cast<StreamWithBuffer*>(strm);
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
  if (zc_strm) {
    *this = zc_strm->PopNDArray();
    return true;
  }
  uint64_t header, reserved;
  CHECK(strm->Read(&header))
      << "Invalid DLTensor file format";
  CHECK(strm->Read(&reserved))
      << "Invalid DLTensor file format";
  CHECK(header == kDGLNDArrayMagic)
      << "Invalid DLTensor file format";
  DLContext ctx;
  int ndim;
  DLDataType dtype;
  CHECK(strm->Read(&ctx))
      << "Invalid DLTensor file format";
  CHECK(strm->Read(&ndim))
      << "Invalid DLTensor file format";
  CHECK(strm->Read(&dtype))
      << "Invalid DLTensor file format";
  CHECK_EQ(ctx.device_type, kDLCPU)
      << "Invalid DLTensor context: can only save as CPU tensor";
  std::vector<int64_t> shape(ndim);
  if (ndim != 0) {
    CHECK(strm->ReadArray(&shape[0], ndim))
        << "Invalid DLTensor file format";
  }
  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;
  CHECK(strm->Read(&data_byte_size))
      << "Invalid DLTensor file format";
  CHECK(data_byte_size == num_elems * elem_bytes)
      << "Invalid DLTensor file format";
  if (data_byte_size != 0)  {
    // 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))
        << "Invalid DLTensor file format";
  }
  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
416
}  // namespace runtime
417
}  // namespace dgl
Minjie Wang's avatar
Minjie Wang committed
418

419
using namespace dgl::runtime;
Minjie Wang's avatar
Minjie Wang committed
420
421
422
423
424
425

void NDArrayDLPackDeleter(DLManagedTensor* tensor) {
  static_cast<NDArray::Container*>(tensor->manager_ctx)->DecRef();
  delete tensor;
}

426
int DGLArrayAlloc(const dgl_index_t* shape,
Minjie Wang's avatar
Minjie Wang committed
427
428
429
430
431
432
                  int ndim,
                  int dtype_code,
                  int dtype_bits,
                  int dtype_lanes,
                  int device_type,
                  int device_id,
433
                  DGLArrayHandle* out) {
Minjie Wang's avatar
Minjie Wang committed
434
435
436
437
438
439
440
441
442
443
444
445
446
  API_BEGIN();
  DLDataType dtype;
  dtype.code = static_cast<uint8_t>(dtype_code);
  dtype.bits = static_cast<uint8_t>(dtype_bits);
  dtype.lanes = static_cast<uint16_t>(dtype_lanes);
  DLContext ctx;
  ctx.device_type = static_cast<DLDeviceType>(device_type);
  ctx.device_id = device_id;
  *out = NDArray::Internal::MoveAsDLTensor(
      NDArray::Empty(std::vector<int64_t>(shape, shape + ndim), dtype, ctx));
  API_END();
}

447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
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) {
  API_BEGIN();
  DLDataType dtype;
  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);
  NDArray arr = NDArray::EmptyShared(mem_name, shape_vec, dtype,
                                     DLContext{kDLCPU, 0}, is_create);
  *out = NDArray::Internal::MoveAsDLTensor(arr);
  API_END();
}

467
int DGLArrayFree(DGLArrayHandle handle) {
Minjie Wang's avatar
Minjie Wang committed
468
469
470
471
472
  API_BEGIN();
  reinterpret_cast<NDArray::Container*>(handle)->DecRef();
  API_END();
}

473
474
475
int DGLArrayCopyFromTo(DGLArrayHandle from,
                       DGLArrayHandle to,
                       DGLStreamHandle stream) {
Minjie Wang's avatar
Minjie Wang committed
476
477
478
479
480
  API_BEGIN();
  NDArray::CopyFromTo(from, to, stream);
  API_END();
}

481
482
int DGLArrayFromDLPack(DLManagedTensor* from,
                       DGLArrayHandle* out) {
Minjie Wang's avatar
Minjie Wang committed
483
484
485
486
487
  API_BEGIN();
  *out = NDArray::Internal::MoveAsDLTensor(NDArray::FromDLPack(from));
  API_END();
}

488
489
490
491
492
493
494
inline bool is_aligned(const void* ptr, std::uintptr_t alignment) noexcept {
  auto iptr = reinterpret_cast<std::uintptr_t>(ptr);
  return !(iptr % alignment);
}

int DGLArrayToDLPack(DGLArrayHandle from, DLManagedTensor** out,
                     int alignment) {
Minjie Wang's avatar
Minjie Wang committed
495
  API_BEGIN();
496
497
  auto* nd_container = reinterpret_cast<NDArray::Container*>(from);
  DLTensor* nd = &(nd_container->dl_tensor);
498
  if (alignment != 0 && !is_aligned(nd->data, alignment)) {
499
    std::vector<int64_t> shape_vec(nd->shape, nd->shape + nd->ndim);
500
    NDArray copy_ndarray = NDArray::Empty(shape_vec, nd->dtype, nd->ctx);
501
502
503
504
505
    copy_ndarray.CopyFrom(nd);
    *out = copy_ndarray.ToDLPack();
  } else {
    *out = NDArray::Internal::ToDLPack(nd_container);
  }
Minjie Wang's avatar
Minjie Wang committed
506
507
508
  API_END();
}

509
void DGLDLManagedTensorCallDeleter(DLManagedTensor* dltensor) {
Minjie Wang's avatar
Minjie Wang committed
510
511
512
  (*(dltensor->deleter))(dltensor);
}

513
int DGLArrayCopyFromBytes(DGLArrayHandle handle,
Minjie Wang's avatar
Minjie Wang committed
514
515
516
                          void* data,
                          size_t nbytes) {
  API_BEGIN();
517
  DGLContext cpu_ctx;
Minjie Wang's avatar
Minjie Wang committed
518
519
520
521
  cpu_ctx.device_type = kDLCPU;
  cpu_ctx.device_id = 0;
  size_t arr_size = GetDataSize(*handle);
  CHECK_EQ(arr_size, nbytes)
522
      << "DGLArrayCopyFromBytes: size mismatch";
Minjie Wang's avatar
Minjie Wang committed
523
524
525
526
527
528
529
  DeviceAPI::Get(handle->ctx)->CopyDataFromTo(
      data, 0,
      handle->data, static_cast<size_t>(handle->byte_offset),
      nbytes, cpu_ctx, handle->ctx, handle->dtype, nullptr);
  API_END();
}

530
int DGLArrayCopyToBytes(DGLArrayHandle handle,
Minjie Wang's avatar
Minjie Wang committed
531
532
533
                        void* data,
                        size_t nbytes) {
  API_BEGIN();
534
  DGLContext cpu_ctx;
Minjie Wang's avatar
Minjie Wang committed
535
536
537
538
  cpu_ctx.device_type = kDLCPU;
  cpu_ctx.device_id = 0;
  size_t arr_size = GetDataSize(*handle);
  CHECK_EQ(arr_size, nbytes)
539
      << "DGLArrayCopyToBytes: size mismatch";
Minjie Wang's avatar
Minjie Wang committed
540
541
542
543
544
545
  DeviceAPI::Get(handle->ctx)->CopyDataFromTo(
      handle->data, static_cast<size_t>(handle->byte_offset),
      data, 0,
      nbytes, handle->ctx, cpu_ctx, handle->dtype, nullptr);
  API_END();
}
546
547
548
549

int DGLArrayPinData(DGLArrayHandle handle,
                    DLContext ctx) {
  API_BEGIN();
550
551
  auto* nd_container = reinterpret_cast<NDArray::Container*>(handle);
  NDArray::PinContainer(nd_container);
552
553
554
555
556
557
  API_END();
}

int DGLArrayUnpinData(DGLArrayHandle handle,
                      DLContext ctx) {
  API_BEGIN();
558
559
  auto* nd_container = reinterpret_cast<NDArray::Container*>(handle);
  NDArray::UnpinContainer(nd_container);
560
561
  API_END();
}