25 #ifndef MSHADOW_TENSOR_CPU_INL_H_ 26 #define MSHADOW_TENSOR_CPU_INL_H_ 49 bool create_dnn_handle,
59 inline std::ostream &operator<<(std::ostream &os, const Shape<ndim> &shape) {
61 for (
int i = 0; i < ndim; ++i) {
62 if (i != 0) os <<
',';
66 if (ndim == 1) os <<
',';
71 template<
typename xpu>
73 template<
typename xpu>
78 inline void *AllocHost_<gpu>(
size_t size) {
84 inline void FreeHost_<gpu>(
void *dptr) {
99 template<
typename xpu,
int dim,
typename DType>
103 void *dptr = AllocHost_<xpu>(obj->
MSize() *
sizeof(DType));
104 obj->
dptr_ =
reinterpret_cast<DType*
>(dptr);
106 template<
typename xpu,
int dim,
typename DType>
108 if (obj->
dptr_ == NULL) {
109 LOG(FATAL) <<
"FreeHost:: double free";
111 FreeHost_<xpu>(obj->
dptr_);
115 template<
int dim,
typename DType>
121 (&pitch, obj->
size(dim - 1) *
sizeof(DType), obj->
shape_.FlatTo2D()[0]);
126 (&pitch, obj->
shape_.Size() *
sizeof(DType), 1);
128 obj->
dptr_ =
reinterpret_cast<DType*
>(dptr);
130 template<
typename Device,
typename DType,
int dim>
139 template<
int dim,
typename DType>
144 template<
int dim,
typename DType>
149 <<
"Copy:shape mismatch:" << _dst.
shape_ <<
" vs " << _src.
shape_;
156 memcpy(dst[y].dptr_, src[y].dptr_,
sizeof(DType) * dst.
size(1));
161 template<
typename Saver,
typename R,
int dim,
162 typename DType,
typename E>
168 #pragma omp parallel for 172 for (
index_t x = 0; x < shape[1]; ++x) {
174 Saver::template Save<DType>(dplan.REval(y, x), plan.
Eval(y, x));
179 template<
bool pass_check,
typename Saver,
181 typename DType,
typename E,
int etype>
189 template<
typename SV,
int dim,
typename DType,
typename E,
int etype>
191 dim, DType, E, etype> {
196 expr::MapPacketPlan<SV>(dst->
self(),
197 expr::MakePacketPlan<MSHADOW_DEFAULT_PACKET>(exp.
self()));
205 template<
typename Saver,
typename R,
int dim,
206 typename DType,
typename E,
int etype>
210 ::Error_All_Tensor_in_Exp_Must_Have_Same_Type();
213 CHECK(eshape[0] == 0 || eshape == dshape)
214 <<
"Assignment: Shape of Tensors are not consistent with target, " 215 <<
"eshape: " << eshape <<
" dshape:" << dshape;
217 Saver, R, dim, DType, E, etype>
221 template<
typename Saver,
typename Reducer,
222 typename R,
typename DType,
typename E,
int etype>
227 ::Error_TypeCheck_Not_Pass_For_Reduce_Exp();
229 ::Check(exp.
self()).FlatTo2D();
231 CHECK_EQ(eshape[1], dshape[0]) <<
"MapReduceKeepLowest::reduction dimension do not match";
232 CHECK_NE(eshape[0], 0U) <<
"can not reduce over empty tensor";
237 #pragma omp parallel for 240 DType res = splan.Eval(0, x);
241 for (
index_t y = 1; y < eshape[0]; ++y) {
242 Reducer::Reduce(res, splan.Eval(y, x));
244 Saver::template Save<DType>(dplan.REval(0, x), res * scale);
248 template<
typename Saver,
typename Reducer,
int dimkeep,
249 typename R,
typename DType,
typename E,
int etype>
254 ::Error_TypeCheck_Not_Pass_For_Reduce_Exp();
259 CHECK_EQ(eshape[dimkeep], dshape[0])
260 <<
"MapReduceKeepHighDim::reduction dimension do not match";
264 eshape.ProdShape(dimkeep + 1, EShape::kSubdim),
265 eshape[EShape::kSubdim]);
270 #pragma omp parallel for 273 DType res; Reducer::SetInitValue(res);
274 for (
index_t n = 0; n < pshape[0]; ++n) {
275 DType tres; Reducer::SetInitValue(tres);
276 for (
index_t y = 0; y < pshape[2]; ++y) {
277 for (
index_t x = 0; x < pshape[3]; ++x) {
278 Reducer::Reduce(tres,
279 splan.Eval((n * pshape[1] + c) * pshape[2] + y, x));
282 Reducer::Reduce(res, tres);
284 Saver::template Save<DType>(dplan.REval(0, c), DType(res * scale));
288 template<
typename DType>
291 DType mmax = energy[0];
293 if (mmax < energy[x]) mmax = energy[x];
295 DType sum = DType(0.0f);
297 dst[x] = std::exp(energy[x] - mmax);
305 template<
typename DType>
309 #pragma omp parallel for 311 const index_t k =
static_cast<int>(label[y]);
314 dst[y][k] = src[y][k] - 1.0f;
316 dst[y][x] = src[y][x];
322 template<
typename DType>
327 const float smooth_grad = (alpha / (dst.
size(1) - 1));
328 #pragma omp parallel for 330 const index_t k =
static_cast<int>(label[y]);
333 dst[y][k] = src[y][k] - 1.0f + alpha;
335 dst[y][x] = src[y][x] - smooth_grad;
342 template<
typename DType>
346 const DType &ignore_label) {
347 #pragma omp parallel for 349 const int k =
static_cast<int>(label[y]);
350 for (
int x = 0; x < static_cast<int>(dst.
size(1)); ++x) {
351 if (static_cast<int>(ignore_label) == k) {
355 dst[y][k] = src[y][k] - 1.0f;
357 dst[y][x] = src[y][x];
364 template<
typename DType>
368 const DType &ignore_label,
370 const float smooth_grad = (alpha / (dst.
size(1) - 1));
371 #pragma omp parallel for 373 const int k =
static_cast<int>(label[y]);
374 for (
int x = 0; x < static_cast<int>(dst.
size(1)); ++x) {
375 if (static_cast<int>(ignore_label) == k) {
379 dst[y][k] = src[y][k] - 1.0f + alpha;
381 dst[y][x] = src[y][x] - smooth_grad;
388 template<
typename DType>
392 #pragma omp parallel for 395 const int k =
static_cast<int>(label[y][n]);
396 for (
int x = 0; x < static_cast<int>(dst.
size(1)); ++x) {
398 dst[y][k][n] = src[y][k][n] - 1.0f;
400 dst[y][x][n] = src[y][x][n];
407 template<
typename DType>
412 const float smooth_grad = (alpha / (dst.
size(1) - 1));
413 #pragma omp parallel for 416 const int k =
static_cast<int>(label[y][n]);
417 for (
int x = 0; x < static_cast<int>(dst.
size(1)); ++x) {
419 dst[y][k][n] = src[y][k][n] - 1.0f + alpha;
421 dst[y][x][n] = src[y][x][n] - smooth_grad;
428 template<
typename DType>
432 const DType &ignore_label) {
433 #pragma omp parallel for 436 const int k =
static_cast<int>(label[y][n]);
437 if (k == static_cast<int>(ignore_label)) {
438 for (
int x = 0; x < static_cast<int>(dst.
size(1)); ++x) {
439 dst[y][x][n] = DType(0.0f);
442 for (
int x = 0; x < static_cast<int>(dst.
size(1)); ++x) {
444 dst[y][k][n] = src[y][k][n] - 1.0f;
446 dst[y][x][n] = src[y][x][n];
454 template<
typename DType>
458 const DType &ignore_label,
460 const float smooth_grad = (alpha / (dst.
size(1) - 1));
461 #pragma omp parallel for 464 const int k =
static_cast<int>(label[y][n]);
465 if (k == static_cast<int>(ignore_label)) {
466 for (
int x = 0; x < static_cast<int>(dst.
size(1)); ++x) {
467 dst[y][x][n] = DType(0.0f);
470 for (
int x = 0; x < static_cast<int>(dst.
size(1)); ++x) {
472 dst[y][k][n] = src[y][k][n] - 1.0f + alpha;
474 dst[y][x][n] = src[y][x][n] - smooth_grad;
482 template<
typename DType>
485 CHECK_EQ(dst.
shape_, energy.
shape_) <<
"Softmax: shape mismatch";
486 #pragma omp parallel for 492 template<
typename DType>
495 CHECK_EQ(dst.
shape_, energy.
shape_) <<
"Softmax: shape mismatch";
496 #pragma omp parallel for 499 DType mmax = energy[y][0][n];
501 if (mmax < energy[y][x][n]) mmax = energy[y][x][n];
503 DType sum = DType(0.0f);
505 dst[y][x][n] = std::exp(energy[y][x][n] - mmax);
515 template<
bool clip,
typename IndexType,
typename DType>
525 else if (j >= K) j = K - 1;
530 for (
index_t i = 0; i < C; ++i) {
531 dst[j][i] += src[y][i];
536 template<
typename IndexType,
typename DType>
542 dst[sorted[y]] += src[index[y]];
546 template<
typename IndexType,
typename DType>
552 dst[index[y]][j] = src[y][j];
557 template<
typename KDType,
typename VDType>
562 CHECK_EQ(keys.
size(0), values.
size(0))
563 <<
"The sizes of key/value are not equal! keys_size: " << keys.
size(0)
564 <<
"values_size: " << values.
size(0);
565 std::vector<size_t> idx(keys.
size(0));
566 std::vector<KDType> keys_vec(keys.
size(0));
567 std::vector<VDType> values_vec(values.
size(0));
568 for (
int i = 0; i < keys.
size(0); i++) {
570 keys_vec[i] = keys[i];
571 values_vec[i] = values[i];
574 std::stable_sort(idx.begin(), idx.end(),
575 [&keys_vec](
size_t i1,
size_t i2)
576 {
return keys_vec[i1] < keys_vec[i2]; });
578 std::stable_sort(idx.begin(), idx.end(),
579 [&keys_vec](
size_t i1,
size_t i2)
580 {
return keys_vec[i1] > keys_vec[i2]; });
583 keys[i] = keys_vec[idx[i]];
584 values[i] = values_vec[idx[i]];
588 template<
typename Device,
typename VDType,
typename SDType>
596 template<
typename Device,
typename DType>
601 <<
"VectorDot: Shape mismatch";
602 CHECK_EQ(dst.
size(0), 1U)
603 <<
"VectorDot: expect dst to be scalar";
609 template<
bool transpose_left,
bool transpose_right,
typename Device,
typename DType>
625 CHECK(sleft[0] == batch_size && sright[0] == batch_size)
626 <<
"BatchGEMM: batchsize must be equal." 627 <<
"dst: " << dst.
shape_ <<
"\n" 628 <<
"lhs: " << sleft <<
"\n" 629 <<
"rhs: " << sright <<
"\n";
630 CHECK(dst.
size(1) == sleft[1] && dst.
size(2) == sright[2] && sleft[2] == sright[1])
631 <<
"BatchGEMM: matrix shape mismatch" 632 <<
"dst: " << dst.
shape_ <<
"\n" 633 <<
"lhs: " << sleft <<
"\n" 634 <<
"rhs: " << sright <<
"\n";
635 CHECK(workspace.
size(0) >= 3 * batch_size)
636 <<
"Workspace Size must be bigger than " << 3 * batch_size;
641 transpose_right, transpose_left,
642 transpose_right ? rhs.
size(1) : rhs.
size(2),
643 transpose_left ? lhs.
size(2) : lhs.
size(1),
644 transpose_right ? rhs.
size(2) : rhs.
size(1),
653 #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:597
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:91
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:140
void ShutdownTensorEngine< cpu >(void)
Definition: tensor_cpu-inl.h:41
Stream< Device > * stream_
Definition: tensor.h:574
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:547
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:306
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:323
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:71
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:610
DType * dptr_
pointer to the data
Definition: tensor.h:434
void FreeHost_(void *dptr)
Tensor RValue, this is the super type of all kinds of possible tensors.
Definition: tensor.h:409
const Container & self(void) const
Definition: expression.h:82
Definition: expr_engine-inl.h:58
void SetDevice< cpu >(int devid)
Definition: tensor_cpu-inl.h:45
used to help static type check
Definition: expr_engine-inl.h:330
void AlignedFree(void *ptr)
free aligned space
Definition: packet-inl.h:106
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:145
MSHADOW_XINLINE index_t MSize(void) const
Definition: tensor.h:497
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:207
Container * ptrself(void)
Definition: expression.h:86
Shape< dimension > shape_
shape of the tensor
Definition: tensor.h:436
Definition: packet-inl.h:379
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:240
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:558
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:483
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:589
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:77
#define MSHADOW_CUDA_CALL(func)
Protected cuda call in mshadow.
Definition: base.h:278
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:223
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:39
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...
void * AllocHost_(size_t size)
MSHADOW_XINLINE index_t size(index_t i) const
Definition: tensor.h:606
void FreeHost_< cpu >(void *dptr)
Definition: tensor_cpu-inl.h:95
int32_t index_t
type that will be used for index
Definition: base.h:343
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:116
DType * dptr_
Definition: tensor.h:571
MSHADOW_XINLINE Tensor< Device, 2, DType > FlatTo2D(void) const
flatten the tensor to 2 dimension, collapse the higher dimensions together
Definition: tensor.h:519
Generic packet vectorization code.
void InitTensorEngine< cpu >(int dev_id)
Definition: tensor_cpu-inl.h:38
MSHADOW_XINLINE index_t size(int idx) const
return size of i-th dimension, start counting from highest dimension
Definition: tensor.h:505
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:537
MSHADOW_XINLINE bool CheckContiguous(void) const
Definition: tensor.h:491
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:125
void AllocHost(Tensor< cpu, dim, DType > *obj)
Definition: tensor_cpu-inl.h:100
runtime shape checking template get the shape of an expression, report error if shape mismatch ...
Definition: expr_engine-inl.h:364
Stream< cpu > * NewStream< cpu >(bool create_blas_handle, bool create_dnn_handle, int dev_id)
Definition: tensor_cpu-inl.h:48
void MapPlan(TRValue< R, cpu, dim, DType > *dst, const expr::Plan< E, DType > &plan)
Definition: tensor_cpu-inl.h:163
Definition: tensor_cpu-inl.h:182
scalar expression
Definition: expression.h:95
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:250
void * AllocHost_< cpu >(size_t size)
Definition: tensor_cpu-inl.h:90
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:132
defines how expression exp can be evaluated and stored into dst
Definition: expression.h:79
Plan< BinaryMapExp< OP, TA, TB, DType, etype >, DType > MakePlan(const BinaryMapExp< OP, TA, TB, DType, etype > &e)
Definition: expr_engine-inl.h:239
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:516
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:227
overloaded + operator between half_t and bf16_t
Definition: base.h:334
void FreeHost(Tensor< cpu, dim, DType > *obj)
Definition: tensor_cpu-inl.h:107
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:441
#define MSHADOW_DEFAULT_PACKET
Definition: packet-inl.h:47
general tensor
Definition: tensor.h:420
static void SetStream(Stream< Device > *stream)
Definition: dot_engine-inl.h:82
void DeleteStream< cpu >(Stream< cpu > *stream)
Definition: tensor_cpu-inl.h:54
static void Map(Tensor< cpu, dim, DType > *dst, const expr::Exp< E, DType, etype > &exp)
Definition: tensor_cpu-inl.h:192
index_t openmp_index_t
openmp index for linux
Definition: base.h:351
Stream< Device > * stream_
stream where the computation lies stream is a device dependency concept where each computation ...
Definition: tensor.h:446
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:183
computaion stream structure, used for asynchronous computations
Definition: tensor.h:383