mxnet
tuple.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  */
24 #ifndef MXNET_TUPLE_H_
25 #define MXNET_TUPLE_H_
26 
27 #include <vector>
28 #include <type_traits>
29 #include <algorithm>
30 #include <utility>
31 #include <iostream>
32 #include <string>
33 #include "nnvm/op_attr_types.h"
34 #include "nnvm/graph_attr_types.h"
35 #include "nnvm/graph.h"
36 #include "nnvm/pass.h"
37 
38 namespace mxnet {
39 
53 template<typename ValueType>
54 class Tuple {
55  public:
57  Tuple() = default;
59  inline ~Tuple() {
60  delete [] data_heap_;
61  }
66  inline Tuple(const Tuple<ValueType>& s) {
67  if (s.ndim() == -1) {
68  this->SetDim(-1);
69  } else {
70  this->assign(s.begin(), s.end());
71  }
72  }
77  inline Tuple(std::initializer_list<ValueType> init) {
78  this->assign(init.begin(), init.end());
79  }
84  inline Tuple(std::vector<ValueType> init) { // NOLINT(runtime/explicit)
85  this->assign(init.begin(), init.end());
86  }
92  inline Tuple(Tuple<ValueType>&& src) { // NOLINT(runtime/explicit)
93  this->swap(src);
94  }
101  template<typename RandomAccessIterator>
102  inline Tuple(RandomAccessIterator begin,
103  RandomAccessIterator end) {
104  this->assign(begin, end);
105  }
112  template<typename RandomAccessIterator>
113  inline void assign(RandomAccessIterator begin,
114  RandomAccessIterator end) {
115  this->SetDim(end - begin);
116  CHECK_GE(ndim(), 0);
117  std::copy(begin, end, this->begin());
118  }
123  inline void swap(Tuple<ValueType>& other) { // NOLINT(*)
124  std::swap(ndim_, other.ndim_);
125  std::swap(num_heap_allocated_, other.num_heap_allocated_);
126  std::swap(data_stack_, other.data_stack_);
127  std::swap(data_heap_, other.data_heap_);
128  }
135  if (src.ndim() == -1) {
136  this->SetDim(-1);
137  } else {
138  this->assign(src.begin(), src.end());
139  }
140  return *this;
141  }
148  Tuple<ValueType>(std::move(src)).swap(*this);
149  return *this;
150  }
156  inline Tuple<ValueType> &operator=(std::initializer_list<ValueType> init) {
157  this->assign(init.begin(), init.end());
158  return *this;
159  }
164  inline bool operator==(const Tuple<ValueType> &s) const {
165  if (ndim_ != s.ndim_) return false;
166  if (ndim() == -1) return true;
167  return std::equal(begin(), end(), s.begin());
168  }
173  inline bool operator!=(const Tuple<ValueType> &s) const {
174  return !(*this == s);
175  }
177  inline const ValueType *begin() const {
178  return ndim_ <= kStackCache ? data_stack_ : data_heap_;
179  }
181  inline ValueType *begin() {
182  return ndim_ <= kStackCache ? data_stack_ : data_heap_;
183  }
185  inline const ValueType* end() const {
186  return ndim_ <= kStackCache ? (data_stack_ + ndim_): (data_heap_ + ndim_);
187  }
189  inline ValueType* end() {
190  return ndim_ <= kStackCache ? (data_stack_ + ndim_): (data_heap_ + ndim_);
191  }
193  inline int ndim() const {
194  return ndim_;
195  }
201  inline ValueType& operator[](int i) {
202  CHECK(i >= 0 && i < ndim()) << "index = " << i << " must be in range [0, " << ndim() << ")";
203  return begin()[i];
204  }
210  inline const ValueType& operator[](int i) const {
211  CHECK(i >= 0 && i < ndim()) << "index = " << i << " must be in range [0, " << ndim() << ")";
212  return begin()[i];
213  }
218  inline void Save(dmlc::JSONWriter* writer) const {
219  std::vector<ValueType> tmp(begin(), end());
220  writer->Write(tmp);
221  }
226  inline void Load(dmlc::JSONReader* reader) {
227  std::vector<ValueType> tmp;
228  reader->Read(&tmp);
229  this->assign(tmp.begin(), tmp.end());
230  }
237  friend std::ostream &operator<<(std::ostream &os, const Tuple<ValueType> &t) {
238  if (t.ndim() == -1) {
239  // If t is an unknown shape, return string "None".
240  // This is consistent with returning unknown shape in Python and generating
241  // C++ operator APIs by OpWrapperGenerator.py (defaultString) in cpp-package.
242  os << "None";
243  return os;
244  }
245  os << '[';
246  const ValueType* begin = t.begin();
247  const ValueType* end = t.end();
248  for (const ValueType* it = begin; it != end; ++it) {
249  if (it != begin) os << ',';
250  os << *it;
251  }
252  os << ']';
253  return os;
254  }
261  friend std::istream &operator>>(std::istream &is, Tuple<ValueType> &t) {
262  // get (
263  while (true) {
264  char ch = is.peek();
265  if (isdigit(ch) || ch == '-') {
266  ValueType idx;
267  if (is >> idx) {
268  t.assign(&idx, &idx + 1);
269  }
270  return is;
271  }
272  is.get();
273  if (ch == '(' || ch == '[') break;
274  if (!isspace(ch)) {
275  is.setstate(std::ios::failbit);
276  return is;
277  }
278  }
279  // Handle empty tuple. A tensor whose shape is an empty tuple
280  // represents a scalar with ndim = 0.
281  while (isspace(is.peek())) {
282  is.get();
283  }
284  if (is.peek() == ')' || is.peek() == ']') {
285  is.get();
286  t.SetDim(0);
287  return is;
288  }
289  // Handle non-empty tuple
290  ValueType idx;
291  std::vector<ValueType> tmp;
292  while (is >> idx) {
293  tmp.push_back(idx);
294  char ch;
295  do {
296  ch = is.get();
297  } while (isspace(ch));
298  if (std::is_integral<ValueType>::value && ch == 'L') {
299  ch = is.get();
300  }
301  if (ch == ',') {
302  while (true) {
303  ch = is.peek();
304  if (isspace(ch)) {
305  is.get(); continue;
306  }
307  if (ch == ')' || ch == ']') {
308  is.get(); break;
309  }
310  break;
311  }
312  if (ch == ')' || ch == ']') break;
313  } else if (ch == ')' || ch == ']') {
314  break;
315  } else {
316  is.setstate(std::ios::failbit);
317  return is;
318  }
319  }
320  t.assign(tmp.begin(), tmp.end());
321  return is;
322  }
329  template<typename DType = ValueType, typename TStream>
330  inline void Save(TStream *strm) const;
338  template<typename DType = ValueType, typename TStream>
339  inline bool Load(TStream *strm);
340 
341  protected:
342  // stack cache size
343  static const int kStackCache = 4;
345  int ndim_{0};
351  ValueType* data_heap_{nullptr};
352  // internal function to change the dimension
353  inline void SetDim(int ndim) {
354  CHECK_GE(ndim, -1) << "ndim cannot be less than -1, received " << ndim;
355  if (ndim > kStackCache &&
356  ndim > num_heap_allocated_) {
357  delete [] data_heap_;
358  data_heap_ = new ValueType[ndim];
360  } else if (ndim <= 0 && data_heap_ != nullptr) {
361  delete [] data_heap_;
362  data_heap_ = nullptr;
364  }
365  ndim_ = ndim;
366  }
367 };
368 
369 
371 inline bool ndim_is_known(const int ndim) {
372  CHECK_GE(ndim, -1) << "shape ndim must be >= -1, while received " << ndim;
373  return ndim != -1;
374 }
375 
377 inline bool dim_size_is_known(const dim_t dim_size) {
378  CHECK_GE(dim_size, -1) << "shape dim size must be >= -1, while received " << dim_size;
379  return dim_size != -1;
380 }
381 
395 class TShape : public Tuple<dim_t> {
396  public:
398  TShape() {
399  this->SetDim(-1);
400  }
406  inline TShape(const int ndim, const dim_t value) { // NOLINT(*)
407  this->SetDim(ndim);
408  if (ndim > 0) {
409  std::fill_n(begin(), ndim, value);
410  }
411  }
416  inline TShape(const Tuple<dim_t>& s) { // NOLINT(*)
417  if (s.ndim() == -1) {
418  this->SetDim(-1);
419  } else {
420  this->assign(s.begin(), s.end());
421  }
422  }
427  inline TShape(std::initializer_list<dim_t> init) {
428  this->assign(init.begin(), init.end());
429  }
434  inline TShape(Tuple<dim_t>&& s) { // NOLINT(*)
435  this->swap(s);
436  }
445  template<typename RandomAccessIterator,
446  typename std::enable_if<
447  std::is_same<typename std::iterator_traits<RandomAccessIterator>::iterator_category,
448  std::random_access_iterator_tag>::value, int>::type = 0>
449  inline TShape(RandomAccessIterator begin,
450  RandomAccessIterator end) {
451  this->assign(begin, end);
452  }
458  inline TShape& operator=(const Tuple<dim_t>& src) {
459  if (src.ndim() == -1) {
460  this->SetDim(-1);
461  } else {
462  this->assign(src.begin(), src.end());
463  }
464  return *this;
465  }
471  inline TShape& operator=(Tuple<dim_t>&& src) { // NOLINT(*)
472  TShape(std::move(src)).swap(*this); // NOLINT(*)
473  return *this;
474  }
476  inline size_t Size() const {
477  CHECK(ndim_is_known(this->ndim())) << "Shape is unknown.";
478  dim_t size = 1;
479  const dim_t* start = begin(), *fin = end();
480  for (const dim_t* it = start; it != fin; ++it) {
481  CHECK(dim_size_is_known(*it)) << "Shape dim size cannot be a negative value " << *it;
482  size *= *it;
483  }
484  return size;
485  }
491  inline size_t ProdShape(int dimstart, int dimend) const {
492  CHECK(ndim_is_known(this->ndim())) << "Shape is unknown.";
493  CHECK_GE(dimstart, 0) << "dimstart must be >= 0, while received " << dimstart;
494  CHECK_LE(dimend, this->ndim()) << "dimend must be <= " << this->ndim()
495  << ", while received " << dimend;
496  dim_t num = 1;
497  const dim_t *d = this->data();
498  for (int i = dimstart; i < dimend; ++i) {
499  CHECK(dim_size_is_known(d[i])) << "Shape dim size must be known, while received " << d[i];
500  num *= d[i];
501  }
502  return num;
503  }
505  inline const dim_t *data() const {
506  return begin();
507  }
509  inline dim_t *data() {
510  return begin();
511  }
512 #ifdef MSHADOW_XINLINE
513  template<int dim>
514  inline TShape(const mshadow::Shape<dim> &s) {// NOLINT(*)
515  this->assign(s.shape_, s.shape_ + dim);
516  }
517 
518  template<int dim>
519  inline TShape(mshadow::Shape<dim> &&s) {// NOLINT(*)
520  this->assign(s.shape_, s.shape_ + dim);
521  }
528  template<int dim>
529  inline TShape &operator=(const mshadow::Shape<dim> &shape) {
530  this->assign(shape.shape_, shape.shape_ + dim);
531  return *this;
532  }
538  template<int dim>
539  inline mshadow::Shape<dim> get() const {
540  CHECK_EQ(dim, ndim())
541  << "dimension do not match target dimension " << dim << " vs " << ndim();
542  const dim_t *d = this->data();
543  mshadow::Shape<dim> s;
544  for (int i = 0; i < dim; ++i) {
545  s[i] = d[i];
546  }
547  return s;
548  }
553  inline mshadow::Shape<2> FlatTo2D(void) const {
554  mshadow::Shape<2> s;
555  CHECK(ndim_is_known(ndim())) << "shape must have a valid ndim";
556  if (ndim() == 0) return mshadow::Shape2(1, 1);
557  const dim_t *d = this->data();
558  s.shape_[1] = d[ndim() - 1];
559  dim_t ymax = 1;
560  for (int i = 1; i < ndim(); ++i) {
561  ymax *= d[i - 1];
562  }
563  s.shape_[0] = ymax;
564  return s;
565  }
572  inline mshadow::Shape<3> FlatTo3D(int axis_begin, int axis_end) const {
573  CHECK(axis_end >= axis_begin);
574  mshadow::Shape<3> s;
575  CHECK(ndim_is_known(ndim())) << "shape must have a valid ndim";
576  if (ndim() == 0) return mshadow::Shape3(1, 1, 1);
577  const dim_t *d = this->data();
578  s.shape_[0] = 1;
579  s.shape_[1] = 1;
580  s.shape_[2] = 1;
581 
582  for (int i = 0; i < axis_begin; ++i) {
583  s.shape_[0] *= d[i];
584  }
585  for (int i = axis_begin; i <= axis_end; ++i) {
586  s.shape_[1] *= d[i];
587  }
588  for (int i = axis_end + 1; i < ndim(); ++i) {
589  s.shape_[2] *= d[i];
590  }
591  return s;
592  }
598  inline mshadow::Shape<3> FlatTo3D(int axis) const {
599  return FlatTo3D(axis, axis);
600  }
601  inline bool operator==(const TShape &s) const {
602  if (ndim() != s.ndim()) return false;
603  return std::equal(begin(), end(), s.begin());
604  }
605  inline bool operator!=(const TShape &s) const {
606  return !(*this == s);
607  }
613  template<int dim>
614  inline bool operator==(const mshadow::Shape<dim> &s) const {
615  if (ndim_ != dim) return false;
616  const dim_t *d = dim <= kStackCache ? data_stack_ : data_heap_;
617  for (size_t i = 0; i < dim; ++i) {
618  if (d[i] != s.shape_[i]) return false;
619  }
620  return true;
621  }
627  template<int dim>
628  inline bool operator!=(const mshadow::Shape<dim> &s) const {
629  return !(*this == s);
630  }
631 #endif
632 };
633 
635 inline bool ndim_is_known(const TShape& x) {
636  return ndim_is_known(x.ndim());
637 }
638 
640 inline bool dim_size_is_known(const TShape& x, const int idx) {
641  CHECK(idx >= 0 && idx < x.ndim())
642  << "idx = " << idx << " exceeds shape dimension range [0, " << x.ndim() << ")";
643  return dim_size_is_known(x[idx]);
644 }
645 
648 inline bool shape_is_known(const TShape& x) {
649  if (!ndim_is_known(x)) return false;
650  for (int i = 0; i < x.ndim(); ++i) {
651  if (!dim_size_is_known(x, i)) return false;
652  }
653  return true;
654 }
655 
657 template<typename SrcIter, typename DstIter>
658 inline DstIter ShapeTypeCast(const SrcIter begin,
659  const SrcIter end,
660  DstIter dst_begin) {
661  typedef typename std::iterator_traits<SrcIter>::value_type SrcDType;
662  typedef typename std::iterator_traits<DstIter>::value_type DstDType;
663  auto cast = [](const SrcDType& dim) { return static_cast<DstDType>(dim); };
664  return std::transform(begin, end, dst_begin, cast);
665 }
666 
668 template<typename SrcIter>
669 inline TShape ShapeTypeCast(const SrcIter begin, const SrcIter end) {
670  size_t ndim = std::distance(begin, end);
671  TShape res(ndim, -1);
672  ShapeTypeCast(begin, end, res.begin());
673  return res;
674 }
675 
677 template<typename ValueType>
678 template<typename DType, typename TStream>
679 inline void Tuple<ValueType>::Save(TStream *strm) const {
680  strm->Write(&ndim_, sizeof(ndim_));
681  if (typeid(DType) == typeid(ValueType)) {
682  strm->Write(begin(), sizeof(ValueType) * ndim_);
683  } else {
684  std::vector<DType> buffer(ndim_);
685  ShapeTypeCast(begin(), end(), buffer.data());
686  strm->Write(buffer.data(), sizeof(DType) * ndim_);
687  }
688 }
689 
691 template<typename ValueType>
692 template<typename DType, typename TStream>
693 inline bool Tuple<ValueType>::Load(TStream *strm) {
694  if (strm->Read(&ndim_, sizeof(ndim_)) != sizeof(ndim_)) return false;
695  this->SetDim(ndim_);
696  size_t nread = sizeof(DType) * ndim_;
697  if (typeid(DType) == typeid(ValueType)) {
698  if (strm->Read(begin(), nread) != nread) return false;
699  } else {
700  std::vector<DType> buffer(ndim_);
701  if (strm->Read(buffer.data(), nread) != nread) return false;
702  ShapeTypeCast(buffer.begin(), buffer.end(), begin());
703  }
704  return true;
705 }
706 
707 } // namespace mxnet
708 
709 namespace std {
711 template<typename T>
712 struct hash<mxnet::Tuple<T> > {
714  size_t operator()(const mxnet::Tuple<T>& val) const {
715  std::hash<int> hash_int;
716  size_t res = hash_int(val.ndim());
717  for (int i = 0; i < val.ndim(); ++i) {
718  res = dmlc::HashCombine(res, val[i]);
719  }
720  return res;
721  }
722 };
723 
725 template<>
726 struct hash<mxnet::TShape> {
728  size_t operator()(const mxnet::TShape& val) const {
729  std::hash<int> hash_int;
730  size_t res = hash_int(val.ndim());
731  for (int i = 0; i < val.ndim(); ++i) {
732  res = dmlc::HashCombine(res, val[i]);
733  }
734  return res;
735  }
736 };
737 } // namespace std
738 
739 namespace dmlc {
741 DMLC_DECLARE_TYPE_NAME(optional<mxnet::TShape>, "Shape or None");
742 DMLC_DECLARE_TYPE_NAME(optional<mxnet::Tuple<int>>, "Shape or None");
743 // avoid low version of MSVC
744 #if !defined(_MSC_VER)
745 template<typename T>
746 struct type_name_helper<mxnet::Tuple<T> > {
747  static inline std::string value() {
748  return "tuple of <" + type_name<T>() + ">";
749  }
750 };
751 #endif
752 } // namespace dmlc
753 
754 namespace mxnet {
768 using ShapeVector = std::vector<mxnet::TShape>;
769 
780 using FInferShape = nnvm::FInferNodeEntryAttr<mxnet::TShape>;
781 
782 } // namespace mxnet
783 
784 #endif // MXNET_TUPLE_H_
DMLC_DECLARE_TYPE_NAME(optional< mxnet::Tuple< int >>,"Shape or None")
Tuple< ValueType > & operator=(const Tuple< ValueType > &src)
assignment from another tuple.
Definition: tuple.h:134
bool operator==(const Tuple< ValueType > &s) const
Definition: tuple.h:164
size_t operator()(const mxnet::TShape &val) const
hash a TShape into unsigned int
Definition: tuple.h:728
Tuple< ValueType > & operator=(Tuple< ValueType > &&src)
assignment from rvalue of another tuple.
Definition: tuple.h:147
dim_t * data()
Definition: tuple.h:509
TShape(const Tuple< dim_t > &s)
copy constructor of TShape
Definition: tuple.h:416
ValueType data_stack_[kStackCache]
in stack space used to store shape when it is small
Definition: tuple.h:349
namespace of mxnet
Definition: base.h:89
TShape & operator=(Tuple< dim_t > &&src)
move assignment function from tshape
Definition: tuple.h:471
Tuple(std::initializer_list< ValueType > init)
constructor from initializer list
Definition: tuple.h:77
size_t operator()(const mxnet::Tuple< T > &val) const
hash a Tuple into unsigned int
Definition: tuple.h:714
TShape()
default constructor
Definition: tuple.h:398
Definition: tuple.h:709
DstIter ShapeTypeCast(const SrcIter begin, const SrcIter end, DstIter dst_begin)
helper function to cast type of container elements
Definition: tuple.h:658
Tuple(Tuple< ValueType > &&src)
move constructor from Tuple
Definition: tuple.h:92
void Load(dmlc::JSONReader *reader)
Load Tuple from JSON.
Definition: tuple.h:226
const dim_t * data() const
Definition: tuple.h:505
void assign(RandomAccessIterator begin, RandomAccessIterator end)
Assign content to tuple from iterator.
Definition: tuple.h:113
ValueType * end()
Definition: tuple.h:189
TShape(RandomAccessIterator begin, RandomAccessIterator end)
construct the Tuple from content of iterator. This function is enforced with template arguments of ra...
Definition: tuple.h:449
ValueType & operator[](int i)
get corresponding index
Definition: tuple.h:201
const ValueType & operator[](int i) const
get corresponding index
Definition: tuple.h:210
std::vector< mxnet::TShape > ShapeVector
The result holder of shape of each NodeEntry in the graph.
Definition: tuple.h:768
size_t Size() const
Definition: tuple.h:476
Tuple(const Tuple< ValueType > &s)
copy constructor from another tuple
Definition: tuple.h:66
~Tuple()
destructor
Definition: tuple.h:59
Tuple(std::vector< ValueType > init)
constructor from vector
Definition: tuple.h:84
Definition: ndarray.h:1488
Tuple(RandomAccessIterator begin, RandomAccessIterator end)
construct the Tuple from content of iterator
Definition: tuple.h:102
bool dim_size_is_known(const dim_t dim_size)
Definition: tuple.h:377
Tuple()=default
default constructor
int num_heap_allocated_
number of cells allocated in data_heap_
Definition: tuple.h:347
static std::string value()
Definition: tuple.h:747
static const int kStackCache
Definition: tuple.h:343
const ValueType * end() const
Definition: tuple.h:185
void SetDim(int ndim)
Definition: tuple.h:353
void swap(Tuple< ValueType > &other)
Swap current object with other.
Definition: tuple.h:123
TShape(Tuple< dim_t > &&s)
move constructor.
Definition: tuple.h:434
A dynamic sized array data structure that is optimized for storing small number of elements with same...
Definition: tuple.h:54
TShape(std::initializer_list< dim_t > init)
constructor from initializer list
Definition: tuple.h:427
const ValueType * begin() const
Definition: tuple.h:177
int64_t dim_t
data type to store dim size
Definition: c_api.h:62
int ndim_
number of dimension of the tuple
Definition: tuple.h:345
A Shape class that is used to represent shape of each tensor.
Definition: tuple.h:395
nnvm::FInferNodeEntryAttr< mxnet::TShape > FInferShape
Shape inference function. Update the shapes given the input shape information. TShape.ndim() == -1 means the shape is still unknown.
Definition: tuple.h:780
TShape & operator=(const Tuple< dim_t > &src)
assignment function from tshape
Definition: tuple.h:458
TShape(const int ndim, const dim_t value)
Definition: tuple.h:406
size_t ProdShape(int dimstart, int dimend) const
Definition: tuple.h:491
int ndim() const
Definition: tuple.h:193
Tuple< ValueType > & operator=(std::initializer_list< ValueType > init)
assignment from initializer list
Definition: tuple.h:156
bool operator!=(const Tuple< ValueType > &s) const
Definition: tuple.h:173
bool shape_is_known(const TShape &x)
Definition: tuple.h:648
bool ndim_is_known(const int ndim)
Definition: tuple.h:371
ValueType * data_heap_
space to store shape when dimension is big
Definition: tuple.h:351
ValueType * begin()
Definition: tuple.h:181
friend std::istream & operator>>(std::istream &is, Tuple< ValueType > &t)
read tuple from the istream
Definition: tuple.h:261
void Save(dmlc::JSONWriter *writer) const
Save Tuple to JSON.
Definition: tuple.h:218