mxnet
utils.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 
25 #ifndef MXNET_COMMON_UTILS_H_
26 #define MXNET_COMMON_UTILS_H_
27 
28 #include <dmlc/logging.h>
29 #include <dmlc/omp.h>
30 #include <nnvm/graph.h>
31 #include <nnvm/node.h>
32 #include <mxnet/engine.h>
33 #include <mxnet/ndarray.h>
34 #include <mxnet/op_attr_types.h>
35 #include <mxnet/graph_attr_types.h>
36 #include <nnvm/graph_attr_types.h>
37 
38 #include <memory>
39 #include <vector>
40 #include <type_traits>
41 #include <utility>
42 #include <random>
43 #include <string>
44 #include <thread>
45 #include <algorithm>
46 #include <functional>
47 #include <limits>
48 
49 #include "../operator/mxnet_op.h"
50 #if MXNET_USE_MKLDNN == 1
51 #include "../operator/nn/mkldnn/mkldnn_base-inl.h"
52 #endif
53 
54 #if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__)
55 #include <windows.h>
56 #else
57 #include <unistd.h>
58 #endif
59 
60 
61 namespace mxnet {
62 namespace common {
63 
64 #if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__)
65 inline size_t current_process_id() { return ::GetCurrentProcessId(); }
66 #else
67 inline size_t current_process_id() { return getpid(); }
68 #endif
69 
74  template<typename DType, typename IType>
75  MSHADOW_XINLINE static void Map(int i, DType* out, const IType* indptr,
76  const nnvm::dim_t end, const nnvm::dim_t idx_size) {
77  if (indptr[i+1] < 0 || indptr[i+1] < indptr[i] ||
78  (i == 0 && indptr[i] != 0) ||
79  (i == end - 1 && indptr[end] != idx_size))
80  *out = kCSRIndPtrErr;
81  }
82 };
83 
88 struct csr_idx_check {
89  template<typename DType, typename IType, typename RType>
90  MSHADOW_XINLINE static void Map(int i, DType* out, const IType* idx,
91  const RType* indptr, const nnvm::dim_t ncols) {
92  for (RType j = indptr[i]; j < indptr[i+1]; j++) {
93  if (idx[j] >= ncols || idx[j] < 0 ||
94  (j < indptr[i+1] - 1 && idx[j] >= idx[j+1])) {
95  *out = kCSRIdxErr;
96  break;
97  }
98  }
99  }
100 };
101 
107  template<typename DType, typename IType>
108  MSHADOW_XINLINE static void Map(int i, DType* out, const IType* idx,
109  const nnvm::dim_t end, const nnvm::dim_t nrows) {
110  if ((i < end && idx[i+1] <= idx[i])
111  || idx[i] < 0 || idx[i] >= nrows)
112  *out = kRSPIdxErr;
113  }
114 };
115 
116 template<typename xpu>
117 void CheckFormatWrapper(const RunContext &rctx, const NDArray &input,
118  const TBlob &err_cpu, const bool full_check);
119 
128 template<typename xpu>
129 void CheckFormatCSRImpl(const RunContext &rctx, const NDArray &input,
130  const TBlob &err_cpu, const bool full_check) {
131  using namespace op::mxnet_op;
132  CHECK_EQ(input.storage_type(), kCSRStorage)
133  << "CheckFormatCSRImpl is for CSRNDArray";
134  const mxnet::TShape shape = input.shape();
135  const mxnet::TShape idx_shape = input.aux_shape(csr::kIdx);
136  const mxnet::TShape indptr_shape = input.aux_shape(csr::kIndPtr);
137  const mxnet::TShape storage_shape = input.storage_shape();
138  if ((shape.ndim() != 2) ||
139  (idx_shape.ndim() != 1 || indptr_shape.ndim() != 1 || storage_shape.ndim() != 1) ||
140  (indptr_shape[0] != shape[0] + 1) ||
141  (idx_shape[0] != storage_shape[0])) {
142  MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, {
143  DType* err = err_cpu.dptr<DType>();
144  *err = kCSRShapeErr;
145  });
146  return;
147  }
148  if (full_check) {
149  MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, {
150  MSHADOW_IDX_TYPE_SWITCH(input.aux_type(csr::kIndPtr), RType, {
151  MSHADOW_IDX_TYPE_SWITCH(input.aux_type(csr::kIdx), IType, {
152  mshadow::Stream<xpu> *s = rctx.get_stream<xpu>();
153  NDArray ret_xpu = NDArray(mshadow::Shape1(1),
154  rctx.get_ctx(), false, err_cpu.type_flag_);
155  TBlob val_xpu = ret_xpu.data();
156  Kernel<set_to_int<kNormalErr>, xpu>::Launch(s, val_xpu.Size(), val_xpu.dptr<DType>());
157  Kernel<csr_indptr_check, xpu>::Launch(s, indptr_shape[0] - 1, val_xpu.dptr<DType>(),
158  input.aux_data(csr::kIndPtr).dptr<RType>(),
159  indptr_shape[0] - 1, idx_shape[0]);
160  // no need to check indices if indices are empty
161  if (idx_shape[0] != 0) {
162  Kernel<csr_idx_check, xpu>::Launch(s, indptr_shape[0] - 1, val_xpu.dptr<DType>(),
163  input.aux_data(csr::kIdx).dptr<IType>(),
164  input.aux_data(csr::kIndPtr).dptr<RType>(), shape[1]);
165  }
166  mshadow::Copy(err_cpu.get<cpu, 1, DType>(),
167  val_xpu.get<xpu, 1, DType>(s), s);
168  });
169  });
170  });
171  }
172 }
173 
182 template<typename xpu>
183 void CheckFormatRSPImpl(const RunContext &rctx, const NDArray &input,
184  const TBlob &err_cpu, const bool full_check) {
185  using namespace op::mxnet_op;
186  CHECK_EQ(input.storage_type(), kRowSparseStorage)
187  << "CheckFormatRSPImpl is for RSPNDArray";
188  const mxnet::TShape idx_shape = input.aux_shape(rowsparse::kIdx);
189  if (idx_shape[0] != input.storage_shape()[0]) {
190  MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, {
191  DType* err = err_cpu.dptr<DType>();
192  *err = kRSPShapeErr;
193  });
194  return;
195  }
196  if (idx_shape[0] == 0) {
197  return;
198  }
199  if (full_check) {
200  MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, {
201  MSHADOW_IDX_TYPE_SWITCH(input.aux_type(rowsparse::kIdx), IType, {
202  mshadow::Stream<xpu> *s = rctx.get_stream<xpu>();
203  NDArray ret_xpu = NDArray(mshadow::Shape1(1),
204  rctx.get_ctx(), false, err_cpu.type_flag_);
205  TBlob val_xpu = ret_xpu.data();
206  Kernel<set_to_int<kNormalErr>, xpu>::Launch(s, val_xpu.Size(), val_xpu.dptr<DType>());
207 
208  Kernel<rsp_idx_check, xpu>::Launch(s, idx_shape[0],
209  val_xpu.dptr<DType>(), input.aux_data(rowsparse::kIdx).dptr<IType>(),
210  idx_shape[0] - 1, input.shape()[0]);
211  mshadow::Copy(err_cpu.get<cpu, 1, DType>(),
212  val_xpu.get<xpu, 1, DType>(s), s);
213  });
214  });
215  }
216 }
217 
218 template<typename xpu>
219 void CheckFormatImpl(const RunContext &rctx, const NDArray &input,
220  const TBlob &err_cpu, const bool full_check) {
221  int stype = input.storage_type();
222  if (stype == kCSRStorage) {
223  CheckFormatCSRImpl<xpu>(rctx, input, err_cpu, full_check);
224  } else if (stype == kRowSparseStorage) {
225  CheckFormatRSPImpl<xpu>(rctx, input, err_cpu, full_check);
226  } else if (stype == kDefaultStorage) {
227  // no-op for default storage
228  } else {
229  LOG(FATAL) << "Unknown storage type " << stype;
230  }
231 }
232 
236 template<typename xpu>
238  const NDArray& input_nd,
239  const TBlob& idx_data,
240  const OpReqType req,
241  NDArray* output_nd);
242 
243 /* \brief Casts tensor storage type to the new type.
244  */
245 template<typename xpu>
246 void CastStorageDispatch(const OpContext& ctx, const NDArray& input, const NDArray& output);
247 
251 inline bool ContainsOnlyStorage(const StorageTypeVector& vstorage,
252  const NDArrayStorageType stype) {
253  if (!vstorage.empty()) {
254  for (const auto& i : vstorage) {
255  if (i != stype) return false;
256  }
257  return true;
258  }
259  return false;
260 }
261 
266 inline bool ContainsOnlyStorage(const StorageTypeVector& vstorage,
267  const NDArrayStorageType stype1,
268  const NDArrayStorageType stype2,
269  bool *has_both) {
270  if (has_both) {
271  *has_both = false;
272  }
273  if (!vstorage.empty()) {
274  uint8_t has = 0;
275  for (const auto i : vstorage) {
276  if (i == stype1) {
277  has |= 1;
278  } else if (i == stype2) {
279  has |= 2;
280  } else {
281  return false;
282  }
283  }
284  if (has_both) {
285  *has_both = has == 3;
286  }
287  return true;
288  }
289  return false;
290 }
291 
295 inline bool ContainsOnlyStorage(const std::vector<NDArray>& ndarrays,
296  const NDArrayStorageType stype) {
297  if (!ndarrays.empty()) {
298  for (const auto& nd : ndarrays) {
299  if (nd.storage_type() != stype) {
300  return false;
301  }
302  }
303  return true;
304  }
305  return false;
306 }
307 
311 inline bool ContainsOnlyStorage(const std::vector<NDArray>& ndarrays,
312  const NDArrayStorageType stype1,
313  const NDArrayStorageType stype2,
314  bool *has_both) {
315  if (has_both) {
316  *has_both = false;
317  }
318  if (!ndarrays.empty()) {
319  uint8_t has = 0;
320  for (const auto& nd : ndarrays) {
321  const NDArrayStorageType stype = nd.storage_type();
322  if (stype == stype1) {
323  has |= 1;
324  } else if (stype == stype2) {
325  has |= 2;
326  } else {
327  return false;
328  }
329  }
330  if (has_both) {
331  *has_both = has == 3;
332  }
333  return true;
334  }
335  return false;
336 }
337 
341 inline bool ContainsStorageType(const std::vector<NDArray>& ndarrays,
342  const NDArrayStorageType stype) {
343  if (!ndarrays.empty()) {
344  for (const auto& nd : ndarrays) {
345  if (nd.storage_type() == stype) {
346  return true;
347  }
348  }
349  }
350  return false;
351 }
352 
356 inline bool ContainsStorageType(const std::vector<int>& ndstypes,
357  const NDArrayStorageType stype) {
358  if (!ndstypes.empty()) {
359  for (const auto& ndstype : ndstypes) {
360  if (ndstype == stype) {
361  return true;
362  }
363  }
364  }
365  return false;
366 }
367 
368 inline std::string dtype_string(const int dtype) {
369  switch (dtype) {
370  case mshadow::kFloat32:
371  return "float";
372  case mshadow::kFloat64:
373  return "double";
374  case mshadow::kFloat16:
375  return "half";
376  case mshadow::kUint8:
377  return "unsigned char";
378  case mshadow::kInt8:
379  return "char";
380  case mshadow::kInt32:
381  return "int";
382  case mshadow::kInt64:
383  return "long long";
384  case mshadow::kBool:
385  return "bool";
386  default:
387  LOG(FATAL) << "Unknown type enum " << dtype;
388  }
389  return "unknown";
390 }
391 
393 inline std::string dispatch_mode_string(const DispatchMode x) {
394  switch (x) {
396  return "fcompute";
398  return "fcompute_ex";
400  return "fcompute_fallback";
402  return "variable";
404  return "undefined";
405  }
406  return "unknown";
407 }
408 
409 
411 inline std::string stype_string(const int x) {
412  switch (x) {
413  case kDefaultStorage:
414  return "default";
415  case kCSRStorage:
416  return "csr";
417  case kRowSparseStorage:
418  return "row_sparse";
419  }
420  return "unknown";
421 }
422 
424 inline std::string dev_type_string(const int dev_type) {
425  switch (dev_type) {
426  case Context::kCPU:
427  return "cpu";
428  case Context::kGPU:
429  return "gpu";
430  case Context::kCPUPinned:
431  return "cpu_pinned";
432  case Context::kCPUShared:
433  return "cpu_shared";
434  }
435  return "unknown";
436 }
437 
439 inline std::string operator_stype_string(const nnvm::NodeAttrs& attrs,
440  const int dev_mask,
441  const std::vector<int>& in_attrs,
442  const std::vector<int>& out_attrs) {
443  std::ostringstream os;
444  os << "operator = " << attrs.op->name
445  << "\ninput storage types = [";
446  for (const int attr : in_attrs) {
447  os << stype_string(attr) << ", ";
448  }
449  os << "]\n"
450  << "output storage types = [";
451  for (const int attr : out_attrs) {
452  os << stype_string(attr) << ", ";
453  }
454  os << "]\n"
455  << "params = {";
456  for (auto kv : attrs.dict) {
457  os << "\"" << kv.first << "\" : " << kv.second << ", ";
458  }
459  os << "}\n"
460  << "context.dev_mask = " << dev_type_string(dev_mask);
461  return os.str();
462 }
463 
465 inline std::string operator_string(const nnvm::NodeAttrs& attrs,
466  const OpContext& ctx,
467  const std::vector<NDArray>& inputs,
468  const std::vector<OpReqType>& req,
469  const std::vector<NDArray>& outputs) {
470  std::string result = "";
471  std::vector<int> in_stypes;
472  std::vector<int> out_stypes;
473  in_stypes.reserve(inputs.size());
474  out_stypes.reserve(outputs.size());
475  auto xform = [](const NDArray arr) -> int { return arr.storage_type(); };
476  std::transform(inputs.begin(), inputs.end(), std::back_inserter(in_stypes), xform);
477  std::transform(outputs.begin(), outputs.end(), std::back_inserter(out_stypes), xform);
478  result += operator_stype_string(attrs, ctx.run_ctx.ctx.dev_mask(), in_stypes, out_stypes);
479  return result;
480 }
481 
483 inline void LogOnce(const std::string& message) {
485  auto log_store = LogStore::Get();
486  if (log_store->find(message) == log_store->end()) {
487  LOG(INFO) << message;
488  log_store->insert(message);
489  }
490 }
491 
494 inline void LogStorageFallback(const nnvm::NodeAttrs& attrs,
495  const int dev_mask,
496  const std::vector<int>* in_attrs,
497  const std::vector<int>* out_attrs) {
498  static bool log = dmlc::GetEnv("MXNET_STORAGE_FALLBACK_LOG_VERBOSE", true);
499  if (!log) return;
500  const std::string op_str = operator_stype_string(attrs, dev_mask, *in_attrs, *out_attrs);
501  std::ostringstream os;
502  const char* warning = "\nThe operator with default storage type will be dispatched "
503  "for execution. You're seeing this warning message because the operator above is unable "
504  "to process the given ndarrays with specified storage types, context and parameter. "
505  "Temporary dense ndarrays are generated in order to execute the operator. "
506  "This does not affect the correctness of the programme. "
507  "You can set environment variable MXNET_STORAGE_FALLBACK_LOG_VERBOSE to "
508  "0 to suppress this warning.";
509  os << "\nStorage type fallback detected:\n" << op_str << warning;
510  LogOnce(os.str());
511 #if MXNET_USE_MKLDNN == 1
512  if (!MKLDNNEnvSet()) common::LogOnce("MXNET_MKLDNN_ENABLED flag is off. "
513  "You can re-enable by setting MXNET_MKLDNN_ENABLED=1");
514  if (GetMKLDNNCacheSize() != -1) common::LogOnce("MXNET_MKLDNN_CACHE_NUM is set."
515  "Should only be set if "
516  "your model has variable input shapes, "
517  "as cache size may grow unbounded");
518 #endif
519 }
520 
521 // heuristic to dermine number of threads per GPU
522 inline int GetNumThreadsPerGPU() {
523  // This is resource efficient option.
524  return dmlc::GetEnv("MXNET_GPU_WORKER_NTHREADS", 2);
525 }
526 
527 // heuristic to get number of matching colors.
528 // this decides how much parallelism we can get in each GPU.
529 inline int GetExecNumMatchColor() {
530  // This is resource efficient option.
531  int num_match_color = dmlc::GetEnv("MXNET_EXEC_NUM_TEMP", 1);
532  return std::min(num_match_color, GetNumThreadsPerGPU());
533 }
534 
535 template<typename T, typename V>
536 V ParallelAccumulate(const T* a, const int n, V start) {
537  V sum = start;
538 #pragma omp parallel for reduction(+:sum)
539  for (int i = 0; i < n; ++i) {
540  sum += a[i];
541  }
542  return sum;
543 }
544 
552 template<typename RandomIt, typename Compare>
553 void ParallelSortHelper(RandomIt first, size_t len,
554  size_t grainsize, const Compare& comp) {
555  if (len < grainsize) {
556  std::sort(first, first+len, comp);
557  } else {
558  std::thread thr(ParallelSortHelper<RandomIt, Compare>, first, len/2, grainsize, comp);
559  ParallelSortHelper(first+len/2, len - len/2, grainsize, comp);
560  thr.join();
561  std::inplace_merge(first, first+len/2, first+len, comp);
562  }
563 }
564 
574 template<typename RandomIt, typename Compare>
575 void ParallelSort(RandomIt first, RandomIt last, size_t num_threads, Compare comp) {
576  const auto num = std::distance(first, last);
577  size_t grainsize = std::max(num / num_threads + 5, static_cast<size_t>(1024*16));
578  ParallelSortHelper(first, num, grainsize, comp);
579 }
580 
590 template<typename RandomIt>
591 void ParallelSort(RandomIt first, RandomIt last, size_t num_threads) {
592  ParallelSort(first, last, num_threads,
593  std::less<typename std::iterator_traits<RandomIt>::value_type>());
594 }
595 
599 typedef std::mt19937 RANDOM_ENGINE;
600 
604 namespace helper {
605 
609 template <class T>
610 struct UniqueIf {
614  using SingleObject = std::unique_ptr<T>;
615 };
616 
620 template <class T>
621 struct UniqueIf<T[]> {
625  using UnknownBound = std::unique_ptr<T[]>;
626 };
627 
631 template <class T, size_t kSize>
632 struct UniqueIf<T[kSize]> {
636  using KnownBound = void;
637 };
638 
639 } // namespace helper
640 
652 template <class T, class... Args>
654  return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
655 }
656 
666 template <class T>
668  using U = typename std::remove_extent<T>::type;
669  return std::unique_ptr<T>(new U[n]{});
670 }
671 
680 template <class T, class... Args>
681 typename helper::UniqueIf<T>::KnownBound MakeUnique(Args&&... args) = delete;
682 
683 template<typename FCompType>
684 FCompType GetFCompute(const nnvm::Op* op, const std::string& name,
685  const Context& ctx) {
686  static auto& fcompute_cpu = nnvm::Op::GetAttr<FCompType>(name + "<cpu>");
687  static auto& fcompute_gpu = nnvm::Op::GetAttr<FCompType>(name + "<gpu>");
688 
689  if (ctx.dev_mask() == cpu::kDevMask) {
690  return fcompute_cpu.get(op, nullptr);
691  } else if (ctx.dev_mask() == gpu::kDevMask) {
692  return fcompute_gpu.get(op, nullptr);
693  } else {
694  LOG(FATAL) << "Unknown device mask " << ctx.dev_mask();
695  return nullptr;
696  }
697 }
698 
702 template <typename T>
703 constexpr size_t MaxIntegerValue() {
704  return std::is_integral<T>::value ?
705  std::numeric_limits<T>::max():
706  size_t(2) << (std::numeric_limits<T>::digits - 1);
707 }
708 
709 template <>
710 constexpr size_t MaxIntegerValue<mshadow::half::half_t>() {
711  return size_t(2) << 10;
712 }
713 
714 MSHADOW_XINLINE int ilog2ul(size_t a) {
715  int k = 1;
716  while (a >>= 1) ++k;
717  return k;
718 }
719 
720 MSHADOW_XINLINE int ilog2ui(unsigned int a) {
721  int k = 1;
722  while (a >>= 1) ++k;
723  return k;
724 }
725 
729 inline NDArray InitZeros(const NDArrayStorageType stype, const mxnet::TShape &shape,
730  const Context &ctx, const int dtype) {
731  // NDArray with default storage
732  if (stype == kDefaultStorage) {
733  NDArray ret(shape, ctx, false, dtype);
734  ret = 0;
735  return ret;
736  }
737  // NDArray with non-default storage. Storage allocation is always delayed.
738  return NDArray(stype, shape, ctx, true, dtype);
739 }
740 
744 inline void EmplaceBackZeros(const NDArrayStorageType stype, const mxnet::TShape &shape,
745  const Context &ctx, const int dtype,
746  std::vector<NDArray> *vec) {
747  // NDArray with default storage
748  if (stype == kDefaultStorage) {
749  vec->emplace_back(shape, ctx, false, dtype);
750  vec->back() = 0;
751  } else {
752  // NDArray with non-default storage. Storage allocation is always delayed.
753  vec->emplace_back(stype, shape, ctx, true, dtype);
754  }
755 }
756 
757 
761 template<typename DType>
762 inline void ParallelCopy(DType* dst, const DType* src, index_t size) {
763  static index_t copy_block_size = dmlc::GetEnv("MXNET_CPU_PARALLEL_SIZE", 200000);
764  if (size >= copy_block_size) {
765  #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount())
766  for (index_t i = 0; i < size; ++i) {
767  dst[i] = src[i];
768  }
769  } else {
770  std::memcpy(dst, src, sizeof(DType) * size);
771  }
772 }
773 
777 template<typename DType>
778 inline void ParallelAdd(DType* dst, const DType* src, index_t size) {
779  static index_t add_block_size = dmlc::GetEnv("MXNET_CPU_PARALLEL_SIZE", 200000);
780  if (size >= add_block_size) {
781  #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount())
782  for (index_t i = 0; i < size; ++i) {
783  dst[i] += src[i];
784  }
785  } else {
786  for (index_t i = 0; i < size; ++i) {
787  dst[i] += src[i];
788  }
789  }
790 }
791 
810 inline void ConvertToNumpyShape(mxnet::TShape* shape) {
811  if (shape->ndim() == 0) { // legacy shape ndim = 0 means unknown
812  *shape = mxnet::TShape(); // unknown shape ndim = -1
813  } else {
814  for (int j = 0; j < shape->ndim(); ++j) {
815  if ((*shape)[j] == 0) { // legacy shape dim_size = 0 means unknown
816  (*shape)[j] = -1; // unknown dim size = -1
817  }
818  }
819  }
820 }
821 
823  for (size_t i = 0; i < shapes->size(); ++i) {
824  ConvertToNumpyShape(&(shapes->at(i)));
825  }
826 }
827 
832 inline void ConvertToLegacyShape(mxnet::TShape* shape) {
833  if (!mxnet::ndim_is_known(*shape)) {
834  *shape = mxnet::TShape(0, -1);
835  } else {
836  for (int j = 0; j < shape->ndim(); ++j) {
837  if (!mxnet::dim_size_is_known(*shape, j)) {
838  (*shape)[j] = 0;
839  }
840  }
841  }
842 }
843 
845  for (size_t i = 0; i < shapes->size(); ++i) {
846  ConvertToLegacyShape(&(shapes->at(i)));
847  }
848 }
850  const nnvm::IndexedGraph &idx, const std::vector<NDArray *> &state_arrays,
851  size_t nid, const std::function<void(const char *, const char *, void *)>
852  &monitor_callback);
853 
855  const nnvm::IndexedGraph &idx, const std::vector<NDArray *> &state_arrays,
856  size_t nid, const std::function<void(const char *, const char *, void *)>
857  &monitor_callback);
858 
862 static inline std::string GetOutputName(const nnvm::NodeEntry& e) {
863  nnvm::Symbol sym;
864  sym.outputs.push_back(e);
865  return sym.ListOutputNames()[0];
866 }
867 
869  // convert negative axes to positive values
870  const int ndim = src.ndim();
871  mxnet::TShape axes = src;
872  for (int i = 0; i < ndim; ++i) {
873  if (axes[i] < 0) {
874  axes[i] += ndim;
875  }
876  CHECK(axes[i] >= 0 && axes[i] < ndim) << "axes[" << i << "]="
877  << axes[i] << " exceeds the range ["
878  << 0 << ", " << ndim << ")";
879  }
880  return axes;
881 }
882 
883 inline bool is_float(const int dtype) {
884  return dtype == mshadow::kFloat32 || dtype == mshadow::kFloat64 || dtype == mshadow::kFloat16;
885 }
886 
887 inline int get_more_precise_type(const int type1, const int type2) {
888  if (type1 == type2) return type1;
889  if (is_float(type1) && is_float(type2)) {
890  if (type1 == mshadow::kFloat64 || type2 == mshadow::kFloat64) {
891  return mshadow::kFloat64;
892  }
893  if (type1 == mshadow::kFloat32 || type2 == mshadow::kFloat32) {
894  return mshadow::kFloat32;
895  }
896  return mshadow::kFloat16;
897  } else if (is_float(type1) || is_float(type2)) {
898  return is_float(type1) ? type1 : type2;
899  }
900  if (type1 == mshadow::kInt64 || type2 == mshadow::kInt64) {
901  return mshadow::kInt64;
902  }
903  if (type1 == mshadow::kInt32 || type2 == mshadow::kInt32) {
904  return mshadow::kInt32;
905  }
906  CHECK(!((type1 == mshadow::kUint8 && type2 == mshadow::kInt8) ||
907  (type1 == mshadow::kInt8 && type2 == mshadow::kUint8)))
908  << "1 is UInt8 and 1 is Int8 should not get here";
909  if (type1 == mshadow::kUint8 || type2 == mshadow::kUint8) {
910  return mshadow::kUint8;
911  }
912  return mshadow::kInt8;
913 }
914 
915 inline int np_binary_out_infer_type(const int type1, const int type2) {
916  if ((type1 == mshadow::kUint8 && type2 == mshadow::kInt8) ||
917  (type1 == mshadow::kInt8 && type2 == mshadow::kUint8)) {
918  return mshadow::kInt32;
919  }
920  return get_more_precise_type(type1, type2);
921 }
922 
923 } // namespace common
924 } // namespace mxnet
925 #endif // MXNET_COMMON_UTILS_H_
Definition: base.h:307
Definition: ndarray.h:74
static MSHADOW_XINLINE void Map(int i, DType *out, const IType *idx, const RType *indptr, const nnvm::dim_t ncols)
Definition: utils.h:90
Definition: ndarray.h:63
NDArrayStorageType
Definition: ndarray.h:61
void CheckFormatCSRImpl(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check)
Check the validity of CSRNDArray.
Definition: utils.h:129
DeviceType dev_mask() const
Get corresponding device mask.
Definition: base.h:120
Definition: ndarray.h:54
NDArrayStorageType storage_type() const
Definition: ndarray.h:322
Graph node data structure.
Engine that schedules all the operations according to dependency.
void CheckFormatImpl(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check)
Definition: utils.h:219
int GetNumThreadsPerGPU()
Definition: utils.h:522
const mxnet::TShape & shape() const
Definition: ndarray.h:222
void SparseRetainOpForwardRspWrapper(mshadow::Stream< xpu > *s, const NDArray &input_nd, const TBlob &idx_data, const OpReqType req, NDArray *output_nd)
Pick rows specified by user input index array from a row sparse ndarray and save them in the output s...
The attributes of the current operation node. Usually are additional parameters like axis...
Definition: node.h:120
std::vector< NodeEntry > outputs
output entries contained in the symbol
Definition: symbolic.h:74
void ExecuteMonOutputCallback(const nnvm::IndexedGraph &idx, const std::vector< NDArray * > &state_arrays, size_t nid, const std::function< void(const char *, const char *, void *)> &monitor_callback)
std::string operator_stype_string(const nnvm::NodeAttrs &attrs, const int dev_mask, const std::vector< int > &in_attrs, const std::vector< int > &out_attrs)
get string representation of the operator stypes
Definition: utils.h:439
namespace of mxnet
Definition: base.h:89
void KnownBound
Type of T.
Definition: utils.h:636
void ParallelSortHelper(RandomIt first, size_t len, size_t grainsize, const Compare &comp)
Helper function for ParallelSort. DO NOT call this function directly. Use the interface ParallelSort ...
Definition: utils.h:553
int64_t dim_t
data type to store dim size
Definition: tuple.h:39
int type_flag_
type flag of the tensor blob
Definition: tensor_blob.h:74
FCompType GetFCompute(const nnvm::Op *op, const std::string &name, const Context &ctx)
Definition: utils.h:684
V ParallelAccumulate(const T *a, const int n, V start)
Definition: utils.h:536
void LogOnce(const std::string &message)
log message once. Intended for storage fallback warning messages.
Definition: utils.h:483
Context ctx
base Context
Definition: base.h:352
A threadlocal store to store threadlocal variables. Will return a thread local singleton of type T...
Definition: thread_local.h:35
Definition: ndarray.h:72
execution time context. The information needed in runtime for actual execution.
Definition: base.h:350
DispatchMode
the dispatch mode of the operator
Definition: op_attr_types.h:122
std::string stype_string(const int x)
get string representation of storage_type
Definition: utils.h:411
Definition: ndarray.h:65
Data structures that can appear in graph attributes.
void CastStorageDispatch(const OpContext &ctx, const NDArray &input, const NDArray &output)
void CheckFormatWrapper(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check)
Definition: base.h:105
void ParallelSort(RandomIt first, RandomIt last, size_t num_threads, Compare comp)
Sort the elements in the range [first, last) into the ascending order defined by the comparator comp...
Definition: utils.h:575
All the possible information needed by Operator.Forward and Backward This is the superset of RunConte...
Definition: op_attr_types.h:66
bool ContainsOnlyStorage(const StorageTypeVector &vstorage, const NDArrayStorageType stype)
returns true if all storage types in vstorage are the same as target stype. false is returned for emp...
Definition: utils.h:251
std::string operator_string(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector< NDArray > &inputs, const std::vector< OpReqType > &req, const std::vector< NDArray > &outputs)
get string representation of the operator
Definition: utils.h:465
static const int kDevMask
device flag number, identifies this device
Definition: tensor.h:32
std::vector< std::string > ListOutputNames() const
List the names of outputs for this symbol.
std::mt19937 RANDOM_ENGINE
Random Engine.
Definition: utils.h:599
#define MSHADOW_XINLINE
Definition: base.h:204
std::vector< mxnet::TShape > ShapeVector
The result holder of shape of each NodeEntry in the graph.
Definition: tuple.h:793
Indices of RSPNDArray should be non-negative, less than the size of first dimension and in ascending ...
Definition: utils.h:106
const Op * op
The operator this node uses. For place holder variable, op == nullptr.
Definition: node.h:125
Definition: ndarray.h:58
Definition: base.h:107
Auxiliary data structure to index a graph. It maps Nodes in the graph to consecutive integers node_id...
Definition: graph.h:108
std::string dispatch_mode_string(const DispatchMode x)
get string representation of dispatch_mode
Definition: utils.h:393
std::string dev_type_string(const int dev_type)
get string representation of device type
Definition: utils.h:424
Definition: base.h:312
Helper for non-array type T.
Definition: utils.h:610
bool dim_size_is_known(const dim_t dim_size)
Definition: tuple.h:395
Definition: base.h:106
Definition: ndarray.h:54
const mxnet::TShape & storage_shape() const
Definition: ndarray.h:230
void ParallelAdd(DType *dst, const DType *src, index_t size)
Definition: utils.h:778
void ExecuteMonInputCallback(const nnvm::IndexedGraph &idx, const std::vector< NDArray * > &state_arrays, size_t nid, const std::function< void(const char *, const char *, void *)> &monitor_callback)
Definition: base.h:314
Definition: base.h:308
std::string name
name of the operator
Definition: op.h:107
Definition: ndarray.h:64
an entry that represents output data from a node
Definition: node.h:52
int np_binary_out_infer_type(const int type1, const int type2)
Definition: utils.h:915
std::string dtype_string(const int dtype)
Definition: utils.h:368
const mxnet::TShape & aux_shape(size_t index) const
get the shape of aux_data(index)
Definition: ndarray.h:242
IndPtr should be non-negative, in non-decreasing order, start with 0 and end with value equal with si...
Definition: utils.h:73
Definition: ndarray.h:71
std::unique_ptr< T[]> UnknownBound
Type of T.
Definition: utils.h:625
Definition: base.h:311
Configuation of nnvm as well as basic data structure.
OpReqType
operation request type to Forward and Backward
Definition: op_attr_types.h:45
static const int kDevMask
device flag number, identifies this device
Definition: tensor.h:25
bool ContainsStorageType(const std::vector< NDArray > &ndarrays, const NDArrayStorageType stype)
returns true if storage type of any array in ndarrays is the same as the target stype. false is returned for empty inputs.
Definition: utils.h:341
constexpr size_t MaxIntegerValue()
Return the max integer value representable in the type T without loss of precision.
Definition: utils.h:703
RunContext run_ctx
RunContext related resources.
Definition: op_attr_types.h:72
std::unordered_map< std::string, std::string > dict
The dictionary representation of attributes.
Definition: node.h:129
size_t current_process_id()
Definition: utils.h:67
std::unique_ptr< T > SingleObject
Type of T.
Definition: utils.h:614
Definition: base.h:310
A Shape class that is used to represent shape of each tensor.
Definition: tuple.h:413
void CheckFormatRSPImpl(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check)
Check the validity of RowSparseNDArray.
Definition: utils.h:183
int GetExecNumMatchColor()
Definition: utils.h:529
header to handle OpenMP compatibility issues
int ndim() const
Definition: tuple.h:193
#define MSHADOW_TYPE_SWITCH(type, DType,...)
Definition: base.h:991
Definition: base.h:108
static MSHADOW_XINLINE void Map(int i, DType *out, const IType *idx, const nnvm::dim_t end, const nnvm::dim_t nrows)
Definition: utils.h:108
mxnet::TShape CanonicalizeAxes(const mxnet::TShape &src)
Definition: utils.h:868
bool ndim_is_known(const int ndim)
Definition: tuple.h:389
int get_more_precise_type(const int type1, const int type2)
Definition: utils.h:887
mshadow::index_t index_t
index type usually use unsigned
Definition: base.h:95
MSHADOW_XINLINE int ilog2ul(size_t a)
Definition: utils.h:714
Definition: base.h:309
void LogStorageFallback(const nnvm::NodeAttrs &attrs, const int dev_mask, const std::vector< int > *in_attrs, const std::vector< int > *out_attrs)
log storage fallback event
Definition: utils.h:494
Definition: base.h:313
helper::UniqueIf< T >::SingleObject MakeUnique(Args &&...args)
Constructs an object of type T and wraps it in a std::unique_ptr.
Definition: utils.h:653
Context information about the execution environment.
Definition: base.h:102
Indices should be non-negative, less than the number of columns and in ascending order per row...
Definition: utils.h:88
bool is_float(const int dtype)
Definition: utils.h:883
ndarray interface
Definition: ndarray.h:82
void ParallelCopy(DType *dst, const DType *src, index_t size)
parallelize copy by OpenMP.
Definition: utils.h:762
NDArray InitZeros(const NDArrayStorageType stype, const mxnet::TShape &shape, const Context &ctx, const int dtype)
Return an NDArray of all zeros.
Definition: utils.h:729
void EmplaceBackZeros(const NDArrayStorageType stype, const mxnet::TShape &shape, const Context &ctx, const int dtype, std::vector< NDArray > *vec)
Helper to add a NDArray of zeros to a std::vector.
Definition: utils.h:744
MSHADOW_XINLINE int ilog2ui(unsigned int a)
Definition: utils.h:720
static MSHADOW_XINLINE void Map(int i, DType *out, const IType *indptr, const nnvm::dim_t end, const nnvm::dim_t idx_size)
Definition: utils.h:75
Symbol is help class used to represent the operator node in Graph.
Definition: symbolic.h:51
void ConvertToLegacyShape(mxnet::TShape *shape)
This is function is used to convert shapes returned by the infer shape functions/pass to the legacy s...
Definition: utils.h:832
std::vector< int > StorageTypeVector
The result holder of storage type of each NodeEntry in the graph.
Definition: graph_attr_types.h:45
Operator structure.
Definition: op.h:104
tensor blob class that can be used to hold tensor of any dimension, any device and any data type...
Definition: tensor_blob.h:66
void ConvertToNumpyShape(mxnet::TShape *shape)
If numpy compatibility is turned off (default), the shapes passed in by users follow the legacy shape...
Definition: utils.h:810
computaion stream structure, used for asynchronous computations
Definition: tensor.h:365