25 #ifndef MXNET_COMMON_UTILS_H_ 26 #define MXNET_COMMON_UTILS_H_ 28 #include <dmlc/logging.h> 41 #include <type_traits> 50 #include "../operator/mxnet_op.h" 51 #if MXNET_USE_MKLDNN == 1 52 #include "../operator/nn/mkldnn/mkldnn_base-inl.h" 55 #if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__) 65 #if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__) 75 template<
typename DType,
typename IType>
78 if (indptr[i+1] < 0 || indptr[i+1] < indptr[i] ||
79 (i == 0 && indptr[i] != 0) ||
80 (i == end - 1 && indptr[end] != idx_size))
90 template<
typename DType,
typename IType,
typename RType>
93 for (RType j = indptr[i]; j < indptr[i+1]; j++) {
94 if (idx[j] >= ncols || idx[j] < 0 ||
95 (j < indptr[i+1] - 1 && idx[j] >= idx[j+1])) {
108 template<
typename DType,
typename IType>
111 if ((i < end && idx[i+1] <= idx[i])
112 || idx[i] < 0 || idx[i] >= nrows)
117 template<
typename xpu>
119 const TBlob &err_cpu,
const bool full_check);
129 template<
typename xpu>
131 const TBlob &err_cpu,
const bool full_check) {
132 using namespace op::mxnet_op;
134 <<
"CheckFormatCSRImpl is for CSRNDArray";
139 if ((shape.ndim() != 2) ||
140 (idx_shape.
ndim() != 1 || indptr_shape.
ndim() != 1 || storage_shape.
ndim() != 1) ||
141 (indptr_shape[0] != shape[0] + 1) ||
142 (idx_shape[0] != storage_shape[0])) {
144 DType* err = err_cpu.dptr<DType>();
151 MSHADOW_IDX_TYPE_SWITCH(input.aux_type(csr::kIndPtr), RType, {
152 MSHADOW_IDX_TYPE_SWITCH(input.aux_type(csr::kIdx), IType, {
153 mshadow::Stream<xpu> *s = rctx.get_stream<xpu>();
154 NDArray ret_xpu = NDArray(mshadow::Shape1(1),
155 rctx.get_ctx(), false, err_cpu.type_flag_);
156 TBlob val_xpu = ret_xpu.data();
157 Kernel<set_to_int<kNormalErr>, xpu>::Launch(s, val_xpu.Size(), val_xpu.dptr<DType>());
158 Kernel<csr_indptr_check, xpu>::Launch(s, indptr_shape[0] - 1, val_xpu.dptr<DType>(),
159 input.aux_data(csr::kIndPtr).dptr<RType>(),
160 indptr_shape[0] - 1, idx_shape[0]);
162 if (idx_shape[0] != 0) {
163 Kernel<csr_idx_check, xpu>::Launch(s, indptr_shape[0] - 1, val_xpu.dptr<DType>(),
164 input.aux_data(csr::kIdx).dptr<IType>(),
165 input.aux_data(csr::kIndPtr).dptr<RType>(), shape[1]);
167 mshadow::Copy(err_cpu.get<cpu, 1, DType>(),
168 val_xpu.get<xpu, 1, DType>(s), s);
183 template<
typename xpu>
185 const TBlob &err_cpu,
const bool full_check) {
186 using namespace op::mxnet_op;
188 <<
"CheckFormatRSPImpl is for RSPNDArray";
192 DType* err = err_cpu.dptr<DType>();
197 if (idx_shape[0] == 0) {
202 MSHADOW_IDX_TYPE_SWITCH(input.aux_type(rowsparse::kIdx), IType, {
203 mshadow::Stream<xpu> *s = rctx.get_stream<xpu>();
204 NDArray ret_xpu = NDArray(mshadow::Shape1(1),
205 rctx.get_ctx(), false, err_cpu.type_flag_);
206 TBlob val_xpu = ret_xpu.data();
207 Kernel<set_to_int<kNormalErr>, xpu>::Launch(s, val_xpu.Size(), val_xpu.dptr<DType>());
209 Kernel<rsp_idx_check, xpu>::Launch(s, idx_shape[0],
210 val_xpu.dptr<DType>(), input.aux_data(rowsparse::kIdx).dptr<IType>(),
211 idx_shape[0] - 1, input.shape()[0]);
212 mshadow::Copy(err_cpu.get<cpu, 1, DType>(),
213 val_xpu.get<xpu, 1, DType>(s), s);
219 template<
typename xpu>
221 const TBlob &err_cpu,
const bool full_check) {
224 CheckFormatCSRImpl<xpu>(rctx, input, err_cpu, full_check);
226 CheckFormatRSPImpl<xpu>(rctx, input, err_cpu, full_check);
230 LOG(FATAL) <<
"Unknown storage type " << stype;
237 template<
typename xpu>
240 const TBlob& idx_data,
246 template<
typename xpu>
254 if (!vstorage.empty()) {
255 for (
const auto& i : vstorage) {
256 if (i != stype)
return false;
274 if (!vstorage.empty()) {
276 for (
const auto i : vstorage) {
279 }
else if (i == stype2) {
286 *has_both = has == 3;
298 if (!ndarrays.empty()) {
299 for (
const auto& nd : ndarrays) {
300 if (nd.storage_type() != stype) {
319 if (!ndarrays.empty()) {
321 for (
const auto& nd : ndarrays) {
323 if (stype == stype1) {
325 }
else if (stype == stype2) {
332 *has_both = has == 3;
344 if (!ndarrays.empty()) {
345 for (
const auto& nd : ndarrays) {
346 if (nd.storage_type() == stype) {
359 if (!ndstypes.empty()) {
360 for (
const auto& ndstype : ndstypes) {
361 if (ndstype == stype) {
375 return "fcompute_ex";
377 return "fcompute_fallback";
416 const std::string& attr_name,
417 std::string default_val =
"") {
418 if (attrs.
dict.find(attr_name) == attrs.
dict.end()) {
421 return attrs.
dict.at(attr_name);
427 const std::vector<int>& in_attrs,
428 const std::vector<int>& out_attrs) {
429 std::ostringstream os;
430 os <<
"operator = " << attrs.
op->
name 431 <<
"\ninput storage types = [";
432 for (
const int attr : in_attrs) {
436 <<
"output storage types = [";
437 for (
const int attr : out_attrs) {
442 for (
auto kv : attrs.
dict) {
443 os <<
"\"" << kv.first <<
"\" : " << kv.second <<
", ";
453 const std::vector<NDArray>& inputs,
454 const std::vector<OpReqType>& req,
455 const std::vector<NDArray>& outputs) {
456 std::string result =
"";
457 std::vector<int> in_stypes;
458 std::vector<int> out_stypes;
459 in_stypes.reserve(inputs.size());
460 out_stypes.reserve(outputs.size());
461 auto xform = [](
const NDArray arr) ->
int {
return arr.storage_type(); };
462 std::transform(inputs.begin(), inputs.end(), std::back_inserter(in_stypes), xform);
463 std::transform(outputs.begin(), outputs.end(), std::back_inserter(out_stypes), xform);
469 inline void LogOnce(
const std::string& message) {
471 auto log_store = LogStore::Get();
472 if (log_store->find(message) == log_store->end()) {
473 LOG(INFO) << message;
474 log_store->insert(message);
482 const std::vector<int>* in_attrs,
483 const std::vector<int>* out_attrs) {
484 static bool log = dmlc::GetEnv(
"MXNET_STORAGE_FALLBACK_LOG_VERBOSE",
true);
487 std::ostringstream os;
488 const char* warning =
"\nThe operator with default storage type will be dispatched " 489 "for execution. You're seeing this warning message because the operator above is unable " 490 "to process the given ndarrays with specified storage types, context and parameter. " 491 "Temporary dense ndarrays are generated in order to execute the operator. " 492 "This does not affect the correctness of the programme. " 493 "You can set environment variable MXNET_STORAGE_FALLBACK_LOG_VERBOSE to " 494 "0 to suppress this warning.";
495 os <<
"\nStorage type fallback detected:\n" << op_str << warning;
497 #if MXNET_USE_MKLDNN == 1 498 if (!MKLDNNEnvSet())
common::LogOnce(
"MXNET_MKLDNN_ENABLED flag is off. " 499 "You can re-enable by setting MXNET_MKLDNN_ENABLED=1");
500 if (GetMKLDNNCacheSize() != -1)
common::LogOnce(
"MXNET_MKLDNN_CACHE_NUM is set." 501 "Should only be set if " 502 "your model has variable input shapes, " 503 "as cache size may grow unbounded");
510 return dmlc::GetEnv(
"MXNET_GPU_WORKER_NTHREADS", 2);
517 int num_match_color = dmlc::GetEnv(
"MXNET_EXEC_NUM_TEMP", 1);
521 template<
typename T,
typename V>
524 #pragma omp parallel for reduction(+:sum) 525 for (
int i = 0; i < n; ++i) {
538 template<
typename RandomIt,
typename Compare>
540 size_t grainsize,
const Compare& comp) {
541 if (len < grainsize) {
542 std::sort(first, first+len, comp);
544 std::thread thr(ParallelSortHelper<RandomIt, Compare>, first, len/2, grainsize, comp);
547 std::inplace_merge(first, first+len/2, first+len, comp);
560 template<
typename RandomIt,
typename Compare>
561 void ParallelSort(RandomIt first, RandomIt last,
size_t num_threads, Compare comp) {
562 const auto num = std::distance(first, last);
563 size_t grainsize = std::max(num / num_threads + 5, static_cast<size_t>(1024*16));
576 template<
typename RandomIt>
579 std::less<
typename std::iterator_traits<RandomIt>::value_type>());
617 template <
class T,
size_t kSize>
638 template <
class T,
class... Args>
640 return std::unique_ptr<T>(
new T(std::forward<Args>(args)...));
654 using U =
typename std::remove_extent<T>::type;
655 return std::unique_ptr<T>(
new U[n]{});
666 template <
class T,
class... Args>
669 template<
typename FCompType>
672 static auto& fcompute_cpu = nnvm::Op::GetAttr<FCompType>(name +
"<cpu>");
673 static auto& fcompute_gpu = nnvm::Op::GetAttr<FCompType>(name +
"<gpu>");
676 return fcompute_cpu.get(op,
nullptr);
678 return fcompute_gpu.get(op,
nullptr);
680 LOG(FATAL) <<
"Unknown device mask " << ctx.
dev_mask();
688 template <
typename T>
690 return std::is_integral<T>::value ?
691 std::numeric_limits<T>::max():
692 size_t(2) << (std::numeric_limits<T>::digits - 1);
696 constexpr
size_t MaxIntegerValue<mshadow::half::half_t>() {
697 return size_t(2) << 10;
701 constexpr
size_t MaxIntegerValue<mshadow::bfloat::bf16_t>() {
702 return size_t(2) << 14;
721 const Context &ctx,
const int dtype) {
724 NDArray ret(shape, ctx,
false, dtype);
729 return NDArray(stype, shape, ctx,
true, dtype);
736 const Context &ctx,
const int dtype,
737 std::vector<NDArray> *vec) {
740 vec->emplace_back(shape, ctx,
false, dtype);
744 vec->emplace_back(stype, shape, ctx,
true, dtype);
752 template<
typename DType>
754 static index_t copy_block_size = dmlc::GetEnv(
"MXNET_CPU_PARALLEL_SIZE", 200000);
755 if (size >= copy_block_size) {
756 #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) 757 for (
index_t i = 0; i < size; ++i) {
761 std::memcpy(dst, src,
sizeof(DType) * size);
768 template<
typename DType>
770 static index_t add_block_size = dmlc::GetEnv(
"MXNET_CPU_PARALLEL_SIZE", 200000);
771 if (size >= add_block_size) {
772 #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) 773 for (
index_t i = 0; i < size; ++i) {
777 for (
index_t i = 0; i < size; ++i) {
802 if (shape->
ndim() == 0) {
805 for (
int j = 0; j < shape->
ndim(); ++j) {
806 if ((*shape)[j] == 0) {
814 for (
size_t i = 0; i < shapes->size(); ++i) {
827 for (
int j = 0; j < shape->
ndim(); ++j) {
836 for (
size_t i = 0; i < shapes->size(); ++i) {
842 size_t nid,
const std::function<
void(
const char *,
const char *,
void *)>
847 size_t nid,
const std::function<
void(
const char *,
const char *,
void *)>
861 const int ndim = src.
ndim();
863 for (
int i = 0; i < ndim; ++i) {
867 CHECK(axes[i] >= 0 && axes[i] < ndim) <<
"axes[" << i <<
"]=" 868 << axes[i] <<
" exceeds the range [" 869 << 0 <<
", " << ndim <<
")";
884 if (type1 == type2)
return type1;
894 return is_float(type1) ? type1 : type2;
904 <<
"1 is UInt8 and 1 is Int8 should not get here";
926 if (dtype != -1)
return dtype;
934 #endif // MXNET_COMMON_UTILS_H_
static MSHADOW_XINLINE void Map(int i, DType *out, const IType *idx, const RType *indptr, const nnvm::dim_t ncols)
Definition: utils.h:91
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:130
DeviceType dev_mask() const
Get corresponding device mask.
Definition: base.h:120
NDArrayStorageType storage_type() const
Definition: ndarray.h:322
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:220
int GetNumThreadsPerGPU()
Definition: utils.h:508
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:119
std::vector< NodeEntry > outputs
output entries contained in the symbol
Definition: symbolic.h:73
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:425
namespace of mxnet
Definition: api_registry.h:33
void KnownBound
Type of T.
Definition: utils.h:622
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:539
int64_t dim_t
data type to store dim size
Definition: tuple.h:38
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:670
V ParallelAccumulate(const T *a, const int n, V start)
Definition: utils.h:522
void LogOnce(const std::string &message)
log message once. Intended for storage fallback warning messages.
Definition: utils.h:469
int GetDefaultDtype()
Definition: utils.h:919
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
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:123
std::string stype_string(const int x)
get string representation of storage_type
Definition: utils.h:388
Graph node data structure.
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)
bool is_np_default_dtype() const
return current numpy default dtype compatibility status.
Definition: imperative.h:123
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:561
All the possible information needed by Operator.Forward and Backward This is the superset of RunConte...
Definition: op_attr_types.h:67
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:252
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:451
static const int kDevMask
device flag number, identifies this device
Definition: tensor.h:51
std::vector< std::string > ListOutputNames() const
List the names of outputs for this symbol.
std::mt19937 RANDOM_ENGINE
Random Engine.
Definition: utils.h:585
#define MSHADOW_XINLINE
Definition: base.h:223
std::vector< mxnet::TShape > ShapeVector
The result holder of shape of each NodeEntry in the graph.
Definition: tuple.h:820
Indices of RSPNDArray should be non-negative, less than the size of first dimension and in ascending ...
Definition: utils.h:107
const Op * op
The operator this node uses. For place holder variable, op == nullptr.
Definition: node.h:124
Auxiliary data structure to index a graph. It maps Nodes in the graph to consecutive integers node_id...
Definition: graph.h:107
std::string dispatch_mode_string(const DispatchMode x)
get string representation of dispatch_mode
Definition: utils.h:370
std::string dev_type_string(const int dev_type)
get string representation of device type
Definition: utils.h:401
Helper for non-array type T.
Definition: utils.h:596
bool dim_size_is_known(const dim_t dim_size)
Definition: tuple.h:420
const mxnet::TShape & storage_shape() const
Definition: ndarray.h:230
void ParallelAdd(DType *dst, const DType *src, index_t size)
Definition: utils.h:769
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)
std::string name
name of the operator
Definition: op.h:106
bool is_int(const int dtype)
Definition: utils.h:878
an entry that represents output data from a node
Definition: node.h:51
int np_binary_out_infer_type(const int type1, const int type2)
Definition: utils.h:911
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:74
std::unique_ptr< T[]> UnknownBound
Type of T.
Definition: utils.h:611
Configuation of nnvm as well as basic data structure.
OpReqType
operation request type to Forward and Backward
Definition: op_attr_types.h:46
static const int kDevMask
device flag number, identifies this device
Definition: tensor.h:44
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:342
constexpr size_t MaxIntegerValue()
Return the max integer value representable in the type T without loss of precision.
Definition: utils.h:689
RunContext run_ctx
RunContext related resources.
Definition: op_attr_types.h:73
static Imperative * Get()
std::unordered_map< std::string, std::string > dict
The dictionary representation of attributes.
Definition: node.h:128
size_t current_process_id()
Definition: utils.h:68
std::unique_ptr< T > SingleObject
Type of T.
Definition: utils.h:600
A Shape class that is used to represent shape of each tensor.
Definition: tuple.h:438
void CheckFormatRSPImpl(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check)
Check the validity of RowSparseNDArray.
Definition: utils.h:184
int GetExecNumMatchColor()
Definition: utils.h:515
header to handle OpenMP compatibility issues
int ndim() const
Definition: tuple.h:218
#define MSHADOW_TYPE_SWITCH(type, DType,...)
Definition: base.h:1067
std::string attr_value_string(const nnvm::NodeAttrs &attrs, const std::string &attr_name, std::string default_val="")
Definition: utils.h:415
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:109
mxnet::TShape CanonicalizeAxes(const mxnet::TShape &src)
Definition: utils.h:859
bool ndim_is_known(const int ndim)
Definition: tuple.h:414
int get_more_precise_type(const int type1, const int type2)
Definition: utils.h:883
mshadow::index_t index_t
index type usually use unsigned
Definition: base.h:95
MSHADOW_XINLINE int ilog2ul(size_t a)
Definition: utils.h:705
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:480
helper::UniqueIf< T >::SingleObject MakeUnique(Args &&...args)
Constructs an object of type T and wraps it in a std::unique_ptr.
Definition: utils.h:639
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:89
bool is_float(const int dtype)
Definition: utils.h:874
ndarray interface
Definition: ndarray.h:82
void ParallelCopy(DType *dst, const DType *src, index_t size)
parallelize copy by OpenMP.
Definition: utils.h:753
NDArray InitZeros(const NDArrayStorageType stype, const mxnet::TShape &shape, const Context &ctx, const int dtype)
Return an NDArray of all zeros.
Definition: utils.h:720
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:735
MSHADOW_XINLINE int ilog2ui(unsigned int a)
Definition: utils.h:711
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:76
Symbol is help class used to represent the operator node in Graph.
Definition: symbolic.h:50
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:823
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:103
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:801
computaion stream structure, used for asynchronous computations
Definition: tensor.h:384