mxnet
tensor_blob.h
Go to the documentation of this file.
1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements. See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership. The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied. See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19 
28 #ifndef MXNET_TENSOR_BLOB_H_
29 #define MXNET_TENSOR_BLOB_H_
30 
31 #include <dmlc/logging.h>
32 #include <dmlc/json.h>
33 #include <dlpack/dlpack.h>
34 #include <vector>
35 #include <iostream>
36 #include <utility>
37 #include <algorithm>
38 #include "./base.h"
39 
40 namespace mxnet {
41 
42 // redefine DLPack enumeration to be backward compatible.
43 constexpr const int kCPU = kDLCPU;
44 constexpr const int kGPU = kDLGPU;
45 // extension type code under TVM function.
46 // Currently NNVM reserved 16 to 19 type code from TVM
47 // 16, 17, 18 is used by NNVM compiler already.
48 // Pick code 19 for MXNet NDArray
49 constexpr const int kTVMNDArrayTypeCode = 19;
50 
51 /* Forward declaration for friend declaration in TBlob */
52 class NDArray;
53 
66 class TBlob {
67  friend class NDArray;
68  public:
70  void *dptr_;
75 
77  TBlob(void)
78  : dptr_(NULL),
79  type_flag_(mshadow::DataType<real_t>::kFlag) {
80  SetDLTensor(cpu::kDevMask, 0);
81  }
89  template<typename DType>
90  TBlob(DType *dptr, const mxnet::TShape &shape, int dev_mask, int dev_id = -1)
91  : dptr_(dptr), shape_(shape),
92  type_flag_(mshadow::DataType<DType>::kFlag) {
93  SetDLTensor(dev_mask, dev_id);
94  }
103  TBlob(void *dptr, const mxnet::TShape &shape, int dev_mask, int type_flag, int dev_id = -1)
104  : dptr_(dptr), shape_(shape), type_flag_(type_flag) {
105  SetDLTensor(dev_mask, dev_id);
106  }
111  explicit TBlob(const DLTensor &dltensor)
112  : dptr_(dltensor.data),
113  shape_(mxnet::TShape(dltensor.shape, dltensor.shape + dltensor.ndim)),
114  type_flag_(DLDataTypeTransform(dltensor.dtype)),
115  dltensor_(dltensor) {
116  // compactness check for DLTensor
117  if (dltensor.strides != nullptr) {
118  // check strides
119  const int &ndim = dltensor.ndim;
120  const int64_t *shape = dltensor.shape;
121  const int64_t *strides = dltensor.strides;
122  if (ndim >= 1) {
123  bool err = false;
124  if (strides[ndim - 1] != 1) {
125  err = true;
126  } else {
127  for (int i = ndim - 2; i >= 0; --i) {
128  if (strides[i] != shape[i + 1] * strides[i + 1]) {
129  err = true;
130  break;
131  }
132  }
133  }
134  if (err) {
135  LOG(FATAL) << "Unsupported DLPack because MXNet only support compact tensor now";
136  }
137  }
138  }
139  }
147  template<typename Device, int dim, typename DType>
148  TBlob(const mshadow::Tensor<Device, dim, DType> &src) { // NOLINT(*)
149  *this = src;
150  }
155  TBlob(const TBlob &src): dptr_(src.dptr_), shape_(src.shape_), type_flag_(src.type_flag_) {
156  this->SetDLTensor(src.dev_mask(), src.dev_id());
157  }
166  template<typename Device, int dim, typename DType>
168  dptr_ = src.dptr_;
169  shape_ = src.shape_;
170  type_flag_ = mshadow::DataType<DType>::kFlag;
171  SetDLTensor(Device::kDevMask, -1);
172  return *this;
173  }
179  inline TBlob &operator=(const TBlob &src) {
180  dptr_ = src.dptr_;
181  shape_ = src.shape_;
182  type_flag_ = src.type_flag_;
183  SetDLTensor(src.dev_mask(), src.dev_id());
184  return *this;
185  }
189  inline bool CheckContiguous(void) const {
190  return true;
191  }
197  inline TBlob reshape(const mxnet::TShape& shape) const {
198  CHECK_EQ(this->shape_.Size(), shape.Size()) << "Shape size mismatch "
199  << this->shape_.Size() << " v.s. " << shape.Size();
200  TBlob ret(this->dptr_, shape, this->dev_mask(), this->type_flag_, this->dev_id());
201  return ret;
202  }
210  template<typename Device, typename DType>
212  mshadow::Stream<Device> *stream = NULL) const {
213  CHECK(Device::kDevMask == this->dev_mask())
214  << "TBlob.get: device type do not match specified type";
215  CHECK(mshadow::DataType<DType>::kFlag == type_flag_)
216  << "TBlob.get_with_shape: data type do not match specified type."
217  << "Expected: " << type_flag_ << " v.s. given " << mshadow::DataType<DType>::kFlag;
218  return mshadow::Tensor<Device, 2, DType>(static_cast<DType*>(dptr_),
219  shape_.FlatTo2D(),
220  stream);
221  }
229  template<typename Device, typename DType>
231  mshadow::Stream<Device> *stream = NULL) const {
232  return this->get_with_shape<Device, 1, DType>(
233  mshadow::Shape1(shape_.Size()), stream);
234  }
236  inline int ndim(void) const {
237  return shape_.ndim();
238  }
245  inline index_t size(index_t idx) const {
246  return shape_[idx];
247  }
249  inline size_t Size(void) const {
250  return shape_.Size();
251  }
253  template<typename DType>
254  inline DType* dptr() const {
255  CHECK(mshadow::DataType<DType>::kFlag == type_flag_)
256  << "TBlob.get_with_shape: data type do not match specified type."
257  << "Expected: " << type_flag_ << " v.s. given " << mshadow::DataType<DType>::kFlag;
258  return static_cast<DType*>(dptr_);
259  }
261  inline int dev_mask() const {
262  return dltensor_.ctx.device_type;
263  }
265  inline int dev_id() const {
266  return dltensor_.ctx.device_id;
267  }
272  inline const DLTensor& dltensor() const {
273  return dltensor_;
274  }
275 
285  template<typename Device, int dim, typename DType>
287  CHECK(Device::kDevMask == this->dev_mask())
288  << "TBlob.get: device type do not match specified type";
289  return mshadow::Tensor<Device, dim, DType>(dptr<DType>(),
290  shape_.get<dim>(), shape_[shape_.ndim() - 1], stream);
291  }
302  template<typename Device, int dim, typename DType>
304  const mshadow::Shape<dim> &shape,
305  mshadow::Stream<Device> *stream = NULL) const {
306  CHECK(Device::kDevMask == this->dev_mask())
307  << "TBlob.get: device type do not match specified type";
308  CHECK_EQ(this->CheckContiguous(), true) << "TBlob.get_reshape: must be contiguous";
309  CHECK_EQ(this->shape_.Size(), static_cast<size_t>(shape.Size()))
310  << "TBlob.get_with_shape: new and old shape do not match total elements";
311  return mshadow::Tensor<Device, dim, DType>(dptr<DType>(), shape,
312  shape[dim - 1], stream);
313  }
323  template<typename Device, typename DType>
325  int axis, mshadow::Stream<Device> *stream = NULL) const {
326  return this->get_with_shape<Device, 3, DType>(
327  this->shape_.FlatTo3D(axis), stream);
328  }
339  template<typename Device, typename DType>
341  int axis_begin, int axis_end,
342  mshadow::Stream<Device> *stream = NULL) const {
343  return this->get_with_shape<Device, 3, DType>(
344  this->shape_.FlatTo3D(axis_begin, axis_end), stream);
345  }
355  template<typename Device, int dim, typename DType>
357  mshadow::Stream<Device> *stream = NULL) const {
358  mshadow::Shape<dim> shape;
359  shape[0] = 1;
360  // Pad higher dimensions in case dim > ndim()
361  for (int i = 0; i < dim - ndim(); ++i) {
362  shape[i] = 1;
363  }
364  // Collapse higher dimensions in case dim < ndim()
365  for (int i = 0; i < ndim() - dim + 1; ++i) {
366  shape[0] *= shape_[i];
367  }
368  // Preserve lower dimensions.
369  for (int i = std::max(0, ndim() - dim + 1); i < ndim(); ++i) {
370  shape[i - ndim() + dim] = shape_[i];
371  }
372  return this->get_with_shape<Device, dim, DType>(shape, stream);
373  }
374 
375  private:
376  static DLDataType DTypeTransform(int type_flag) {
377  switch (type_flag) {
378  case mshadow::kFloat32: return DLDataType{kDLFloat, 32, 1};
379  case mshadow::kFloat64: return DLDataType{kDLFloat, 64, 1};
380  case mshadow::kFloat16: return DLDataType{kDLFloat, 16, 1};
381  case mshadow::kUint8: return DLDataType{kDLUInt, 8, 1};
382  case mshadow::kInt32: return DLDataType{kDLInt, 32, 1};
383  case mshadow::kInt8: return DLDataType{kDLInt, 8, 1};
384  case mshadow::kInt64: return DLDataType{kDLInt, 64, 1};
385  case mshadow::kBool: return DLDataType{kDLUInt, 1, 1};
386  default: {
387  LOG(FATAL) << "Unknown type_flag=" << type_flag;
388  return DLDataType();
389  }
390  }
391  }
392  static int DLDataTypeTransform(DLDataType dldata_type) {
393  if (dldata_type.lanes != 1) {
394  LOG(FATAL) << "Unsupported DLDataType whose lanes != 1";
395  }
396  switch (dldata_type.code) {
397  case kDLFloat:
398  switch (dldata_type.bits) {
399  case 16: return mshadow::kFloat16;
400  case 32: return mshadow::kFloat32;
401  case 64: return mshadow::kFloat64;
402  }
403  break;
404  case kDLUInt:
405  switch (dldata_type.bits) {
406  case 8: return mshadow::kUint8;
407  }
408  break;
409  case kDLInt:
410  switch (dldata_type.bits) {
411  case 8: return mshadow::kInt8;
412  case 32: return mshadow::kInt32;
413  case 64: return mshadow::kInt64;
414  }
415  break;
416  }
417  LOG(FATAL) << "Unknown DLDataType{" << dldata_type.code
418  << ", " << dldata_type.bits
419  << ", " << dldata_type.lanes << "}";
420  return mshadow::kFloat32;
421  }
422 
423  inline void SetDLTensor(int dev_mask, int dev_id) {
424  dltensor_.data = dptr_;
425  dltensor_.ctx = DLContext{static_cast<DLDeviceType>(dev_mask), dev_id};
426  dltensor_.ndim = shape_.ndim();
427  dltensor_.dtype = DTypeTransform(type_flag_);
428  dltensor_.shape = shape_.data();
429  dltensor_.strides = nullptr;
430  dltensor_.byte_offset = 0;
431  }
432 
433  private:
435  DLTensor dltensor_;
436 };
437 } // namespace mxnet
438 
439 namespace dmlc {
440 // Add a few patches to support mxnet::TShape in dmlc/parameter.
441 DMLC_DECLARE_TYPE_NAME(mxnet::TShape, "Shape(tuple)");
446 
447 namespace parameter {
448 
449 template<>
450 class FieldEntry<mxnet::TShape>
451  : public FieldEntryBase<FieldEntry<mxnet::TShape>, mxnet::TShape> {
452  public:
453  FieldEntry() : enforce_nonzero_(false), expect_ndim_(0) {}
454  // parent class
455  typedef FieldEntryBase<FieldEntry<mxnet::TShape>, mxnet::TShape> Parent;
456 
457  virtual void Check(void *head) const {
458  Parent::Check(head);
459  mxnet::TShape &v = this->Get(head);
460  if (expect_ndim_ != 0 && v.ndim() != expect_ndim_) {
461  std::ostringstream os;
462  os << "value " << v << "for Parameter " << this->key_
463  << " has wrong dimensions, expected dimension=" << expect_ndim_;
464  throw dmlc::ParamError(os.str());
465  }
466  if (enforce_nonzero_) {
467  for (int i = 0; i < v.ndim(); ++i) {
468  if (v[i] == 0U) {
469  std::ostringstream os;
470  os << "value " << v << "for Parameter " << this->key_
471  << " is invalid, the input shape must be nonzero in all dimensions";
472  throw dmlc::ParamError(os.str());
473  }
474  }
475  }
476  }
478  this->enforce_nonzero_ = true;
479  return this->self();
480  }
482  expect_ndim_ = ndim;
483  return this->self();
484  }
485 
486  private:
487  // whether all the entries need to be nonzero
488  bool enforce_nonzero_;
489  // expected number of dimension, default = 0 means no restriction.
490  int expect_ndim_;
491 };
492 
493 } // namespace parameter
494 } // namespace dmlc
495 
496 #endif // MXNET_TENSOR_BLOB_H_
#define DMLC_DECLARE_TYPE_NAME(Type, Name)
macro to quickly declare traits information
Definition: type_traits.h:133
Definition: base.h:307
TBlob & operator=(const mshadow::Tensor< Device, dim, DType > &src)
assignment from tensor
Definition: tensor_blob.h:167
The common header of DLPack.
Definition: dlpack.h:81
MSHADOW_XINLINE index_t Size(void) const
Definition: tensor.h:126
mxnet::TShape shape_
shape of the tensor
Definition: tensor_blob.h:72
constexpr const int kTVMNDArrayTypeCode
Definition: tensor_blob.h:49
DType * dptr_
pointer to the data
Definition: tensor.h:416
TBlob(const DLTensor &dltensor)
constructor that construct TBlob from DLTensor
Definition: tensor_blob.h:111
namespace of mxnet
Definition: base.h:89
A Device context for Tensor and operator.
Definition: dlpack.h:69
Shape< dimension > shape_
shape of the tensor
Definition: tensor.h:418
int64_t * strides
strides of the tensor (in number of elements, not bytes) can be NULL, indicating tensor is compact an...
Definition: dlpack.h:144
mshadow::default_real_t real_t
data type that will be used to store ndarray
Definition: base.h:97
TBlob(void)
default constructor, default copy assign will work
Definition: tensor_blob.h:77
int type_flag_
type flag of the tensor blob
Definition: tensor_blob.h:74
mshadow::Tensor< Device, dim, DType > get_with_shape(const mshadow::Shape< dim > &shape, mshadow::Stream< Device > *stream=NULL) const
fetch a tensor in given shape If size do not match the stored size, an error will be issued ...
Definition: tensor_blob.h:303
FieldEntry< mxnet::TShape > & set_expect_ndim(int ndim)
Definition: tensor_blob.h:481
FieldEntry< mxnet::TShape > & enforce_nonzero()
Definition: tensor_blob.h:477
FieldEntryBase< FieldEntry< mxnet::TShape >, mxnet::TShape > Parent
Definition: tensor_blob.h:455
mshadow::Tensor< Device, 1, DType > FlatTo1D(mshadow::Stream< Device > *stream=NULL) const
flatten the tensor to 1 dimension, collapse all the dimensions together.
Definition: tensor_blob.h:230
const dim_t * data() const
Definition: tuple.h:523
Definition: dlpack.h:80
TBlob(void *dptr, const mxnet::TShape &shape, int dev_mask, int type_flag, int dev_id=-1)
constructor that construct TBlob from contiguous memory
Definition: tensor_blob.h:103
Definition: dlpack.h:82
uint8_t code
Type code of base types. We keep it uint8_t instead of DLDataTypeCode for minimal memory footprint...
Definition: dlpack.h:99
int device_id
The device index.
Definition: dlpack.h:73
constexpr const int kGPU
Definition: tensor_blob.h:44
Lightweight JSON Reader/Writer that read save into C++ data structs. This includes STL composites and...
CPU device.
Definition: dlpack.h:40
index_t size(index_t idx) const
return size of i-th dimension, start counting from highest dimension. return type needs to be a signe...
Definition: tensor_blob.h:245
size_t Size() const
Definition: tuple.h:494
void * dptr_
pointer to the data
Definition: tensor_blob.h:70
int64_t * shape
The shape of the tensor.
Definition: dlpack.h:139
namespace for dmlc
Definition: array_view.h:12
uint8_t bits
Number of bits, common choices are 8, 16, 32.
Definition: dlpack.h:103
void * data
The opaque data pointer points to the allocated data. This will be CUDA device pointer or cl_mem hand...
Definition: dlpack.h:131
Definition: base.h:312
DLDataType dtype
The data type of the pointer.
Definition: dlpack.h:137
DType * dptr() const
get pointer in dtype
Definition: tensor_blob.h:254
DLDeviceType
The device type in DLContext.
Definition: dlpack.h:38
Definition: base.h:314
int ndim(void) const
return number of dimension of the tensor inside
Definition: tensor_blob.h:236
Definition: base.h:308
DLDeviceType device_type
The device type used in the device.
Definition: dlpack.h:71
TBlob reshape(const mxnet::TShape &shape) const
reshape to shape
Definition: tensor_blob.h:197
MSHADOW_XINLINE Shape< 1 > Shape1(index_t s0)
construct a one dimension shape, stride will equal s0
Definition: tensor.h:188
TBlob(const mshadow::Tensor< Device, dim, DType > &src)
constructor from tensor
Definition: tensor_blob.h:148
Definition: base.h:311
A dynamic sized array data structure that is optimized for storing small number of elements with same...
Definition: tuple.h:54
TBlob(DType *dptr, const mxnet::TShape &shape, int dev_mask, int dev_id=-1)
constructor that construct TBlob from contiguous memory
Definition: tensor_blob.h:90
int ndim
Number of dimensions.
Definition: dlpack.h:135
TBlob & operator=(const TBlob &src)
assignment from TBlob (copy assignment)
Definition: tensor_blob.h:179
static const int kDevMask
device flag number, identifies this device
Definition: tensor.h:25
const DLTensor & dltensor() const
return the corresponding DLTensor
Definition: tensor_blob.h:272
Definition: base.h:310
A Shape class that is used to represent shape of each tensor.
Definition: tuple.h:413
mshadow::Tensor< Device, 3, DType > FlatTo3D(int axis_begin, int axis_end, mshadow::Stream< Device > *stream=NULL) const
flatten the tensor to 3 dimension, collapse the dimension: [0, axis_begin), [axis_begin, axis_end], (axis_end, ndim).
Definition: tensor_blob.h:340
mshadow::Tensor< Device, dim, DType > FlatToKD(mshadow::Stream< Device > *stream=NULL) const
flatten the tensor to specified number of dimensions, collapse the highest dimensions or pad with hig...
Definition: tensor_blob.h:356
mshadow::Tensor< Device, 2, DType > FlatTo2D(mshadow::Stream< Device > *stream=NULL) const
flatten the tensor to 2 dimension, collapse the higher dimensions together
Definition: tensor_blob.h:211
virtual void Check(void *head) const
Definition: tensor_blob.h:457
int ndim() const
Definition: tuple.h:193
Definition: tensor.h:550
bool CheckContiguous(void) const
Definition: tensor_blob.h:189
Definition: base.h:318
namespace for mshadow
Definition: base.h:282
mshadow::Tensor< Device, 3, DType > FlatTo3D(int axis, mshadow::Stream< Device > *stream=NULL) const
flatten the tensor to 3 dimension, collapse the dimension before and after specified axis...
Definition: tensor_blob.h:324
mshadow::index_t index_t
index type usually use unsigned
Definition: base.h:95
constexpr const int kCPU
Definition: tensor_blob.h:43
DLContext ctx
The device context of the tensor.
Definition: dlpack.h:133
CUDA GPU device.
Definition: dlpack.h:42
Definition: base.h:309
Definition: base.h:313
The data type the tensor can hold.
Definition: dlpack.h:93
general tensor
Definition: tensor.h:402
uint16_t lanes
Number of lanes in the type, used for vector types.
Definition: dlpack.h:105
Plain C Tensor object, does not manage memory.
Definition: dlpack.h:111
FieldEntry()
Definition: tensor_blob.h:453
ndarray interface
Definition: ndarray.h:82
uint64_t byte_offset
The offset in bytes to the beginning pointer to data.
Definition: dlpack.h:146
int dev_mask() const
device mask of the corresponding device
Definition: tensor_blob.h:261
TBlob(const TBlob &src)
constructor from TBlob (copy constructor)
Definition: tensor_blob.h:155
tensor blob class that can be used to hold tensor of any dimension, any device and any data type...
Definition: tensor_blob.h:66
int dev_id() const
device index of the corresponding device
Definition: tensor_blob.h:265
computaion stream structure, used for asynchronous computations
Definition: tensor.h:365
size_t Size(void) const
total number of elements in the tensor
Definition: tensor_blob.h:249