26 #ifndef MSHADOW_TENSOR_CPU_INL_H_ 27 #define MSHADOW_TENSOR_CPU_INL_H_ 50 bool create_dnn_handle,
60 inline std::ostream &operator<<(std::ostream &os, const Shape<ndim> &shape) {
62 for (
int i = 0; i < ndim; ++i) {
63 if (i != 0) os <<
',';
67 if (ndim == 1) os <<
',';
72 template<
typename xpu>
74 template<
typename xpu>
79 inline void *AllocHost_<gpu>(
size_t size) {
85 inline void FreeHost_<gpu>(
void *dptr) {
100 template<
typename xpu,
int dim,
typename DType>
104 void *dptr = AllocHost_<xpu>(obj->
MSize() *
sizeof(DType));
105 obj->
dptr_ =
reinterpret_cast<DType*
>(dptr);
107 template<
typename xpu,
int dim,
typename DType>
109 if (obj->
dptr_ == NULL) {
110 LOG(FATAL) <<
"FreeHost:: double free";
112 FreeHost_<xpu>(obj->
dptr_);
116 template<
int dim,
typename DType>
122 (&pitch, obj->
size(dim - 1) *
sizeof(DType), obj->
shape_.FlatTo2D()[0]);
127 (&pitch, obj->
shape_.Size() *
sizeof(DType), 1);
129 obj->
dptr_ =
reinterpret_cast<DType*
>(dptr);
131 template<
typename Device,
typename DType,
int dim>
140 template<
int dim,
typename DType>
145 template<
int dim,
typename DType>
150 <<
"Copy:shape mismatch:" << _dst.
shape_ <<
" vs " << _src.
shape_;
157 memcpy(dst[y].dptr_, src[y].dptr_,
sizeof(DType) * dst.
size(1));
162 template<
typename Saver,
typename R,
int dim,
163 typename DType,
typename E>
169 #pragma omp parallel for 173 for (
index_t x = 0; x < shape[1]; ++x) {
175 Saver::template Save<DType>(dplan.REval(y, x), plan.
Eval(y, x));
180 template<
bool pass_check,
typename Saver,
182 typename DType,
typename E,
int etype>
190 template<
typename SV,
int dim,
typename DType,
typename E,
int etype>
192 dim, DType, E, etype> {
197 expr::MapPacketPlan<SV>(dst->
self(),
198 expr::MakePacketPlan<MSHADOW_DEFAULT_PACKET>(exp.
self()));
206 template<
typename Saver,
typename R,
int dim,
207 typename DType,
typename E,
int etype>
211 ::Error_All_Tensor_in_Exp_Must_Have_Same_Type();
214 CHECK(eshape[0] == 0 || eshape == dshape)
215 <<
"Assignment: Shape of Tensors are not consistent with target, " 216 <<
"eshape: " << eshape <<
" dshape:" << dshape;
218 Saver, R, dim, DType, E, etype>
222 template<
typename Saver,
typename Reducer,
223 typename R,
typename DType,
typename E,
int etype>
228 ::Error_TypeCheck_Not_Pass_For_Reduce_Exp();
230 ::Check(exp.
self()).FlatTo2D();
232 CHECK_EQ(eshape[1], dshape[0]) <<
"MapReduceKeepLowest::reduction dimension do not match";
233 CHECK_NE(eshape[0], 0U) <<
"can not reduce over empty tensor";
238 #pragma omp parallel for 241 DType res = splan.Eval(0, x);
242 for (
index_t y = 1; y < eshape[0]; ++y) {
243 Reducer::Reduce(res, splan.Eval(y, x));
245 Saver::template Save<DType>(dplan.REval(0, x), res * scale);
249 template<
typename Saver,
typename Reducer,
int dimkeep,
250 typename R,
typename DType,
typename E,
int etype>
255 ::Error_TypeCheck_Not_Pass_For_Reduce_Exp();
260 CHECK_EQ(eshape[dimkeep], dshape[0])
261 <<
"MapReduceKeepHighDim::reduction dimension do not match";
265 eshape.ProdShape(dimkeep + 1, EShape::kSubdim),
266 eshape[EShape::kSubdim]);
271 #pragma omp parallel for 274 DType res; Reducer::SetInitValue(res);
275 for (
index_t n = 0; n < pshape[0]; ++n) {
276 DType tres; Reducer::SetInitValue(tres);
277 for (
index_t y = 0; y < pshape[2]; ++y) {
278 for (
index_t x = 0; x < pshape[3]; ++x) {
279 Reducer::Reduce(tres,
280 splan.Eval((n * pshape[1] + c) * pshape[2] + y, x));
283 Reducer::Reduce(res, tres);
285 Saver::template Save<DType>(dplan.REval(0, c), DType(res * scale));
289 template<
typename DType>
292 DType mmax = energy[0];
294 if (mmax < energy[x]) mmax = energy[x];
296 DType sum = DType(0.0f);
298 dst[x] = std::exp(energy[x] - mmax);
306 template<
typename DType>
310 #pragma omp parallel for 312 const index_t k =
static_cast<int>(label[y]);
315 dst[y][k] = src[y][k] - 1.0f;
317 dst[y][x] = src[y][x];
323 template<
typename DType>
328 const float smooth_grad = (alpha / (dst.
size(1) - 1));
329 #pragma omp parallel for 331 const index_t k =
static_cast<int>(label[y]);
334 dst[y][k] = src[y][k] - 1.0f + alpha;
336 dst[y][x] = src[y][x] - smooth_grad;
343 template<
typename DType>
347 const DType &ignore_label) {
348 #pragma omp parallel for 350 const int k =
static_cast<int>(label[y]);
351 for (
int x = 0; x < static_cast<int>(dst.
size(1)); ++x) {
352 if (static_cast<int>(ignore_label) == k) {
356 dst[y][k] = src[y][k] - 1.0f;
358 dst[y][x] = src[y][x];
365 template<
typename DType>
369 const DType &ignore_label,
371 const float smooth_grad = (alpha / (dst.
size(1) - 1));
372 #pragma omp parallel for 374 const int k =
static_cast<int>(label[y]);
375 for (
int x = 0; x < static_cast<int>(dst.
size(1)); ++x) {
376 if (static_cast<int>(ignore_label) == k) {
380 dst[y][k] = src[y][k] - 1.0f + alpha;
382 dst[y][x] = src[y][x] - smooth_grad;
389 template<
typename DType>
393 #pragma omp parallel for 396 const int k =
static_cast<int>(label[y][n]);
397 for (
int x = 0; x < static_cast<int>(dst.
size(1)); ++x) {
399 dst[y][k][n] = src[y][k][n] - 1.0f;
401 dst[y][x][n] = src[y][x][n];
408 template<
typename DType>
413 const float smooth_grad = (alpha / (dst.
size(1) - 1));
414 #pragma omp parallel for 417 const int k =
static_cast<int>(label[y][n]);
418 for (
int x = 0; x < static_cast<int>(dst.
size(1)); ++x) {
420 dst[y][k][n] = src[y][k][n] - 1.0f + alpha;
422 dst[y][x][n] = src[y][x][n] - smooth_grad;
429 template<
typename DType>
433 const DType &ignore_label) {
434 #pragma omp parallel for 437 const int k =
static_cast<int>(label[y][n]);
438 if (k == static_cast<int>(ignore_label)) {
439 for (
int x = 0; x < static_cast<int>(dst.
size(1)); ++x) {
440 dst[y][x][n] = DType(0.0f);
443 for (
int x = 0; x < static_cast<int>(dst.
size(1)); ++x) {
445 dst[y][k][n] = src[y][k][n] - 1.0f;
447 dst[y][x][n] = src[y][x][n];
455 template<
typename DType>
459 const DType &ignore_label,
461 const float smooth_grad = (alpha / (dst.
size(1) - 1));
462 #pragma omp parallel for 465 const int k =
static_cast<int>(label[y][n]);
466 if (k == static_cast<int>(ignore_label)) {
467 for (
int x = 0; x < static_cast<int>(dst.
size(1)); ++x) {
468 dst[y][x][n] = DType(0.0f);
471 for (
int x = 0; x < static_cast<int>(dst.
size(1)); ++x) {
473 dst[y][k][n] = src[y][k][n] - 1.0f + alpha;
475 dst[y][x][n] = src[y][x][n] - smooth_grad;
483 template<
typename DType>
486 CHECK_EQ(dst.
shape_, energy.
shape_) <<
"Softmax: shape mismatch";
487 #pragma omp parallel for 493 template<
typename DType>
496 CHECK_EQ(dst.
shape_, energy.
shape_) <<
"Softmax: shape mismatch";
497 #pragma omp parallel for 500 DType mmax = energy[y][0][n];
502 if (mmax < energy[y][x][n]) mmax = energy[y][x][n];
504 DType sum = DType(0.0f);
506 dst[y][x][n] = std::exp(energy[y][x][n] - mmax);
516 template<
bool clip,
typename IndexType,
typename DType>
526 else if (j >= K) j = K - 1;
531 for (
index_t i = 0; i < C; ++i) {
532 dst[j][i] += src[y][i];
537 template<
typename IndexType,
typename DType>
543 dst[sorted[y]] += src[index[y]];
547 template<
typename IndexType,
typename DType>
553 dst[index[y]][j] = src[y][j];
558 template<
typename KDType,
typename VDType>
563 CHECK_EQ(keys.
size(0), values.
size(0))
564 <<
"The sizes of key/value are not equal! keys_size: " << keys.
size(0)
565 <<
"values_size: " << values.
size(0);
566 std::vector<size_t> idx(keys.
size(0));
567 std::vector<KDType> keys_vec(keys.
size(0));
568 std::vector<VDType> values_vec(values.
size(0));
569 for (
int i = 0; i < keys.
size(0); i++) {
571 keys_vec[i] = keys[i];
572 values_vec[i] = values[i];
575 std::stable_sort(idx.begin(), idx.end(),
576 [&keys_vec](
size_t i1,
size_t i2)
577 {
return keys_vec[i1] < keys_vec[i2]; });
579 std::stable_sort(idx.begin(), idx.end(),
580 [&keys_vec](
size_t i1,
size_t i2)
581 {
return keys_vec[i1] > keys_vec[i2]; });
584 keys[i] = keys_vec[idx[i]];
585 values[i] = values_vec[idx[i]];
589 template<
typename Device,
typename VDType,
typename SDType>
597 template<
typename Device,
typename DType>
602 <<
"VectorDot: Shape mismatch";
603 CHECK_EQ(dst.
size(0), 1U)
604 <<
"VectorDot: expect dst to be scalar";
610 template<
bool transpose_left,
bool transpose_right,
typename Device,
typename DType>
626 CHECK(sleft[0] == batch_size && sright[0] == batch_size)
627 <<
"BatchGEMM: batchsize must be equal." 628 <<
"dst: " << dst.
shape_ <<
"\n" 629 <<
"lhs: " << sleft <<
"\n" 630 <<
"rhs: " << sright <<
"\n";
631 CHECK(dst.
size(1) == sleft[1] && dst.
size(2) == sright[2] && sleft[2] == sright[1])
632 <<
"BatchGEMM: matrix shape mismatch" 633 <<
"dst: " << dst.
shape_ <<
"\n" 634 <<
"lhs: " << sleft <<
"\n" 635 <<
"rhs: " << sright <<
"\n";
636 CHECK(workspace.
size(0) >= 3 * batch_size)
637 <<
"Workspace Size must be bigger than " << 3 * batch_size;
642 transpose_right, transpose_left,
643 transpose_right ? rhs.
size(1) : rhs.
size(2),
644 transpose_left ? lhs.
size(2) : lhs.
size(1),
645 transpose_right ? rhs.
size(2) : rhs.
size(1),
654 #endif // MSHADOW_TENSOR_CPU_INL_H_ void VectorDot(Tensor< Device, 1, DType > dst, const Tensor< Device, 1, DType > &lhs, const Tensor< Device, 1, DType > &rhs)
CPU/GPU: 1 dimension vector dot.
Definition: tensor_cpu-inl.h:598
static void batched_gemm(Stream< Device > *stream, bool transa, bool transb, int m, int n, int k, DType alpha, const DType *A, int lda, const DType *B, int ldb, DType beta, DType *C, int ldc, int batch_count, DType **workspace)
Definition: dot_engine-inl.h:92
void FreeSpace(Tensor< cpu, dim, DType > *obj)
CPU/GPU: free the space of tensor, will set obj.dptr to NULL.
Definition: tensor_cpu-inl.h:141
void ShutdownTensorEngine< cpu >(void)
Definition: tensor_cpu-inl.h:42
Stream< Device > * stream_
Definition: tensor.h:575
void IndexFill(Tensor< cpu, 2, DType > dst, const Tensor< cpu, 1, IndexType > &index, const Tensor< cpu, 2, DType > &src)
CPU/GPU: Fill the values of the destination matrix to specific rows in the source matrix...
Definition: tensor_cpu-inl.h:548
void SoftmaxGrad(Tensor< cpu, 2, DType > dst, const Tensor< cpu, 2, DType > &src, const Tensor< cpu, 1, DType > &label)
CPU/GPU: softmax gradient.
Definition: tensor_cpu-inl.h:307
void SmoothSoftmaxGrad(Tensor< cpu, 2, DType > dst, const Tensor< cpu, 2, DType > &src, const Tensor< cpu, 1, DType > &label, const float alpha)
Definition: tensor_cpu-inl.h:324
PaddingExp< SrcExp, DType, ExpInfo< SrcExp >::kDim > pad(const Exp< SrcExp, DType, etype > &src, index_t pad)
padding expression, pad a image with zeros on boundaries, padding affects shape[0], and shape[1]
Definition: pad.h:72
DType * dptr_
pointer to the data
Definition: tensor.h:435
void FreeHost_(void *dptr)
Tensor RValue, this is the super type of all kinds of possible tensors.
Definition: tensor.h:410
Definition: expr_engine-inl.h:59
void SetDevice< cpu >(int devid)
Definition: tensor_cpu-inl.h:46
used to help static type check
Definition: expr_engine-inl.h:331
void AlignedFree(void *ptr)
free aligned space
Definition: packet-inl.h:103
void Copy(Tensor< cpu, dim, DType > dst, const Tensor< cpu, dim, DType > &src, Stream< cpu > *stream=NULL)
copy data from one tensor to another, with same shape
Definition: tensor_cpu-inl.h:146
void MapExp(TRValue< R, cpu, dim, DType > *dst, const expr::Exp< E, DType, etype > &exp)
CPU/GPU: map a expression to a tensor, this function calls MapPlan.
Definition: tensor_cpu-inl.h:208
Container * ptrself(void)
Definition: expression.h:87
Shape< dimension > shape_
shape of the tensor
Definition: tensor.h:437
Definition: packet-inl.h:376
MSHADOW_XINLINE DType Eval(index_t y, index_t x) const
evaluate the expression at index [y][x] to be implemented by SubType, for RValue, the return type wil...
MSHADOW_XINLINE Shape< 4 > Shape4(index_t s0, index_t s1, index_t s2, index_t s3)
construct a four dimension shape, stride will equal s0
Definition: tensor.h:241
void SortByKey(Tensor< cpu, 1, KDType > keys, Tensor< cpu, 1, VDType > values, bool is_ascend=true)
CPU/GPU: Sort key-value pairs stored in separate places. (Stable sort is performed!) ...
Definition: tensor_cpu-inl.h:559
void Softmax(Tensor< cpu, 2, DType > dst, const Tensor< cpu, 2, DType > &energy)
CPU/GPU: normalize softmax: dst[i][j] = exp(energy[i][j]) /(sum_j exp(energy[i][j])) ...
Definition: tensor_cpu-inl.h:484
void VectorizedSort(Tensor< Device, 1, VDType > values, Tensor< Device, 1, SDType > segments)
CPU/GPU: Sort the keys within each segment. (Stable sort is performed!) Segments is defined as an asc...
Definition: tensor_cpu-inl.h:590
void * AlignedMallocPitch(size_t *out_pitch, size_t lspace, size_t num_line)
analog to cudaMallocPitch, allocate a aligned space with num_line * lspace cells
Definition: packet-inl.h:78
void BatchGEMM(Tensor< Device, 3, DType > dst, const Tensor< Device, 3, DType > &lhs, const Tensor< Device, 3, DType > &rhs, DType alpha, DType beta, Tensor< Device, 1, DType * > workspace)
CPU/GPU: dst = alpha * op(lhs) op(rhs) + beta * dst.
Definition: tensor_cpu-inl.h:611
#define MSHADOW_CUDA_CALL(func)
Protected cuda call in mshadow.
Definition: base.h:271
void MapReduceKeepLowest(TRValue< R, cpu, 1, DType > *dst, const expr::Exp< E, DType, etype > &exp, DType scale=1)
CPU/GPU: map a expression, do reduction to 1D Tensor in lowest dimension (dimension 0) ...
Definition: tensor_cpu-inl.h:224
static Shape< dim > Check(const E &t)
header file of tensor data structure and functions This lib requires explicit memory allocation and d...
device name CPU
Definition: tensor.h:40
MSHADOW_XINLINE Tensor< Device, 2, DType > FlatTo2D(void) const
flatten the tensor to 2 dimension, collapse the higher dimensions together
Definition: tensor.h:520
void * AllocHost_(size_t size)
MSHADOW_XINLINE index_t size(index_t i) const
Definition: tensor.h:607
void FreeHost_< cpu >(void *dptr)
Definition: tensor_cpu-inl.h:96
int32_t index_t
type that will be used for index
Definition: base.h:336
void AllocSpace(Tensor< cpu, dim, DType > *obj, bool pad=MSHADOW_ALLOC_PAD)
CPU/CPU: allocate space for CTensor, according to the shape in the obj this function is responsible t...
Definition: tensor_cpu-inl.h:117
DType * dptr_
Definition: tensor.h:572
Generic packet vectorization code.
void InitTensorEngine< cpu >(int dev_id)
Definition: tensor_cpu-inl.h:39
void AddTakeGradLargeBatch(Tensor< cpu, 2, DType > dst, const Tensor< cpu, 1, IndexType > &sorted, const Tensor< cpu, 1, IndexType > &index, const Tensor< cpu, 2, DType > &src)
CPU/GPU: Gradient accumulate of embedding matrix. dst[sorted[i]] += src[index[i]] Called when the bat...
Definition: tensor_cpu-inl.h:538
static void dot(Stream< Device > *stream, int n, const DType *X, int incX, const DType *Y, int incY, DType *ret)
Definition: dot_engine-inl.h:126
void AllocHost(Tensor< cpu, dim, DType > *obj)
Definition: tensor_cpu-inl.h:101
runtime shape checking template get the shape of an expression, report error if shape mismatch ...
Definition: expr_engine-inl.h:365
Stream< cpu > * NewStream< cpu >(bool create_blas_handle, bool create_dnn_handle, int dev_id)
Definition: tensor_cpu-inl.h:49
void MapPlan(TRValue< R, cpu, dim, DType > *dst, const expr::Plan< E, DType > &plan)
Definition: tensor_cpu-inl.h:164
MSHADOW_XINLINE bool CheckContiguous(void) const
Definition: tensor.h:492
Definition: tensor_cpu-inl.h:183
scalar expression
Definition: expression.h:96
void MapReduceKeepHighDim(TRValue< R, cpu, 1, DType > *dst, const expr::Exp< E, DType, etype > &exp, DType scale=1)
CPU/GPU: map a expression, do reduction to 1D Tensor in third dimension (dimension 2) ...
Definition: tensor_cpu-inl.h:251
void * AllocHost_< cpu >(size_t size)
Definition: tensor_cpu-inl.h:91
Tensor< Device, dim, DType > NewTensor(const Shape< dim > &shape, DType initv, bool pad=MSHADOW_ALLOC_PAD, Stream< Device > *stream=NULL)
CPU/GPU: short cut to allocate and initialize a Tensor.
Definition: tensor_cpu-inl.h:133
defines how expression exp can be evaluated and stored into dst
Definition: expression.h:80
const Container & self(void) const
Definition: expression.h:83
Plan< BinaryMapExp< OP, TA, TB, DType, etype >, DType > MakePlan(const BinaryMapExp< OP, TA, TB, DType, etype > &e)
Definition: expr_engine-inl.h:240
void AddTakeGrad(Tensor< cpu, 2, DType > dst, const Tensor< cpu, 1, IndexType > &index, const Tensor< cpu, 2, DType > &src)
CPU/GPU: Gradient accumulate of embedding matrix. dst[index[i]] += src[i] Called when the featuredim ...
Definition: tensor_cpu-inl.h:517
MSHADOW_XINLINE Shape< 3 > Shape3(index_t s0, index_t s1, index_t s2)
construct a three dimension shape, stride will equal s0
Definition: tensor.h:228
overloaded + operator between half_t and bf16_t
Definition: base.h:327
void FreeHost(Tensor< cpu, dim, DType > *obj)
Definition: tensor_cpu-inl.h:108
MSHADOW_XINLINE index_t size(int idx) const
return size of i-th dimension, start counting from highest dimension
Definition: tensor.h:506
index_t stride_
storing the stride information in x dimension this is used to deal with pitch allocation in gpu or ss...
Definition: tensor.h:442
#define MSHADOW_DEFAULT_PACKET
Definition: packet-inl.h:48
general tensor
Definition: tensor.h:421
static void SetStream(Stream< Device > *stream)
Definition: dot_engine-inl.h:83
MSHADOW_XINLINE index_t MSize(void) const
Definition: tensor.h:498
void DeleteStream< cpu >(Stream< cpu > *stream)
Definition: tensor_cpu-inl.h:55
static void Map(Tensor< cpu, dim, DType > *dst, const expr::Exp< E, DType, etype > &exp)
Definition: tensor_cpu-inl.h:193
index_t openmp_index_t
openmp index for linux
Definition: base.h:344
Stream< Device > * stream_
stream where the computation lies stream is a device dependency concept where each computation ...
Definition: tensor.h:447
definitions of how Matrix Multiplications can be evaluated
static void Map(TRValue< R, cpu, dim, DType > *dst, const expr::Exp< E, DType, etype > &exp)
Definition: tensor_cpu-inl.h:184
computaion stream structure, used for asynchronous computations
Definition: tensor.h:384