Matrix.cpp 154.8 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "Matrix.h"
Q
qijun 已提交
16
#include "MathFunctions.h"
Z
zhangjinchao01 已提交
17 18 19 20 21
#include "SparseMatrix.h"
#include "SparseRowMatrix.h"

#include <float.h>
#include <algorithm>
Q
qijun 已提交
22
#include <cmath>
Z
zhangjinchao01 已提交
23 24

#include <string.h>
L
liaogang 已提交
25
#include "hl_cnn.h"
Z
zhangjinchao01 已提交
26 27 28
#include "hl_gpu.h"
#include "hl_table_apply.h"
#include "hl_top_k.h"
X
Xin Pan 已提交
29
#include "paddle/legacy/utils/Logging.h"
Z
zhangjinchao01 已提交
30

X
xzl 已提交
31
#include "NEONFunctions.h"
X
Xin Pan 已提交
32
#include "paddle/legacy/function/GemmFunctor.h"
X
Xin Pan 已提交
33
#include "paddle/legacy/utils/ThreadLocal.h"
Z
zhangjinchao01 已提交
34 35 36 37 38 39 40 41 42 43 44

#include "SIMDFunctions.h"

namespace paddle {

inline real _pow(real a, real beta) { return std::pow(a, beta); }

inline real _square(real a) { return a * a; }

inline real _safelog(real a) { return a > 0.0f ? std::log(a) : -40.0f; }

45 46 47 48 49
Matrix::Matrix(MemoryHandlePtr memHandle,
               size_t height,
               size_t width,
               bool trans,
               bool use_gpu)
Z
zhangjinchao01 已提交
50
    : BaseMatrix(
51 52
          height,
          width,
Q
qijun 已提交
53
          memHandle ? (reinterpret_cast<real*>(memHandle->getBuf())) : nullptr,
54 55
          trans,
          use_gpu) {
Z
zhangjinchao01 已提交
56 57 58 59
  elementCnt_ = width * height;
  memoryHandle_ = memHandle;
}

60 61
Matrix::Matrix(
    real* data, size_t height, size_t width, bool trans, bool use_gpu)
Z
zhangjinchao01 已提交
62 63 64 65
    : BaseMatrix(height, width, data, trans, use_gpu) {
  elementCnt_ = width * height;
}

66 67 68 69 70 71
Matrix::Matrix(real* data,
               size_t height,
               size_t width,
               size_t stride,
               bool trans,
               bool use_gpu)
Z
zhangjinchao01 已提交
72 73 74 75
    : BaseMatrix(height, width, stride, data, trans, use_gpu) {
  elementCnt_ = width * height;
}

76 77 78 79 80
MatrixPtr Matrix::createSparseMatrix(real* data,
                                     int* row,
                                     int* col,
                                     size_t height,
                                     size_t width,
Z
zhangjinchao01 已提交
81 82
                                     size_t nnz, /* used to allocate space */
                                     SparseValueType valueType, /*value type*/
83 84
                                     SparseFormat format,
                                     bool trans,
Z
zhangjinchao01 已提交
85 86
                                     bool useGpu) {
  if (useGpu) {
87 88
    return std::make_shared<GpuSparseMatrix>(
        data, row, col, height, width, nnz, valueType, format, trans);
Z
zhangjinchao01 已提交
89
  } else {
90 91
    return std::make_shared<CpuSparseMatrix>(
        data, row, col, height, width, nnz, valueType, format, trans);
Z
zhangjinchao01 已提交
92 93 94
  }
}

95 96
MatrixPtr Matrix::createSparseMatrix(size_t height,
                                     size_t width,
Z
zhangjinchao01 已提交
97 98
                                     size_t nnz, /* used to allocate space */
                                     SparseValueType valueType, /*value type*/
99 100
                                     SparseFormat format,
                                     bool trans,
Z
zhangjinchao01 已提交
101 102
                                     bool useGpu) {
  if (useGpu) {
103 104
    return std::make_shared<GpuSparseMatrix>(
        height, width, nnz, valueType, format, trans);
Z
zhangjinchao01 已提交
105
  } else {
106 107
    return std::make_shared<CpuSparseMatrix>(
        height, width, nnz, valueType, format, trans);
Z
zhangjinchao01 已提交
108 109 110
  }
}

111 112 113
MatrixPtr Matrix::create(MemoryHandlePtr memHandle,
                         size_t height,
                         size_t width,
Z
zhangjinchao01 已提交
114 115 116 117
                         bool trans) {
  if (auto gpuHandle = std::dynamic_pointer_cast<GpuMemoryHandle>(memHandle)) {
    return std::make_shared<GpuMatrix>(gpuHandle, height, width, trans);
  } else if (auto cpuHandle =
Q
qijun 已提交
118
                 std::dynamic_pointer_cast<CpuMemoryHandle>(memHandle)) {
Z
zhangjinchao01 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
    return std::make_shared<CpuMatrix>(cpuHandle, height, width, trans);
  } else {
    LOG(FATAL) << "Wrong";
    return nullptr;
  }
}

MatrixPtr Matrix::create(size_t height, size_t width, bool trans, bool useGpu) {
  if (useGpu) {
    return std::make_shared<GpuMatrix>(height, width, trans);
  } else {
    return std::make_shared<CpuMatrix>(height, width, trans);
  }
}

134 135
MatrixPtr Matrix::create(
    real* data, size_t height, size_t width, bool trans, bool useGpu) {
Z
zhangjinchao01 已提交
136 137 138 139 140 141 142
  if (useGpu) {
    return std::make_shared<GpuMatrix>(data, height, width, trans);
  } else {
    return std::make_shared<CpuMatrix>(data, height, width, trans);
  }
}

143 144 145 146 147 148
MatrixPtr Matrix::create(real* data,
                         size_t height,
                         size_t width,
                         size_t stride,
                         bool trans,
                         bool useGpu) {
Z
zhangjinchao01 已提交
149 150 151 152 153 154 155
  if (useGpu) {
    return std::make_shared<GpuMatrix>(data, height, width, stride, trans);
  } else {
    return std::make_shared<CpuMatrix>(data, height, width, stride, trans);
  }
}

156 157 158 159 160
MatrixPtr Matrix::createSparseMatrix(size_t height,
                                     size_t width,
                                     size_t nnz,
                                     SparseValueType valueType,
                                     bool trans,
Z
zhangjinchao01 已提交
161 162
                                     bool useGpu) {
  if (useGpu) {
163 164
    return std::make_shared<GpuSparseMatrix>(
        height, width, nnz, valueType, SPARSE_CSR, trans);
Z
zhangjinchao01 已提交
165
  } else {
166 167
    return std::make_shared<CpuSparseMatrix>(
        height, width, nnz, valueType, SPARSE_CSR, trans);
Z
zhangjinchao01 已提交
168 169 170
  }
}

171 172
void Matrix::resizeOrCreate(
    MatrixPtr& matrix, size_t height, size_t width, bool trans, bool useGpu) {
Z
zhangjinchao01 已提交
173 174 175
  if (!matrix) {
    matrix = Matrix::create(height, width, trans, useGpu);
  } else {
176
    CHECK_EQ(matrix->useGpu(), useGpu);
Z
zhangjinchao01 已提交
177 178 179 180
    matrix->resize(height, width);
  }
}

181 182 183 184
void Matrix::resizeOrCreateSparseMatrix(MatrixPtr& matrix,
                                        size_t height,
                                        size_t width,
                                        size_t nnz,
Z
zhangjinchao01 已提交
185
                                        SparseValueType valueType,
186 187
                                        SparseFormat format,
                                        bool trans,
Z
zhangjinchao01 已提交
188 189
                                        bool useGpu) {
  if (!matrix) {
190 191
    matrix = Matrix::createSparseMatrix(
        height, width, nnz, valueType, format, trans, useGpu);
Z
zhangjinchao01 已提交
192 193 194
  } else {
    CHECK(dynamic_cast<CpuSparseMatrix*>(matrix.get()) ||
          dynamic_cast<GpuSparseMatrix*>(matrix.get()));
195
    CHECK_EQ(matrix->useGpu(), useGpu);
Z
zhangjinchao01 已提交
196 197 198 199 200 201 202 203 204 205 206 207
    matrix->resize(height, width, nnz, valueType, format);
  }
}

void Matrix::reshape(size_t height, size_t width) {
  CHECK(isContiguous());
  CHECK(height_ * width_ == height * width);
  height_ = height;
  width_ = width;
  stride_ = width_;
}

208 209 210
MatrixPtr Matrix::subMatrix(size_t startRow,
                            size_t endRow,
                            size_t startCol,
Z
zhangjinchao01 已提交
211 212 213 214 215 216 217
                            size_t endCol) {
  CHECK_LE(startRow, endRow);
  CHECK_LE(endRow, getHeight());
  CHECK_LE(startCol, endCol);
  CHECK_LE(endCol, getWidth());

  return Matrix::create(getData() + startRow * getStride() + startCol,
218 219 220 221 222
                        endRow - startRow,
                        endCol - startCol,
                        getStride(),
                        trans_,
                        useGpu_);
Z
zhangjinchao01 已提交
223 224
}

225 226 227 228 229 230 231 232 233
void Matrix::setDiag(real value) {
  CHECK(data_ != NULL);
  CHECK_EQ(height_, width_);

  zeroMem();
  BaseMatrix diag(height_, 1, stride_ + 1, data_, false, useGpu_);
  diag.assign(value);
}

Z
zhangjinchao01 已提交
234 235
GpuMatrix::GpuMatrix(size_t height, size_t width, bool trans)
    : Matrix(std::make_shared<GpuMemoryHandle>(height * width * sizeof(real)),
236 237 238 239
             height,
             width,
             trans,
             true) {}
Z
zhangjinchao01 已提交
240 241 242 243 244 245 246 247 248 249 250 251

GpuMatrix::~GpuMatrix() {}

void GpuMatrix::zeroMem() {
  CHECK(data_ != NULL);
  zero();
}

void GpuMatrix::resetOne() {
  CHECK(data_ != NULL);
  one();
}
252

Z
zhangjinchao01 已提交
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
void GpuMatrix::resize(size_t newHeight, size_t newWidth) {
  size_t newSize = newHeight * newWidth;
  if (NULL == memoryHandle_.get() ||
      newSize * sizeof(real) > memoryHandle_->getAllocSize()) {
    memoryHandle_ = std::make_shared<GpuMemoryHandle>(newSize * sizeof(real));
    data_ = reinterpret_cast<real*>(memoryHandle_->getBuf());
  }
  height_ = newHeight;
  width_ = newWidth;
  elementCnt_ = newSize;
  stride_ = width_;
}

real GpuMatrix::getElement(size_t x, size_t y) const {
  real elem = 0;
  hl_memcpy_device2host(&elem, &data_[x * stride_ + y], sizeof(real));
  return elem;
}

real GpuMatrix::getSum() {
  CHECK(isContiguous());
  real sum = 0.0f;
  hl_vector_sum(data_, &sum, height_ * width_);
  return sum;
}

279 280 281 282 283 284 285 286 287 288 289 290
real GpuMatrix::getMin() {
  CHECK(isContiguous());
  auto vec = GpuVector(height_ * width_, data_);
  return vec.getMin();
}

real GpuMatrix::getMax() {
  CHECK(isContiguous());
  auto vec = GpuVector(height_ * width_, data_);
  return vec.getMax();
}

Z
zhangjinchao01 已提交
291 292 293
void GpuMatrix::accumulateColSum(Matrix& src) {
  CHECK_EQ(getWidth(), src.getWidth());
  CHECK_EQ(getHeight(), (size_t)1);
X
xuwei06 已提交
294
  sumCols(src, 1.0, 1.0);
Z
zhangjinchao01 已提交
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
}

real GpuMatrix::getAbsSum() {
  CHECK(isContiguous());
  real sum = 0.0f;
  hl_vector_abs_sum(data_, &sum, height_ * width_);
  return sum;
}

void GpuMatrix::copyFrom(const Matrix& src) {
  CHECK(isContiguous());
  CHECK(src.isContiguous());
  CHECK(elementCnt_ == src.getElementCnt());

  if (typeid(src) == typeid(CpuMatrix)) {
310 311
    hl_memcpy_host2device(
        data_, const_cast<real*>(src.getData()), sizeof(real) * elementCnt_);
Z
zhangjinchao01 已提交
312
  } else if (typeid(src) == typeid(GpuMatrix)) {
313 314
    hl_memcpy_device2device(
        data_, const_cast<real*>(src.getData()), sizeof(real) * elementCnt_);
Z
zhangjinchao01 已提交
315 316 317 318 319 320 321 322 323
  } else {
    LOG(FATAL) << "Wrong";
  }
}

void GpuMatrix::copyFrom(const Matrix& src, hl_stream_t stream) {
  CHECK(isContiguous());
  CHECK(src.isContiguous());
  CHECK(elementCnt_ == src.getElementCnt());
324 325 326 327
  hl_memcpy_async(this->getData(),
                  const_cast<real*>(src.getData()),
                  sizeof(real) * elementCnt_,
                  stream);
Z
zhangjinchao01 已提交
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
}

void GpuMatrix::copyFrom(const real* hostSrc, size_t size) {
  CHECK(isContiguous());
  CHECK(size <= elementCnt_);
  hl_memcpy_host2device(data_, const_cast<real*>(hostSrc), sizeof(real) * size);
}

void GpuMatrix::copyFrom(const real* hostSrc, const int64_t* seq) {
  LOG(FATAL) << "not implemented";
}

void GpuMatrix::copyFrom(const IVector& src) {
  CHECK(isContiguous());
  CpuMatrix matrix(src.getSize(), 1, false);
  matrix.copyFrom(src);
  copyFrom(matrix);
}

347
void GpuMatrix::copyByRowIndex(Matrix& b, const IVector& rowIndex) {
Z
zhangjinchao01 已提交
348 349 350 351 352
  size_t height = getHeight();
  size_t width = getWidth();
  CHECK_EQ(b.getWidth(), width);
  real* dst = getData();
  real* src = b.getData();
353
  const int* index = rowIndex.getData();
Z
zhangjinchao01 已提交
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
  hl_sequence2batch_copy(dst, src, index, width, height, true);
}

MatrixPtr GpuMatrix::clone(size_t height, size_t width, bool useGpu) {
  CHECK(isContiguous());

  if (height == 0 && width == 0) {
    height = height_;
    width = width_;
  }

  CHECK(width && height);

  if (useGpu) {
    return std::make_shared<GpuMatrix>(height, width);
  } else {
    return std::make_shared<CpuMatrix>(height, width);
  }
}

MatrixPtr GpuMatrix::getTranspose() {
  if (memoryHandle_.get() != NULL) {
    MatrixPtr copy_T(
        new GpuMatrix(std::dynamic_pointer_cast<GpuMemoryHandle>(memoryHandle_),
378 379 380
                      height_,
                      width_,
                      true));
Z
zhangjinchao01 已提交
381 382 383 384 385 386 387
    return copy_T;
  } else {
    MatrixPtr copy_T(new GpuMatrix(data_, height_, width_, true));
    return copy_T;
  }
}

388
void GpuMatrix::transpose(MatrixPtr& matTrans, bool memAlloc) {
Z
zhangjinchao01 已提交
389 390 391 392
  if (memAlloc) {
    matTrans = std::make_shared<GpuMatrix>(width_, height_);
  } else {
    CHECK(matTrans != NULL);
H
Haonan 已提交
393 394
    CHECK_EQ(matTrans->getHeight(), width_);
    CHECK_EQ(matTrans->getWidth(), height_);
Z
zhangjinchao01 已提交
395 396 397 398 399 400 401 402 403
  }
  real* dataTrans = matTrans->getData();
  real* data = getData();
  int lda = getStride();
  int ldc = matTrans->getStride();

  hl_matrix_transpose(data, dataTrans, height_, width_, lda, ldc);
}

404 405 406 407 408
void GpuMatrix::rotate(MatrixPtr& matRot, bool memAlloc, bool clockWise) {
  if (memAlloc) {
    matRot = std::make_shared<GpuMatrix>(width_, height_);
  } else {
    CHECK(matRot != NULL);
H
Haonan 已提交
409 410
    CHECK_EQ(matRot->getHeight(), width_);
    CHECK_EQ(matRot->getWidth(), height_);
411 412
  }

H
Haonan 已提交
413 414 415
  real* dataRot = matRot->getData();
  real* data = getData();
  hl_matrix_rotate(data, dataRot, height_, width_, clockWise);
416 417
}

L
lzhao4ever 已提交
418 419 420 421 422 423
MatrixPtr GpuMatrix::getInverse() {
  MatrixPtr matInv;
  inverse(matInv, true);
  return matInv;
}

424
void GpuMatrix::inverse(MatrixPtr& matInv, bool memAlloc) {
L
lzhao4ever 已提交
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
  CHECK_EQ(height_, width_);

  if (memAlloc) {
    matInv = std::make_shared<GpuMatrix>(height_, width_);
  } else {
    CHECK(matInv != NULL);
  }

  real* data = getData();
  real* dataInv = matInv->getData();
  int lda = getStride();
  int ldc = matInv->getStride();

  hl_matrix_inverse(data, dataInv, height_, lda, ldc);
}

Z
zhangjinchao01 已提交
441 442 443 444 445
void GpuMatrix::addBias(Matrix& b, real scale) {
  CHECK(b.getHeight() == 1) << "the Bias should be a vector";
  BaseMatrix::addBias(b, scale);
}

446 447 448 449
void GpuMatrix::addSharedBias(Matrix& b, real scale) {
  CHECK(b.getHeight() == 1) << "the Bias should be a vector";
  CHECK_LE(b.getWidth(), getWidth());
  CHECK_EQ(getWidth() % b.getWidth(), 0UL);
450 451
  hl_matrix_add_shared_bias(
      getData(), b.getData(), b.getWidth(), getHeight(), getWidth(), scale);
452 453
}

Z
zhangjinchao01 已提交
454
void GpuMatrix::collectBias(Matrix& a, real scale) {
455
#ifdef PADDLE_WITH_CUDA
Z
zhangjinchao01 已提交
456 457
  CHECK_EQ(getHeight(), (size_t)1);
  CHECK_EQ(width_, a.getWidth());
Q
qijun 已提交
458
  GpuSparseMatrix* sMatPtr = dynamic_cast<GpuSparseMatrix*>(&a);
Z
zhangjinchao01 已提交
459
  if (!sMatPtr) {
460
    sumCols(a, /* scaleSum= */ scale, /* scaleDest= */ 1);
Z
zhangjinchao01 已提交
461 462 463
  } else {
    real* data = getData();
    hl_sparse_matrix_s A_d = sMatPtr->sMatrix_.get();
Q
qijun 已提交
464
    hl_sparse_matrix_column_sum(data, A_d, sMatPtr->getHeight(), width_, scale);
Z
zhangjinchao01 已提交
465
  }
466
#endif
Z
zhangjinchao01 已提交
467 468
}

469 470 471
void GpuMatrix::collectSharedBias(Matrix& a, real scale) {
  CHECK_EQ(getHeight(), (size_t)1);
  CHECK_EQ(a.getWidth() % getWidth(), 0UL);
472 473
  hl_matrix_collect_shared_bias(
      getData(), a.getData(), getWidth(), a.getHeight(), a.getWidth(), scale);
474 475
}

Z
zhangjinchao01 已提交
476 477 478 479 480 481 482 483 484 485 486 487 488 489
void GpuMatrix::sequenceAvgForward(Matrix& a,
                                   const IVector& startsPos,
                                   int mode) {
  size_t height = getHeight();
  size_t width = getWidth();
  CHECK_EQ(height, startsPos.getSize() - 1);
  CHECK_EQ(width, a.getWidth());
  real* dst = getData();
  real* src = a.getData();
  const int* starts = startsPos.getData();

  hl_sequence_avg_forward(dst, src, starts, height, width, mode);
}

L
Luo Tao 已提交
490 491 492 493 494 495 496 497 498 499 500 501 502 503
void GpuMatrix::sequenceAvgBackward(Matrix& a,
                                    const IVector& startsPos,
                                    int mode) {
  size_t height = a.getHeight();
  size_t width = getWidth();
  CHECK_EQ(height, startsPos.getSize() - 1);
  CHECK_EQ(width, a.getWidth());
  real* dst = getData();
  real* src = a.getData();
  const int* starts = startsPos.getData();

  hl_sequence_avg_backward(dst, src, starts, height, width, mode);
}

Z
zhangjinchao01 已提交
504
/* this = scaleAB*(a*b) +  scaleT*this */
505 506 507
void GpuMatrix::mul(const GpuMatrix& a,
                    const GpuMatrix& b,
                    real scaleAB,
Z
zhangjinchao01 已提交
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
                    real scaleT) {
  CHECK(!isTransposed()) << "Not supported";

  if (!a.isTransposed() && !b.isTransposed()) {
    CHECK_EQ(width_, b.width_);
    CHECK_EQ(height_, a.height_);
    CHECK_EQ(a.width_, b.height_);
  } else if (a.isTransposed() && !b.isTransposed()) {
    CHECK_EQ(width_, b.width_);
    CHECK_EQ(height_, a.width_);
    CHECK_EQ(a.height_, b.height_);
  } else if (!a.isTransposed() && b.isTransposed()) {
    CHECK_EQ(width_, b.height_);
    CHECK_EQ(height_, a.height_);
    CHECK_EQ(a.width_, b.width_);
  } else {
    LOG(FATAL) << "Is not supported";
  }

  real* A_d = a.data_;
  real* B_d = b.data_;
  real* C_d = data_;
  int dimM = getHeight();
  int dimN = getWidth();
  int dimK = !a.isTransposed() ? a.width_ : a.height_;
  int lda = a.getStride();
  int ldb = b.getStride();
  int ldc = getStride();
  hl_trans_op_t transa = !a.isTransposed() ? HPPL_OP_N : HPPL_OP_T;
  hl_trans_op_t transb = !b.isTransposed() ? HPPL_OP_N : HPPL_OP_T;

539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
  hl_matrix_mul(A_d,
                transa,
                B_d,
                transb,
                C_d,
                dimM,
                dimN,
                dimK,
                scaleAB,
                scaleT,
                lda,
                ldb,
                ldc);
}

void GpuMatrix::mul(const GpuSparseMatrix& a,
                    const GpuMatrix& b,
                    real scaleAB,
Z
zhangjinchao01 已提交
557
                    real scaleT) {
558
#ifdef PADDLE_WITH_CUDA
Z
zhangjinchao01 已提交
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
  CHECK(isContiguous());
  CHECK(b.isContiguous());
  CHECK(b.useGpu_ == true) << "Matrix type are not equal";
  CHECK(!trans_ && !b.trans_) << "not supported";

  if (!a.trans_) {
    CHECK(width_ == b.width_ && height_ == a.height_ && a.width_ == b.height_)
        << "Matrix dimensions are not equal";
  } else {
    CHECK(width_ == b.width_ && height_ == a.width_ && a.height_ == b.height_)
        << "Matrix dimensions are not equal";
  }
  hl_trans_op_t transA = a.trans_ ? HPPL_OP_T : HPPL_OP_N;
  hl_sparse_matrix_s A_d = a.sMatrix_.get();
  real* B_d = b.data_;
  real* C_d = data_;
575 576 577 578 579 580 581 582 583 584
  hl_matrix_csr_mul_dense(A_d,
                          transA,
                          B_d,
                          HPPL_OP_N,
                          C_d,
                          height_,
                          width_,
                          b.height_,
                          scaleAB,
                          scaleT);
585
#endif
586 587 588 589 590
}

void GpuMatrix::mul(const GpuMatrix& a,
                    const GpuSparseMatrix& b,
                    real scaleAB,
Z
zhangjinchao01 已提交
591
                    real scaleT) {
592
#ifdef PADDLE_WITH_CUDA
Z
zhangjinchao01 已提交
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
  CHECK(isContiguous());
  CHECK(a.isContiguous());
  CHECK(a.useGpu_ == true) << "Matrix type are not equal";

  hl_sparse_matrix_s B_d = b.sMatrix_.get();
  real* A_d = a.data_;
  real* C_d = data_;
  hl_trans_op_t transB = b.trans_ ? HPPL_OP_T : HPPL_OP_N;
  if (!b.trans_) {
    CHECK(width_ == b.width_ && height_ == a.height_ && a.width_ == b.height_)
        << "Matrix dimensions are not equal";
  } else {
    CHECK(width_ == b.height_ && height_ == a.height_ && a.width_ == b.width_)
        << "Matrix dimensions are not equal";
  }
  if (b.format_ == SPARSE_CSC) {
609 610 611 612 613 614 615 616 617 618
    hl_matrix_dense_mul_csc(A_d,
                            HPPL_OP_N,
                            B_d,
                            transB,
                            C_d,
                            height_,
                            width_,
                            a.width_,
                            scaleAB,
                            scaleT);
Z
zhangjinchao01 已提交
619
  } else {
620 621 622 623 624 625 626 627 628 629
    hl_matrix_dense_mul_csr(A_d,
                            HPPL_OP_N,
                            B_d,
                            transB,
                            C_d,
                            height_,
                            width_,
                            a.width_,
                            scaleAB,
                            scaleT);
Z
zhangjinchao01 已提交
630
  }
631
#endif
Z
zhangjinchao01 已提交
632 633 634
}

/* this = a*b */
635
void GpuMatrix::mul(const Matrix& a, const Matrix& b) { mul(a, b, 1.0, 0.0); }
Z
zhangjinchao01 已提交
636

637 638
void GpuMatrix::mul(const Matrix& a,
                    const Matrix& b,
639
                    real scaleAB,
Z
zhangjinchao01 已提交
640
                    real scaleT) {
641 642 643 644
  const auto a_ptr = dynamic_cast<const GpuMatrix*>(&a);
  const auto b_ptr = dynamic_cast<const GpuMatrix*>(&b);
  const auto a_ptr_s = dynamic_cast<const GpuSparseMatrix*>(&a);
  const auto b_ptr_s = dynamic_cast<const GpuSparseMatrix*>(&b);
Z
zhangjinchao01 已提交
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679

  if (a_ptr && b_ptr) {
    mul(*a_ptr, *b_ptr, scaleAB, scaleT);
  } else if (a_ptr_s && b_ptr) {
    mul(*a_ptr_s, *b_ptr, scaleAB, scaleT);
  } else if (a_ptr && b_ptr_s) {
    mul(*a_ptr, *b_ptr_s, scaleAB, scaleT);
  } else {
    LOG(FATAL) << "Not supported";
  }
}

/* this = this* b */
void GpuMatrix::rightMul(Matrix& b) { rightMul(b, 1.0, 0.0); }

/* this = scaleAB*(this*b) +  scaleT*this */
void GpuMatrix::rightMul(Matrix& b, real scaleAB, real scaleT) {
  CHECK(dynamic_cast<GpuMatrix*>(&b));
  CHECK(!isTransposed()) << "Not supported";
  CHECK(!b.isTransposed()) << "Not supported";
  mul(*this, *dynamic_cast<GpuMatrix*>(&b), scaleAB, scaleT);
}

/* this = a*this */
void GpuMatrix::leftMul(Matrix& a) { leftMul(a, 1.0, 0.0); }

/* this = scaleAB*(a*this) +  scaleT*this */
void GpuMatrix::leftMul(Matrix& a, real scaleAB, real scaleT) {
  CHECK(dynamic_cast<GpuMatrix*>(&a));
  CHECK(!isTransposed()) << "Not supported";
  CHECK(!a.isTransposed()) << "Not supported";
  mul(*dynamic_cast<GpuMatrix*>(&a), *this, scaleAB, scaleT);
}

void GpuMatrix::selectRows(Matrix& table, IVector& ids) {
680
#ifdef PADDLE_WITH_CUDA
Z
zhangjinchao01 已提交
681 682 683 684 685 686 687 688 689 690 691
  CHECK(dynamic_cast<GpuMatrix*>(&table));
  CHECK(table.useGpu());
  CHECK(ids.useGpu());
  CHECK_EQ(getHeight(), ids.getSize());
  CHECK_EQ(getWidth(), table.getWidth());
  size_t numSamples = getHeight();
  size_t dim = getWidth();
  real* a = getData();
  size_t tableSize = table.getHeight();
  int* index = ids.getData();

692 693 694 695 696 697 698 699
  hl_matrix_select_rows(a,
                        stride_,
                        table.getData(),
                        table.stride_,
                        index,
                        numSamples,
                        tableSize,
                        dim);
Z
zhangjinchao01 已提交
700 701 702 703
#endif
}

void GpuMatrix::addToRows(Matrix& table, IVector& ids) {
704
#ifdef PADDLE_WITH_CUDA
Z
zhangjinchao01 已提交
705 706 707 708 709 710 711 712 713 714 715
  CHECK(dynamic_cast<GpuMatrix*>(&table));
  CHECK(table.useGpu());
  CHECK(ids.useGpu());
  CHECK_EQ(getHeight(), ids.getSize());
  CHECK_EQ(getWidth(), table.getWidth());
  size_t numSamples = getHeight();
  size_t dim = getWidth();
  real* a = getData();
  size_t tableSize = table.getHeight();
  int* index = ids.getData();

716 717 718 719 720 721 722 723
  hl_matrix_add_to_rows(table.getData(),
                        table.stride_,
                        a,
                        stride_,
                        index,
                        numSamples,
                        tableSize,
                        dim);
Z
zhangjinchao01 已提交
724 725 726 727 728 729
#endif
}

void GpuMatrix::colMerge(Matrix& src) {
  CHECK(src.height_ == height_);
  if (!trans_ && !src.trans_) {
730
    sumRows(src, /* scaleSum= */ 1, /* scaleDest= */ 0);
Z
zhangjinchao01 已提交
731 732 733 734 735 736 737 738 739
  } else {
    LOG(FATAL) << "Is not supported";
  }
}

void GpuMatrix::rowSum(Matrix& sum) {
  CHECK_EQ(sum.getHeight(), getHeight());
  CHECK_EQ(sum.getWidth(), (size_t)1);

740
  sum.sumRows(*this, /* scaleSum= */ 1, /* scaleDest= */ 0);
Z
zhangjinchao01 已提交
741 742 743 744 745 746 747 748 749 750
}

void GpuMatrix::rowMax(Matrix& max) {
  CHECK_EQ(max.getHeight(), getHeight());
  CHECK_EQ(max.getWidth(), (size_t)1);

  max.maxRows(*this);
}

void GpuMatrix::rowMax(IVector& maxIds, Matrix& maxVal) {
751
#ifdef PADDLE_WITH_CUDA
Z
zhangjinchao01 已提交
752 753 754 755 756
  CHECK(maxIds.useGpu() && maxVal.useGpu()) << "Matrix type are not equal";
  size_t numSamples = getHeight();
  size_t beam = maxVal.getWidth();
  CHECK_EQ(maxIds.getSize(), numSamples * beam);
  CHECK_EQ(maxVal.getHeight(), numSamples);
L
Liang Zhao 已提交
757
  CHECK_EQ(maxVal.getWidth(), beam);
Z
zhangjinchao01 已提交
758

759 760 761 762 763 764 765
  hl_matrix_top_k(maxVal.getData(),
                  maxVal.getStride(),
                  maxIds.getData(),
                  this->getData(),
                  this->getStride(),
                  this->getWidth(),
                  beam,
Z
zhangjinchao01 已提交
766 767 768 769 770 771 772 773 774 775 776
                  numSamples);
#endif
}

void GpuMatrix::colMax(Matrix& max) {
  CHECK_EQ(max.getWidth(), getWidth());
  CHECK_EQ(max.getHeight(), (size_t)1);

  max.maxCols(*this);
}

777 778 779 780
void GpuMatrix::colMax(IVector& maxIds, Matrix& maxVal) {
  LOG(FATAL) << "Is not supported";
}

781 782 783
void GpuMatrix::maxoutForward(Matrix& a,
                              IVector& id,
                              size_t channels,
784 785 786 787 788 789 790
                              size_t groups) {
  CHECK(dynamic_cast<GpuMatrix*>(&a));
  CHECK(dynamic_cast<GpuIVector*>(&id));
  CHECK_EQ(a.getHeight(), getHeight());

  size_t size = getWidth();
  size_t batchSize = getHeight();
Q
qijun 已提交
791
  const real* input = a.getData();
792 793 794
  real* output = getData();
  int* idForGpu = id.getData();

795 796
  hl_maxout_forward(
      input, output, idForGpu, batchSize, size, size / channels, groups);
797 798
}

799 800 801
void GpuMatrix::maxoutBackward(Matrix& a,
                               IVector& id,
                               size_t channels,
802 803 804 805 806 807 808
                               size_t groups) {
  CHECK(dynamic_cast<GpuMatrix*>(&a));
  CHECK(dynamic_cast<GpuIVector*>(&id));
  CHECK_EQ(a.getHeight(), getHeight());

  size_t size = a.getWidth();
  size_t batchSize = getHeight();
Q
qijun 已提交
809
  real* input = getData();
810 811 812
  const real* output = a.getData();
  const int* idForGpu = id.getData();

813 814
  hl_maxout_backward(
      input, output, idForGpu, batchSize, size, size / channels, groups);
815 816
}

Z
zhangjinchao01 已提交
817
/*calulate the error of classification */
818 819 820 821 822 823 824 825 826 827 828 829 830
void GpuMatrix::classificationError(Matrix& output,
                                    IVector& label,
                                    size_t topkSize) {
  auto gpuOutput = dynamic_cast<GpuMatrix*>(&output);
  auto gpuLabel = dynamic_cast<GpuIVector*>(&label);
  size_t numSamples = this->getHeight();
  GpuMatrixPtr gpuTopVal = std::make_shared<GpuMatrix>(numSamples, topkSize);
  GpuIVectorPtr gpuTopIds = std::make_shared<GpuIVector>(numSamples * topkSize);

  CHECK(gpuOutput && gpuLabel) << "Invalid argument pointer";
  CHECK(gpuTopVal && gpuTopIds) << "Allocate GPU memory failed";
  CHECK(gpuLabel->getSize() == numSamples) << "Vector size is not equal";
  CHECK(numSamples == gpuOutput->getHeight() && this->getWidth() == 1)
Z
zhangjinchao01 已提交
831 832
      << "Matrix dimensions are not equal";

833 834 835 836 837 838 839 840 841 842 843
  size_t dim = gpuOutput->getWidth();
  hl_matrix_classification_error(gpuTopVal->getData(),
                                 gpuTopVal->getStride(),
                                 gpuTopIds->getData(),
                                 gpuOutput->getData(),
                                 gpuOutput->getStride(),
                                 dim,
                                 topkSize,
                                 numSamples,
                                 gpuLabel->getData(),
                                 this->getData());
Z
zhangjinchao01 已提交
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
}

/* copy -log(output[i * width + label]) to this->data[i] */
void GpuMatrix::oneHotCrossEntropy(Matrix& output, IVector& label) {
  GpuMatrix* output_ptr = dynamic_cast<GpuMatrix*>(&output);
  GpuIVector* label_ptr = dynamic_cast<GpuIVector*>(&label);

  CHECK(output_ptr && label_ptr) << "Invalid argument pointer";

  CHECK(height_ == label.getSize() && width_ == 1 && height_ == output.height_)
      << "Matrix dimensions are not equal";

  real* A_d = output_ptr->data_;
  real* C_d = data_;
  int* label_d = label_ptr->getData();

  hl_matrix_cross_entropy(A_d, C_d, label_d, height_, output.width_);
}

/* calculate the error of outputV according to label */
void GpuMatrix::oneHotCrossEntropyBp(Matrix& outputV, IVector& label) {
  GpuMatrix* output_ptr = dynamic_cast<GpuMatrix*>(&outputV);
  GpuIVector* label_ptr = dynamic_cast<GpuIVector*>(&label);

  CHECK(output_ptr && label_ptr) << "Invalid argument pointer";

  CHECK(height_ == output_ptr->height_ && width_ == output_ptr->width_)
      << "Matrix dimensions are not equal";

  real* output_d = output_ptr->data_;
  real* grad_d = data_;
  int* label_d = label_ptr->getData();

  hl_matrix_cross_entropy_bp(grad_d, output_d, label_d, height_, width_);
}

880 881
void GpuMatrix::oneHotCrossEntropyWithSelfNorm(Matrix& output,
                                               IVector& label,
Z
zhangjinchao01 已提交
882 883 884 885 886
                                               real alpha) {
  LOG(FATAL) << "Not implemented";
}

void GpuMatrix::oneHotCrossEntropyWithSelfNormBp(Matrix& outputV,
887 888
                                                 IVector& label,
                                                 real alpha) {
Z
zhangjinchao01 已提交
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
  LOG(FATAL) << "Not implemented";
}

void GpuMatrix::softmax(Matrix& output) {
  CHECK(output.useGpu()) << "Matrix type are not equal";

  size_t height = getHeight();
  size_t width = getWidth();
  CHECK(height == output.getHeight() && width == output.getWidth())
      << "Matrix dimensions are not equal";

  real* inputData = getData();
  real* outputData = output.getData();
  hl_matrix_softmax(inputData, outputData, height, width);
}

void GpuMatrix::sequenceSoftmax(Matrix& output, const IVector& index) {
  CHECK_EQ(getWidth(), 1UL);
  CHECK_EQ(output.getWidth(), 1UL);
  CHECK(isContiguous());

  real* inputData = getData();
  real* outputData = output.getData();
  auto starts = index.getData();
  int numSequences = index.getSize() - 1;
Q
qijun 已提交
914
  hl_sequence_softmax_forward(inputData, outputData, starts, numSequences);
Z
zhangjinchao01 已提交
915 916 917 918 919 920 921 922 923 924 925 926 927
}

void GpuMatrix::softmaxDerivative(Matrix& output, Matrix& sftmaxSum) {
  CHECK(output.useGpu_ == true && sftmaxSum.useGpu_ == true)
      << "Matrix type are not equal";

  CHECK(height_ == output.height_ && width_ == output.width_ &&
        height_ == sftmaxSum.height_)
      << "Matrix dimensions are not equal";

  real* output_d = output.data_;
  real* sftmaxSum_d = sftmaxSum.data_;
  real* grad_d = data_;
Q
qijun 已提交
928
  hl_matrix_softmax_derivative(grad_d, output_d, sftmaxSum_d, height_, width_);
Z
zhangjinchao01 已提交
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
}

void GpuMatrix::softmaxBackward(Matrix& outputV) {
  CHECK(outputV.useGpu()) << "Matrix type are not equal";

  size_t height = getHeight();
  size_t width = getWidth();
  CHECK(height == outputV.getHeight() && width == outputV.getWidth())
      << "Matrix dimensions are not equal";

  real* output_grad = getData();
  real* output_value = outputV.getData();
  hl_softmax_backward(output_value, output_grad, height, width);
}

void GpuMatrix::sumOfSquares(Matrix& output, Matrix& label) {
  CHECK_EQ(label.getHeight(), height_);
  CHECK_EQ(output.getHeight(), height_);
  CHECK_EQ(label.getWidth(), output.getWidth());
  CHECK_EQ((size_t)1, width_);

  auto labelptr = dynamic_cast<GpuSparseMatrix*>(&label);
  if (labelptr) {
    LOG(FATAL) << "not supported: GpuSparseMatrix as label";
  }

955 956 957 958
  BaseMatrix::sumOfSquaredDiffs(output,
                                label,
                                /* scaleSum= */ 1,
                                /* scaleDest= */ 1);
Z
zhangjinchao01 已提交
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
}

void GpuMatrix::sumOfSquaresBp(Matrix& outputV, Matrix& label) {
  add2(outputV, label, 1, 2, -2);
}

void GpuMatrix::tanh(Matrix& output) { BaseMatrix::tanh(output); }

void GpuMatrix::tanhDerivative(Matrix& output) {
  BaseMatrix::tanhDerivative(output);
}

void GpuMatrix::softrelu(Matrix& output) { BaseMatrix::softrelu(output); }

void GpuMatrix::softreluDerivative(Matrix& output) {
  BaseMatrix::softreluDerivative(output);
}

void GpuMatrix::scaledTanh(Matrix& output, real p1, real p2) {
  BaseMatrix::scaledTanh(output, p1, p2);
}

void GpuMatrix::randomizeUniform() {
  CHECK(isContiguous());
  real* data = data_;
  size_t size = height_ * width_;

  hl_rand(data, size);
}

void GpuMatrix::print(std::ostream& os) const {
  CHECK(isContiguous());
  CpuMatrix cpuMat(getHeight(), getWidth());
  cpuMat.copyFrom(*this);
  cpuMat.print(os);
}

void GpuMatrix::print(std::ostream& os, size_t height, size_t width) const {
  CHECK(isContiguous());
  CpuMatrix cpuMat(getHeight(), getWidth());
  cpuMat.copyFrom(*this);
  cpuMat.print(os, height, width);
}

void GpuMatrix::check(std::ostream& os, Matrix& refMat, bool printDiff) {
  CHECK(isContiguous());
  CHECK(height_ == refMat.getHeight());
  CHECK(width_ == refMat.getWidth());
  CpuMatrix cpuRef(height_, width_);
  GpuMatrix gpuRef(height_, width_);
  cpuRef.copyFrom(refMat);
  gpuRef.copyFrom(*this);
  size_t diffCnt = 0;
  for (size_t i = 0; i < height_; ++i) {
    for (size_t j = 0; j < width_; ++j) {
      real a = gpuRef.getElement(i, j);
      real b = cpuRef.getElement(i, j);
      if (fabs(a - b) > 0.00001) {
        ++diffCnt;
        if (printDiff) {
          os << "ref= " << a << "  check= " << b << std::endl;
        }
      }
    }
  }
  LOG(INFO) << "the  diffCnt is " << diffCnt;
}

X
xzl 已提交
1027
void GpuMatrix::upsampleForward(Matrix& input,
X
xzl 已提交
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
                                Matrix& mask,
                                size_t imgSizeH,
                                size_t imgSizeW,
                                size_t channels,
                                size_t outputH,
                                size_t outputW) {
  CHECK(input.useGpu_ == true) << "Matrix type are not equal";
  CHECK(mask.useGpu_ == true) << "Matrix type are not equal";

  real* inputData = input.getData();
  real* maskData = mask.getData();
  real* outData = data_;

  size_t batch = input.getHeight();

  CHECK(imgSizeH * imgSizeW * channels == input.getWidth());
  CHECK(imgSizeH * imgSizeW * channels == mask.getWidth());
  CHECK_EQ(batch, this->getHeight());
  CHECK(width_ == outputH * outputW * channels);
  hl_upsample_forward(inputData,
                      maskData,
                      batch,
                      imgSizeH,
                      imgSizeW,
                      channels,
                      outputH,
                      outputW,
                      outData);
X
xzl 已提交
1056 1057 1058
}

void GpuMatrix::upsampleBackward(Matrix& outputGrad,
X
xzl 已提交
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
                                 Matrix& mask,
                                 size_t imgSizeH,
                                 size_t imgSizeW,
                                 size_t channels,
                                 size_t outputH,
                                 size_t outputW) {
  CHECK(outputGrad.useGpu_ == true) << "Matrix type are not equal";
  CHECK(mask.useGpu_ == true) << "Matrix type are not equal";

  real* outputGradData = outputGrad.getData();
  real* maskData = mask.getData();
  real* inputGradData = data_;
  size_t batch = outputGrad.getHeight();

  CHECK(imgSizeH * imgSizeW == this->getWidth() / channels);
  CHECK_EQ(batch, this->getHeight());
  CHECK_EQ(channels * outputH * outputW, outputGrad.getWidth());
  hl_upsample_backward(outputGradData,
                       maskData,
                       batch,
                       imgSizeH,
                       imgSizeW,
                       channels,
                       outputH,
                       outputW,
                       inputGradData);
X
xzl 已提交
1085 1086
}

X
xzl 已提交
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
void GpuMatrix::maxPoolForward(Matrix& inputMat,
                               size_t imgSizeH,
                               size_t imgSizeW,
                               size_t channels,
                               size_t sizeX,
                               size_t sizeY,
                               size_t strideH,
                               size_t strideW,
                               size_t outputH,
                               size_t outputW,
                               size_t paddingH,
                               size_t paddingW,
1099
                               MatrixPtr maskMatP) {
Z
zhangjinchao01 已提交
1100 1101 1102
  CHECK(inputMat.useGpu_ == true) << "Matrix type are not equal";

  real* inputData = inputMat.getData();
X
xzl 已提交
1103
  real* maskData = NULL;
Z
zhangjinchao01 已提交
1104
  size_t frameNum = inputMat.getHeight();
1105
  CHECK(imgSizeH * imgSizeW * channels == inputMat.getWidth());
Z
zhangjinchao01 已提交
1106 1107 1108
  CHECK(height_ == inputMat.getHeight());
  CHECK(width_ == outputH * outputW * channels);

1109
  if (maskMatP != NULL) {
X
xzl 已提交
1110 1111 1112 1113 1114
    CHECK(maskMatP->useGpu_ == true) << "Matrix type are not equal";
    CHECK(outputH * outputW * channels == maskMatP->getWidth());
    maskData = maskMatP->getData();
  }

1115 1116 1117
  hl_maxpool_forward(frameNum,
                     inputData,
                     channels,
1118 1119
                     imgSizeH,
                     imgSizeW,
1120 1121 1122 1123 1124 1125 1126 1127 1128
                     outputH,
                     outputW,
                     sizeX,
                     sizeY,
                     strideH,
                     strideW,
                     paddingH,
                     paddingW,
                     data_,
X
xzl 已提交
1129
                     getStride(),
1130
                     maskData);
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
}

void GpuMatrix::maxPoolBackward(Matrix& inputMat,
                                size_t imgSizeH,
                                size_t imgSizeW,
                                Matrix& outGrad,
                                Matrix& outV,
                                size_t sizeX,
                                size_t sizeY,
                                size_t strideH,
                                size_t strideW,
                                size_t outputH,
                                size_t outputW,
                                real scaleTargets,
                                real scaleOutput,
                                size_t paddingH,
                                size_t paddingW) {
Z
zhangjinchao01 已提交
1148 1149 1150 1151 1152 1153 1154 1155 1156
  CHECK(inputMat.useGpu_ == true && outGrad.useGpu_ == true &&
        outV.useGpu_ == true)
      << "Matrix type are not equal";

  real* inputData = inputMat.getData();
  real* outData = outV.getData();
  real* outDiff = outGrad.getData();
  size_t frameNum = inputMat.getHeight();
  size_t channels = outV.getWidth() / outputH / outputW;
1157
  CHECK(imgSizeH * imgSizeW * channels == inputMat.getWidth());
Z
zhangjinchao01 已提交
1158 1159 1160 1161
  CHECK(height_ == inputMat.getHeight());
  CHECK(outGrad.getHeight() == outV.getHeight() &&
        outGrad.getWidth() == outV.getWidth());

1162 1163 1164 1165 1166
  hl_maxpool_backward(frameNum,
                      inputData,
                      outData,
                      outDiff,
                      channels,
1167 1168
                      imgSizeH,
                      imgSizeW,
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
                      outputH,
                      outputW,
                      sizeX,
                      sizeY,
                      strideH,
                      strideW,
                      paddingH,
                      paddingW,
                      scaleTargets,
                      scaleOutput,
                      data_,
Q
qijun 已提交
1180
                      outGrad.getStride());
Z
zhangjinchao01 已提交
1181 1182
}

1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
void GpuMatrix::avgPoolForward(Matrix& inputMat,
                               size_t imgSizeH,
                               size_t imgSizeW,
                               size_t channels,
                               size_t sizeX,
                               size_t sizeY,
                               size_t strideH,
                               size_t strideW,
                               size_t outputH,
                               size_t outputW,
                               size_t paddingH,
1194 1195
                               size_t paddingW,
                               bool excludeMode) {
Z
zhangjinchao01 已提交
1196 1197 1198 1199
  CHECK(inputMat.useGpu_ == true) << "Matrix type are not equal";

  real* inputData = inputMat.getData();
  size_t frameNum = inputMat.getHeight();
1200
  CHECK(imgSizeH * imgSizeW * channels == inputMat.getWidth());
Z
zhangjinchao01 已提交
1201 1202 1203
  CHECK(height_ == inputMat.getHeight());
  CHECK(width_ == outputH * outputW * channels);

1204 1205 1206
  hl_avgpool_forward(frameNum,
                     inputData,
                     channels,
1207 1208
                     imgSizeH,
                     imgSizeW,
1209 1210 1211 1212 1213 1214 1215 1216 1217
                     outputH,
                     outputW,
                     sizeX,
                     sizeY,
                     strideH,
                     strideW,
                     paddingH,
                     paddingW,
                     data_,
1218 1219
                     getStride(),
                     excludeMode);
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
}

void GpuMatrix::avgPoolBackward(Matrix& outGrad,
                                size_t imgSizeH,
                                size_t imgSizeW,
                                size_t sizeX,
                                size_t sizeY,
                                size_t strideH,
                                size_t strideW,
                                size_t outputH,
                                size_t outputW,
                                real scaleTargets,
                                real scaleOutput,
                                size_t paddingH,
1234 1235
                                size_t paddingW,
                                bool excludeMode) {
Z
zhangjinchao01 已提交
1236 1237 1238 1239 1240
  CHECK(outGrad.useGpu_ == true) << "Matrix type are not equal";

  real* outDiff = outGrad.getData();
  size_t frameNum = outGrad.getHeight();
  size_t channels = outGrad.getWidth() / outputH / outputW;
1241
  CHECK(imgSizeH * imgSizeW * channels == width_);
Z
zhangjinchao01 已提交
1242 1243 1244
  CHECK(height_ == outGrad.getHeight());
  CHECK(outGrad.getWidth() == outputH * outputW * channels);

1245 1246 1247
  hl_avgpool_backward(frameNum,
                      outDiff,
                      channels,
1248 1249
                      imgSizeH,
                      imgSizeW,
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
                      outputH,
                      outputW,
                      sizeX,
                      sizeY,
                      strideH,
                      strideW,
                      paddingH,
                      paddingW,
                      scaleTargets,
                      scaleOutput,
                      data_,
1261 1262
                      outGrad.getStride(),
                      excludeMode);
Z
zhangjinchao01 已提交
1263 1264
}

C
chengduoZH 已提交
1265
void GpuMatrix::maxPool3DForward(Matrix& inputMat,
C
chengduoZH 已提交
1266
                                 Matrix& maxPoolIdx,
C
chengduoZH 已提交
1267
                                 size_t channels,
C
chengduoZH 已提交
1268 1269 1270
                                 size_t imgSizeD,
                                 size_t imgSizeH,
                                 size_t imgSizeW,
C
chengduoZH 已提交
1271 1272 1273
                                 size_t outputD,
                                 size_t outputH,
                                 size_t outputW,
C
chengduoZH 已提交
1274 1275 1276 1277 1278 1279 1280 1281 1282
                                 size_t sizeZ,
                                 size_t sizeY,
                                 size_t sizeX,
                                 size_t strideD,
                                 size_t strideH,
                                 size_t strideW,
                                 size_t paddingD,
                                 size_t paddingH,
                                 size_t paddingW) {
C
chengduoZH 已提交
1283
  CHECK(inputMat.useGpu_) << "Matrix type are not correct";
C
chengduoZH 已提交
1284 1285

  real* inputData = inputMat.getData();
C
chengduoZH 已提交
1286
  real* maxPoolIdxData = maxPoolIdx.getData();
C
chengduoZH 已提交
1287
  size_t num = inputMat.getHeight();
1288
  CHECK(imgSizeD * imgSizeH * imgSizeW * channels == inputMat.getWidth());
C
chengduoZH 已提交
1289 1290 1291 1292 1293 1294
  CHECK(height_ == inputMat.getHeight());
  CHECK(width_ == outputD * outputH * outputW * channels);

  hl_maxpool3D_forward(num,
                       inputData,
                       channels,
1295 1296 1297
                       imgSizeD,
                       imgSizeH,
                       imgSizeW,
C
chengduoZH 已提交
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
                       outputD,
                       outputH,
                       outputW,
                       sizeZ,
                       sizeY,
                       sizeX,
                       strideD,
                       strideH,
                       strideW,
                       paddingD,
                       paddingH,
                       paddingW,
C
chengduoZH 已提交
1310
                       getData(),
C
chengduoZH 已提交
1311
                       maxPoolIdxData,
C
chengduoZH 已提交
1312 1313 1314
                       getStride());
}

C
chengduoZH 已提交
1315 1316
void GpuMatrix::maxPool3DBackward(Matrix& outGrad,
                                  Matrix& maxPoolIdx,
C
chengduoZH 已提交
1317 1318 1319
                                  size_t imgSizeD,
                                  size_t imgSizeH,
                                  size_t imgSizeW,
C
chengduoZH 已提交
1320 1321 1322
                                  size_t outputD,
                                  size_t outputH,
                                  size_t outputW,
C
chengduoZH 已提交
1323 1324 1325 1326 1327 1328 1329 1330
                                  size_t sizeZ,
                                  size_t sizeY,
                                  size_t sizeX,
                                  size_t strideD,
                                  size_t strideH,
                                  size_t strideW,
                                  size_t paddingD,
                                  size_t paddingH,
C
chengduoZH 已提交
1331 1332 1333
                                  size_t paddingW,
                                  real scaleTargets,
                                  real scaleOutput) {
C
chengduoZH 已提交
1334
  CHECK(outGrad.useGpu_ && maxPoolIdx.useGpu_) << "Matrix type are not equal";
C
chengduoZH 已提交
1335 1336

  real* outDiff = outGrad.getData();
C
chengduoZH 已提交
1337 1338 1339
  real* maxPoolIdxData = maxPoolIdx.getData();
  size_t frameNum = getHeight();
  size_t channels = outGrad.getWidth() / outputD / outputH / outputW;
1340
  CHECK(imgSizeD * imgSizeH * imgSizeW * channels == getWidth());
C
chengduoZH 已提交
1341 1342
  CHECK(outGrad.getHeight() == maxPoolIdx.getHeight() &&
        outGrad.getWidth() == maxPoolIdx.getWidth());
C
chengduoZH 已提交
1343 1344 1345 1346

  hl_maxpool3D_backward(frameNum,
                        outDiff,
                        channels,
1347 1348 1349
                        imgSizeD,
                        imgSizeH,
                        imgSizeW,
C
chengduoZH 已提交
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
                        outputD,
                        outputH,
                        outputW,
                        sizeZ,
                        sizeY,
                        sizeX,
                        strideD,
                        strideH,
                        strideW,
                        paddingD,
                        paddingH,
                        paddingW,
                        scaleTargets,
                        scaleOutput,
C
chengduoZH 已提交
1364
                        getData(),
C
chengduoZH 已提交
1365
                        maxPoolIdxData,
C
chengduoZH 已提交
1366 1367 1368 1369
                        outGrad.getStride());
}

void GpuMatrix::avgPool3DForward(Matrix& inputMat,
C
chengduoZH 已提交
1370
                                 size_t channels,
C
chengduoZH 已提交
1371 1372 1373
                                 size_t imgSizeD,
                                 size_t imgSizeH,
                                 size_t imgSizeW,
C
chengduoZH 已提交
1374 1375 1376
                                 size_t outputD,
                                 size_t outputH,
                                 size_t outputW,
C
chengduoZH 已提交
1377 1378 1379 1380 1381 1382 1383 1384 1385
                                 size_t sizeZ,
                                 size_t sizeY,
                                 size_t sizeX,
                                 size_t strideD,
                                 size_t strideH,
                                 size_t strideW,
                                 size_t paddingD,
                                 size_t paddingH,
                                 size_t paddingW) {
C
chengduoZH 已提交
1386
  CHECK(inputMat.useGpu_) << "Matrix type are not equal";
C
chengduoZH 已提交
1387 1388 1389

  real* inputData = inputMat.getData();
  size_t frameNum = inputMat.getHeight();
1390
  CHECK(imgSizeD * imgSizeH * imgSizeW * channels == inputMat.getWidth());
C
chengduoZH 已提交
1391 1392 1393 1394 1395 1396
  CHECK(height_ == inputMat.getHeight());
  CHECK(width_ == outputD * outputH * outputW * channels);

  hl_avgpool3D_forward(frameNum,
                       inputData,
                       channels,
1397 1398 1399
                       imgSizeD,
                       imgSizeH,
                       imgSizeW,
C
chengduoZH 已提交
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
                       outputD,
                       outputH,
                       outputW,
                       sizeZ,
                       sizeY,
                       sizeX,
                       strideD,
                       strideH,
                       strideW,
                       paddingD,
                       paddingH,
                       paddingW,
C
chengduoZH 已提交
1412
                       getData(),
C
chengduoZH 已提交
1413 1414 1415 1416 1417 1418 1419
                       getStride());
}

void GpuMatrix::avgPool3DBackward(Matrix& outGrad,
                                  size_t imgSizeD,
                                  size_t imgSizeH,
                                  size_t imgSizeW,
C
chengduoZH 已提交
1420 1421 1422
                                  size_t outputD,
                                  size_t outputH,
                                  size_t outputW,
C
chengduoZH 已提交
1423 1424 1425 1426 1427 1428 1429 1430
                                  size_t sizeZ,
                                  size_t sizeY,
                                  size_t sizeX,
                                  size_t strideD,
                                  size_t strideH,
                                  size_t strideW,
                                  size_t paddingD,
                                  size_t paddingH,
C
chengduoZH 已提交
1431 1432 1433 1434
                                  size_t paddingW,
                                  real scaleTargets,
                                  real scaleOutput) {
  CHECK(outGrad.useGpu_) << "Matrix type are not equal";
C
chengduoZH 已提交
1435 1436 1437 1438

  real* outDiff = outGrad.getData();
  size_t frameNum = outGrad.getHeight();
  size_t channels = outGrad.getWidth() / outputD / outputH / outputW;
1439
  CHECK(imgSizeD * imgSizeH * imgSizeW * channels == width_);
C
chengduoZH 已提交
1440 1441 1442 1443 1444 1445
  CHECK(height_ == outGrad.getHeight());
  CHECK(outGrad.getWidth() == outputD * outputH * outputW * channels);

  hl_avgpool3D_backward(frameNum,
                        outDiff,
                        channels,
1446 1447 1448
                        imgSizeD,
                        imgSizeH,
                        imgSizeW,
C
chengduoZH 已提交
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
                        outputD,
                        outputH,
                        outputW,
                        sizeZ,
                        sizeY,
                        sizeX,
                        strideD,
                        strideH,
                        strideW,
                        paddingD,
                        paddingH,
                        paddingW,
                        scaleTargets,
                        scaleOutput,
C
chengduoZH 已提交
1463
                        getData(),
C
chengduoZH 已提交
1464 1465 1466
                        outGrad.getStride());
}

1467 1468
void GpuMatrix::maxSequenceForward(Matrix& input,
                                   const IVector& sequence,
Z
zhangjinchao01 已提交
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
                                   IVector& index) {
  CHECK(dynamic_cast<GpuMatrix*>(&input));
  CHECK(dynamic_cast<const GpuIVector*>(&sequence));
  CHECK(dynamic_cast<GpuIVector*>(&index));

  real* outData = getData();
  real* inputData = input.getData();
  const int* starts = sequence.getData();
  int* maxIndex = index.getData();
  size_t numSequences = getHeight();
  size_t dim = getWidth();

  CHECK_EQ(dim, input.getWidth());
  CHECK_EQ(numSequences, sequence.getSize() - 1);
  CHECK_EQ(numSequences * dim, index.getSize());

1485 1486
  hl_max_sequence_forward(
      inputData, starts, outData, maxIndex, numSequences, dim);
Z
zhangjinchao01 已提交
1487 1488
}

1489 1490
void GpuMatrix::maxSequenceBackward(Matrix& outputGrad,
                                    const IVector& sequence,
Z
zhangjinchao01 已提交
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
                                    IVector& index) {
  CHECK(dynamic_cast<GpuMatrix*>(&outputGrad));
  CHECK(dynamic_cast<const GpuIVector*>(&sequence));
  CHECK(dynamic_cast<GpuIVector*>(&index));

  real* inputGrad = getData();
  real* outGrad = outputGrad.getData();
  int* maxIndex = index.getData();
  size_t dim = getWidth();
  size_t numSequences = sequence.getSize() - 1;

  CHECK_EQ(dim, outputGrad.getWidth());
  CHECK_EQ(numSequences, outputGrad.getHeight());
  CHECK_EQ(numSequences * dim, index.getSize());

  hl_max_sequence_backward(outGrad, maxIndex, inputGrad, numSequences, dim);
}

void GpuMatrix::paramReluForward(Matrix& data, Matrix& W) {
  CHECK(data.useGpu_ == true && W.useGpu_ == true)
      << "Matrix type are not equal";
  real* input = data.getData();
  real* w = W.getData();
  size_t numElements = data.getWidth();
  size_t numSamples = data.getHeight();
H
hedaoyuan 已提交
1516 1517 1518
  size_t paraSize = W.getHeight() * W.getWidth();
  CHECK(!(numElements % paraSize));  // this check from ParameterReluLayer::init
  size_t partial_sum = numElements / paraSize;
Z
zhangjinchao01 已提交
1519
  real* output = getData();
Q
qijun 已提交
1520
  hl_param_relu_forward(output, input, w, numElements, numSamples, partial_sum);
Z
zhangjinchao01 已提交
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
}

void GpuMatrix::paramReluBackwardW(Matrix& oGrad, Matrix& data) {
  CHECK(oGrad.useGpu_ == true && data.useGpu_ == true)
      << "Matrix type are not equal";
  real* ograd = oGrad.getData();
  real* input = data.getData();
  real* wgrad = data_;
  size_t numElements = data.getWidth();
  size_t numSamples = data.getHeight();
H
hedaoyuan 已提交
1531 1532 1533
  size_t paraSize = this->getHeight() * this->getWidth();
  CHECK(!(numElements % paraSize));  // this check from ParameterReluLayer::init
  size_t partial_sum = numElements / paraSize;
1534 1535
  hl_param_relu_backward_w(
      wgrad, ograd, input, numElements, numSamples, partial_sum);
Z
zhangjinchao01 已提交
1536 1537 1538 1539 1540 1541 1542 1543 1544
}

void GpuMatrix::paramReluBackwardDiff(Matrix& oGrad, Matrix& data, Matrix& W) {
  real* diff = data_;
  real* input = data.getData();
  real* ograd = oGrad.getData();
  real* w = W.getData();
  size_t numElements = data.getWidth();
  size_t numSamples = data.getHeight();
H
hedaoyuan 已提交
1545 1546 1547
  size_t paraSize = W.getHeight() * W.getWidth();
  CHECK(!(numElements % paraSize));  // this check from ParameterReluLayer::init
  size_t partial_sum = numElements / paraSize;
1548 1549
  hl_param_relu_backward_diff(
      ograd, input, w, diff, numElements, numSamples, partial_sum);
Z
zhangjinchao01 已提交
1550 1551 1552 1553 1554 1555
}

void GpuMatrix::addColumnVector(const Matrix& b) {
  BaseMatrix::addColVector(const_cast<Matrix&>(b));
}

L
liaogang 已提交
1556 1557 1558 1559 1560
void GpuMatrix::bilinearForward(const Matrix& in,
                                const size_t inImgH,
                                const size_t inImgW,
                                const size_t outImgH,
                                const size_t outImgW,
L
liaogang 已提交
1561 1562 1563
                                const size_t numChannels,
                                const real ratioH,
                                const real ratioW) {
L
liaogang 已提交
1564 1565 1566 1567 1568 1569 1570 1571
  CHECK(dynamic_cast<const GpuMatrix*>(&in));

  const size_t outputW = getWidth();
  const size_t outputH = getHeight();
  const size_t inputW = in.getWidth();
  const size_t inputH = in.getHeight();

  real* outData = getData();
1572
  const real* inData = in.getData();
L
liaogang 已提交
1573 1574 1575 1576

  if (inImgH == outImgW && inImgW == outImgW) {
    this->copyFrom(in);
  } else {
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
    hl_bilinear_forward(inData,
                        inImgH,
                        inImgW,
                        inputH,
                        inputW,
                        outData,
                        outImgH,
                        outImgW,
                        outputH,
                        outputW,
                        numChannels,
                        ratioH,
                        ratioW);
L
liaogang 已提交
1590 1591 1592 1593 1594 1595 1596 1597
  }
}

void GpuMatrix::bilinearBackward(const Matrix& out,
                                 const size_t outImgH,
                                 const size_t outImgW,
                                 const size_t inImgH,
                                 const size_t inImgW,
L
liaogang 已提交
1598 1599 1600
                                 const size_t numChannels,
                                 const real ratioH,
                                 const real ratioW) {
L
liaogang 已提交
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
  CHECK(dynamic_cast<const GpuMatrix*>(&out));

  const size_t inputW = getWidth();
  const size_t inputH = getHeight();
  const size_t outputW = out.getWidth();
  const size_t outputH = out.getHeight();

  real* inGrad = getData();
  const real* outGrad = out.getData();

  if (outImgH == inImgH && outImgW == inImgW) {
L
liaogang 已提交
1612
    this->add(const_cast<Matrix&>(out));
L
liaogang 已提交
1613
  } else {
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
    hl_bilinear_backward(inGrad,
                         inImgH,
                         inImgW,
                         inputH,
                         inputW,
                         outGrad,
                         outImgH,
                         outImgW,
                         outputH,
                         outputW,
                         numChannels,
                         ratioH,
                         ratioW);
L
liaogang 已提交
1627 1628 1629
  }
}

1630
void GpuMatrix::multiBinaryLabelCrossEntropy(Matrix& output, Matrix& label) {
1631
#ifdef PADDLE_WITH_CUDA
1632 1633 1634 1635 1636 1637 1638 1639 1640
  GpuMatrix* outputPtr = dynamic_cast<GpuMatrix*>(&output);
  auto labelPtr = dynamic_cast<GpuSparseMatrix*>(&label);

  CHECK(outputPtr && labelPtr) << "Invalid argument pointer";
  CHECK(labelPtr->format_ == SPARSE_CSR) << "Matrix format not supported";
  CHECK(height_ == outputPtr->height_ && width_ == 1 &&
        outputPtr->width_ == labelPtr->getWidth() &&
        outputPtr->height_ == labelPtr->getHeight())
      << "Matrix dimensions are not equal";
1641

1642 1643 1644 1645 1646
  real* output_d = outputPtr->data_;
  real* entropy_d = data_;
  hl_sparse_matrix_s mat_d = labelPtr->sMatrix_.get();
  hl_matrix_multi_binary_cross_entropy(
      output_d, entropy_d, mat_d, height_, outputPtr->width_);
1647
#endif
1648 1649
}

1650
void GpuMatrix::multiBinaryLabelCrossEntropyBp(Matrix& output, Matrix& label) {
1651
#ifdef PADDLE_WITH_CUDA
1652 1653
  GpuMatrix* outputPtr = dynamic_cast<GpuMatrix*>(&output);
  auto labelPtr = dynamic_cast<GpuSparseMatrix*>(&label);
H
Haonan 已提交
1654

1655 1656 1657 1658 1659 1660
  CHECK(outputPtr && labelPtr) << "Invalid argument pointer";
  CHECK(labelPtr->format_ == SPARSE_CSR) << "Matrix format not supported";
  CHECK(height_ == outputPtr->height_ && width_ == outputPtr->width_ &&
        outputPtr->width_ == labelPtr->getWidth() &&
        outputPtr->height_ == labelPtr->getHeight())
      << "Matrix dimensions are not equal";
1661

1662 1663 1664 1665 1666
  real* output_d = outputPtr->data_;
  real* grad_d = data_;
  hl_sparse_matrix_s mat_d = labelPtr->sMatrix_.get();
  hl_matrix_multi_binary_cross_entropy_bp(
      output_d, grad_d, mat_d, height_, width_);
1667
#endif
1668 1669
}

C
chengduoZH 已提交
1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730
void GpuMatrix::vol2Col(real* dataSrc,
                        int channels,
                        int depth,
                        int height,
                        int width,
                        int filterD,
                        int filterH,
                        int filterW,
                        int strideD,
                        int strideH,
                        int strideW,
                        int paddingD,
                        int paddingH,
                        int paddingW) {
  hl_matrix_vol2Col(dataSrc,
                    channels,
                    depth,
                    height,
                    width,
                    filterD,
                    filterH,
                    filterW,
                    strideD,
                    strideH,
                    strideW,
                    paddingD,
                    paddingH,
                    paddingW,
                    getData());
}

void GpuMatrix::col2Vol(real* dataDst,
                        int channels,
                        int depth,
                        int height,
                        int width,
                        int filterD,
                        int filterH,
                        int filterW,
                        int strideD,
                        int strideH,
                        int strideW,
                        int paddingD,
                        int paddingH,
                        int paddingW,
                        real alpha,
                        real beta) {
  hl_matrix_col2Vol(dataDst,
                    channels,
                    depth,
                    height,
                    width,
                    filterD,
                    filterH,
                    filterW,
                    strideD,
                    strideH,
                    strideW,
                    paddingD,
                    paddingH,
                    paddingW,
C
chengduoZH 已提交
1731
                    getData(),
C
chengduoZH 已提交
1732 1733 1734
                    alpha,
                    beta);
}
C
chengduoZH 已提交
1735

Z
zhangjinchao01 已提交
1736 1737 1738 1739 1740 1741
/**
 * CpuMatrix
 */

CpuMatrix::CpuMatrix(size_t height, size_t width, bool trans)
    : Matrix(std::make_shared<CpuMemoryHandle>(height * width * sizeof(real)),
1742 1743 1744 1745
             height,
             width,
             trans,
             false) {}
Z
zhangjinchao01 已提交
1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766

CpuMatrix::~CpuMatrix() {}

void CpuMatrix::zeroMem() {
  CHECK(data_ != NULL);
  if (isContiguous()) {
    memset(data_, 0, height_ * width_ * sizeof(real));
  } else {
    BaseMatrix::zero();
  }
}
void CpuMatrix::resetOne() {
  CHECK(data_ != NULL);
  BaseMatrix::one();
}

void CpuMatrix::copyFrom(const Matrix& src) {
  CHECK(isContiguous());
  if (typeid(src) == typeid(GpuMatrix)) {
    CHECK(src.isContiguous());
    CHECK(elementCnt_ == src.getElementCnt());
1767 1768
    hl_memcpy_device2host(
        data_, const_cast<real*>(src.getData()), sizeof(real) * elementCnt_);
1769 1770
  } else if (typeid(src) == typeid(CpuMatrix) ||
             typeid(src) == typeid(SharedCpuMatrix)) {
Z
zhangjinchao01 已提交
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832
    CHECK(src.isContiguous());
    CHECK(elementCnt_ == src.getElementCnt());
    memcpy(data_, src.getData(), sizeof(real) * elementCnt_);
  } else if (typeid(src) == typeid(CpuSparseMatrix)) {
    CHECK_GE(elementCnt_, src.getElementCnt());
    copyFrom(dynamic_cast<CpuSparseMatrix&>(const_cast<Matrix&>(src)));
  } else {
    LOG(FATAL) << "Wrong";
  }
}

void CpuMatrix::copyFrom(CpuSparseMatrix& src) {
  CHECK(isContiguous());
  CHECK(height_ == src.getHeight());
  CHECK(width_ == src.getWidth());
  memset(data_, 0, sizeof(real) * height_ * width_);
  if (src.getValueType() == FLOAT_VALUE) {
    if (src.getFormat() == SPARSE_CSC) {
      int* rows = src.getRows();
      real* vals = src.getValue();
      for (size_t i = 0; i < width_; i++) {
        for (size_t j = src.getColStartIdx(i); j < src.getColStartIdx(i + 1);
             j++) {
          data_[rows[j] * width_ + i] = vals[j];
        }
      }
    } else {
      int* cols = src.getCols();
      real* vals = src.getValue();
      for (size_t i = 0; i < height_; i++) {
        for (size_t j = src.getRowStartIdx(i); j < src.getRowStartIdx(i + 1);
             j++) {
          data_[i * width_ + cols[j]] = vals[j];
        }
      }
    }
  } else {
    if (src.getFormat() == SPARSE_CSC) {
      int* rows = src.getRows();
      for (size_t i = 0; i < width_; i++) {
        for (size_t j = src.getColStartIdx(i); j < src.getColStartIdx(i + 1);
             j++) {
          data_[rows[j] * width_ + i] = 1.0;
        }
      }
    } else {
      int* cols = src.getCols();
      for (size_t i = 0; i < height_; i++) {
        for (size_t j = src.getRowStartIdx(i); j < src.getRowStartIdx(i + 1);
             j++) {
          data_[i * width_ + cols[j]] = 1.0;
        }
      }
    }
  }
}

void CpuMatrix::copyFrom(const Matrix& src, hl_stream_t stream) {
  CHECK(isContiguous());
  CHECK(src.isContiguous());
  CHECK(elementCnt_ == src.getElementCnt());
  if (typeid(src) == typeid(GpuMatrix)) {
1833 1834 1835 1836
    hl_memcpy_async(this->getData(),
                    const_cast<real*>(src.getData()),
                    sizeof(real) * elementCnt_,
                    stream);
1837 1838
    // There is a need to add synchronization to ensure that the data is copied.
    hl_stream_synchronize(stream);
Z
zhangjinchao01 已提交
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876
  } else if (typeid(src) == typeid(CpuMatrix)) {
    memcpy(data_, src.getData(), sizeof(real) * elementCnt_);
  } else {
    LOG(FATAL) << "Wrong";
  }
}

void CpuMatrix::copyFrom(const real* cpuSrc, size_t size) {
  CHECK(isContiguous());
  CHECK(size <= elementCnt_);
  memcpy(data_, cpuSrc, sizeof(real) * size);
}

void CpuMatrix::copyFrom(const real* cpuSrc, const int64_t* seq) {
  CHECK(isContiguous());
  for (size_t i = 0; i < height_; i++) {
    memcpy(data_ + i * width_, cpuSrc + seq[i] * width_, sizeof(real) * width_);
  }
}

void CpuMatrix::copyFrom(const IVector& src) {
  CHECK(isContiguous());
  CHECK(elementCnt_ == src.getSize())
      << "the src and dst should have same size.";
  const int* cpuSrc = NULL;
  IVectorPtr tmp;
  if (src.useGpu()) {
    CpuIVector tmp(src.getSize());
    tmp.copyFrom(src);
    cpuSrc = tmp.getData();
  } else {
    cpuSrc = src.getData();
  }
  for (size_t i = 0; i < elementCnt_; ++i) {
    data_[i] = cpuSrc[i];
  }
}

1877
void CpuMatrix::copyByRowIndex(Matrix& b, const IVector& rowIndex) {
Z
zhangjinchao01 已提交
1878 1879 1880
  size_t height = getHeight();
  size_t width = getWidth();
  CHECK_EQ(b.getWidth(), width);
1881
  const int* index = rowIndex.getData();
Z
zhangjinchao01 已提交
1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939
  for (size_t i = 0; i < height; i++) {
    CHECK_LT(static_cast<size_t>(index[i]), b.getHeight());
    real* src = b.getData() + index[i] * width;
    real* dst = getData() + i * width;
    memcpy(dst, src, sizeof(real) * width);
  }
}

MatrixPtr CpuMatrix::clone(size_t height, size_t width, bool useGpu) {
  CHECK(isContiguous());

  if (height == 0 && width == 0) {
    height = height_;
    width = width_;
  }

  CHECK(width && height);

  if (useGpu) {
    return std::make_shared<GpuMatrix>(height, width);
  } else {
    return std::make_shared<CpuMatrix>(height, width);
  }
}

void CpuMatrix::resize(size_t newHeight, size_t newWidth) {
  size_t newSize = newHeight * newWidth;
  if (NULL == memoryHandle_.get() ||
      newSize * sizeof(real) > memoryHandle_->getAllocSize()) {
    memoryHandle_ = std::make_shared<CpuMemoryHandle>(newSize * sizeof(real));
    data_ = reinterpret_cast<real*>(memoryHandle_->getBuf());
  }

  height_ = newHeight;
  width_ = newWidth;
  elementCnt_ = newSize;
  stride_ = width_;
}

real CpuMatrix::getElement(size_t x, size_t y) const {
  return data_[x * stride_ + y];
}

real CpuMatrix::getSum() {
  CHECK(isContiguous());
  double sum = 0;
  for (size_t i = 0; i < height_; ++i) {
    for (size_t j = 0; j < width_; ++j) {
      sum += data_[i * width_ + j];
    }
  }
  return sum;
}

void CpuMatrix::accumulateColSum(Matrix& src) {
  CHECK_EQ(getWidth(), src.getWidth());
  CHECK_EQ(getHeight(), (size_t)1);

1940
  sumCols(src, /* scaleSum= */ 1, /* scaleDest= */ 1);
Z
zhangjinchao01 已提交
1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
}

real CpuMatrix::getAbsSum() {
  CHECK(isContiguous());
  double sum = 0;
  for (size_t i = 0; i < height_; ++i) {
    for (size_t j = 0; j < width_; ++j) {
      sum += fabs(data_[i * width_ + j]);
    }
  }
  return sum;
}

MatrixPtr CpuMatrix::getTranspose() {
  if (memoryHandle_.get() != NULL) {
    return std::make_shared<CpuMatrix>(
1957 1958 1959 1960
        std::dynamic_pointer_cast<CpuMemoryHandle>(memoryHandle_),
        height_,
        width_,
        true);
Z
zhangjinchao01 已提交
1961 1962 1963 1964 1965 1966
  } else {
    MatrixPtr copy_T(new CpuMatrix(data_, height_, width_, true));
    return copy_T;
  }
}

1967
void CpuMatrix::transpose(MatrixPtr& matTrans, bool memAlloc) {
Z
zhangjinchao01 已提交
1968 1969 1970 1971
  if (memAlloc) {
    matTrans = std::make_shared<CpuMatrix>(width_, height_);
  } else {
    CHECK(matTrans != NULL);
H
Haonan 已提交
1972 1973
    CHECK_EQ(matTrans->getHeight(), width_);
    CHECK_EQ(matTrans->getWidth(), height_);
Z
zhangjinchao01 已提交
1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986
  }
  real* dataTrans = matTrans->getData();
  real* data = getData();
  int lda = getStride();
  int ldc = matTrans->getStride();

  for (size_t i = 0; i < height_; i++) {
    for (size_t j = 0; j < width_; j++) {
      dataTrans[j * ldc + i] = data[i * lda + j];
    }
  }
}

1987 1988 1989 1990 1991
void CpuMatrix::rotate(MatrixPtr& matRot, bool memAlloc, bool clockWise) {
  if (memAlloc) {
    matRot = std::make_shared<CpuMatrix>(width_, height_);
  } else {
    CHECK(matRot != NULL);
H
Haonan 已提交
1992 1993
    CHECK_EQ(matRot->getHeight(), width_);
    CHECK_EQ(matRot->getWidth(), height_);
1994 1995 1996 1997 1998 1999 2000
  }
  real* dataRot = matRot->getData();
  real* data = getData();

  for (size_t i = 0; i < height_; i++) {
    for (size_t j = 0; j < width_; j++) {
      if (clockWise) {
H
Haonan 已提交
2001
        dataRot[j * height_ + i] = data[(height_ - i - 1) * width_ + j];
2002
      } else {
H
Haonan 已提交
2003
        dataRot[j * height_ + i] = data[i * width_ + (width_ - j - 1)];
2004 2005 2006 2007 2008
      }
    }
  }
}

L
lzhao4ever 已提交
2009 2010 2011 2012 2013 2014
MatrixPtr CpuMatrix::getInverse() {
  MatrixPtr matInv;
  inverse(matInv, true);
  return matInv;
}

2015
void CpuMatrix::inverse(MatrixPtr& matInv, bool memAlloc) {
L
lzhao4ever 已提交
2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048
  CHECK_EQ(height_, width_);

  if (memAlloc) {
    matInv = std::make_shared<CpuMatrix>(height_, width_);
  } else {
    CHECK(matInv != NULL);
  }

  CHECK_EQ(height_, matInv->getHeight());
  CHECK_EQ(width_, matInv->getWidth());
  matInv->copyFrom(*this);

  real* data = getData();
  real* dataInv = matInv->getData();
  int ldc = matInv->getStride();

  if (height_ == 1) {
    CHECK_NE(*data, 0);
    *dataInv = 1.0 / (*data);
    return;
  }

  /* Compute the LU decomposition of the matrix */
  std::vector<int> ipiv(height_);
  CBLAS_ORDER order = (matInv->isTransposed() ? CblasColMajor : CblasRowMajor);
  int info = getrf<real>(order, height_, height_, dataInv, ldc, ipiv.data());
  CHECK_EQ(info, 0);

  /* Compute the inverse of the matrix given its LU decompsotion */
  info = getri<real>(order, height_, dataInv, ldc, ipiv.data());
  CHECK_EQ(info, 0);
}

X
xzl 已提交
2049
void CpuMatrix::upsampleForward(Matrix& input,
X
xzl 已提交
2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
                                Matrix& mask,
                                size_t imgSizeH,
                                size_t imgSizeW,
                                size_t channels,
                                size_t outputH,
                                size_t outputW) {
  real* inputData = input.getData();
  real* maskData = mask.getData();
  real* outData = data_;
  size_t inLength = imgSizeH * imgSizeW;
  size_t outLength = outputH * outputW;
  size_t batch = input.getHeight();
  CHECK(inLength == input.getWidth() / channels);
  CHECK_EQ(batch, this->getHeight());
  CHECK_EQ(channels * outLength, this->getWidth());

  for (size_t k = 0; k < batch; k++) {
    for (size_t c = 0; c < channels; c++) {
      for (size_t i = 0; i < inLength; i++) {
        size_t out_index = static_cast<int>(maskData[i]);
        if (out_index >= outLength) {
          LOG(FATAL) << "upsample index " << out_index << " out of range.";
X
xzl 已提交
2072
        }
X
xzl 已提交
2073 2074 2075 2076 2077
        outData[out_index] = inputData[i];
      }
      inputData += inLength;
      maskData += inLength;
      outData += outLength;
X
xzl 已提交
2078
    }
X
xzl 已提交
2079
  }
X
xzl 已提交
2080 2081 2082
}

void CpuMatrix::upsampleBackward(Matrix& outputGrad,
X
xzl 已提交
2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104
                                 Matrix& mask,
                                 size_t imgSizeH,
                                 size_t imgSizeW,
                                 size_t channels,
                                 size_t outputH,
                                 size_t outputW) {
  real* outputGradData = outputGrad.getData();
  real* maskData = mask.getData();
  real* inputGradData = data_;
  size_t inLength = imgSizeH * imgSizeW;
  size_t outLength = outputH * outputW;
  size_t batch = outputGrad.getHeight();
  CHECK(inLength == this->getWidth() / channels);
  CHECK_EQ(batch, this->getHeight());
  CHECK_EQ(channels * outLength, outputGrad.getWidth());

  for (size_t k = 0; k < batch; k++) {
    for (size_t c = 0; c < channels; c++) {
      for (size_t i = 0; i < inLength; i++) {
        size_t out_index = static_cast<int>(maskData[i]);
        if (out_index >= outLength) {
          LOG(FATAL) << "upsample index " << out_index << " out of range.";
X
xzl 已提交
2105
        }
X
xzl 已提交
2106 2107 2108 2109 2110
        inputGradData[i] = outputGradData[out_index];
      }
      inputGradData += inLength;
      maskData += inLength;
      outputGradData += outLength;
X
xzl 已提交
2111
    }
X
xzl 已提交
2112
  }
X
xzl 已提交
2113 2114
}

X
xzl 已提交
2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126
void CpuMatrix::maxPoolForward(Matrix& inputMat,
                               size_t imgSizeH,
                               size_t imgSizeW,
                               size_t channels,
                               size_t sizeX,
                               size_t sizeY,
                               size_t strideH,
                               size_t strideW,
                               size_t outputH,
                               size_t outputW,
                               size_t paddingH,
                               size_t paddingW,
2127
                               MatrixPtr maskMatP) {
Z
zhangjinchao01 已提交
2128 2129
  real* inputData = inputMat.getData();
  real* outData = data_;
X
xzl 已提交
2130
  real* maskData = NULL;
Z
zhangjinchao01 已提交
2131
  size_t num = inputMat.getHeight();
2132 2133 2134
  size_t inLength = imgSizeH * imgSizeW;
  size_t outLength = outputH * outputW;
  CHECK(inLength == inputMat.getWidth() / channels);
2135
  CHECK_EQ(num, this->getHeight());
2136
  CHECK_EQ(channels * outLength, this->getWidth());
Q
qijun 已提交
2137
  size_t outStride = getStride();
Z
zhangjinchao01 已提交
2138

2139
  if (maskMatP != NULL) {
X
xzl 已提交
2140 2141 2142 2143
    maskData = maskMatP->getData();
    CHECK_EQ(channels * outLength, maskMatP->getWidth());
  }

Z
zhangjinchao01 已提交
2144
  /* pool max one by one */
Q
qijun 已提交
2145 2146
  for (size_t n = 0; n < num; ++n) {  // frame by frame
    if (!isContiguous()) {
Q
qijun 已提交
2147
      outData = data_ + n * outStride;
Q
qijun 已提交
2148
    }
Z
zhangjinchao01 已提交
2149 2150
    for (size_t c = 0; c < channels; ++c) {  // channel by channel
      for (size_t ph = 0; ph < outputH; ++ph) {
2151
        int hstart = ph * strideH - paddingH;
H
hedaoyuan 已提交
2152 2153 2154
        int hend = hstart + sizeY;
        hstart = hstart < 0 ? 0 : hstart;
        hend = hend < (int)imgSizeH ? hend : (int)imgSizeH;
Z
zhangjinchao01 已提交
2155
        for (size_t pw = 0; pw < outputW; ++pw) {
2156
          int wstart = pw * strideW - paddingW;
H
hedaoyuan 已提交
2157 2158 2159
          int wend = wstart + sizeX;
          wstart = wstart < 0 ? 0 : wstart;
          wend = wend < (int)imgSizeW ? wend : (int)imgSizeW;
X
xzl 已提交
2160 2161 2162 2163 2164 2165 2166 2167

          real maxval = -(real)FLT_MAX;
          int max_index = -1;
          for (int h = hstart; h < hend; ++h) {
            for (int w = wstart; w < wend; ++w) {
              if (maxval < inputData[h * imgSizeW + w]) {
                maxval = inputData[h * imgSizeW + w];
                max_index = h * imgSizeW + w;
X
xzl 已提交
2168
              }
Z
zhangjinchao01 已提交
2169 2170
            }
          }
X
xzl 已提交
2171 2172 2173

          outData[ph * outputW + pw] = maxval;
          if (maskData != NULL) maskData[ph * outputW + pw] = max_index;
Z
zhangjinchao01 已提交
2174 2175 2176
        }
      }
      // compute offset
2177 2178
      inputData += inLength;
      outData += outLength;
X
xzl 已提交
2179

X
xzl 已提交
2180
      if (maskData != NULL) maskData += outLength;
Z
zhangjinchao01 已提交
2181 2182 2183 2184
    }
  }
}

2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199
void CpuMatrix::maxPoolBackward(Matrix& image,
                                size_t imgSizeH,
                                size_t imgSizeW,
                                Matrix& outGrad,
                                Matrix& outV,
                                size_t sizeX,
                                size_t sizeY,
                                size_t strideH,
                                size_t strideW,
                                size_t outputH,
                                size_t outputW,
                                real scaleTargets,
                                real scaleOutput,
                                size_t paddingH,
                                size_t paddingW) {
Z
zhangjinchao01 已提交
2200
  size_t num = image.getHeight();
2201 2202 2203 2204
  size_t inLength = imgSizeH * imgSizeW;
  size_t outLength = outputH * outputW;
  size_t channels = size_t(width_ / inLength);
  CHECK(image.getWidth() == inLength * channels);
Z
zhangjinchao01 已提交
2205 2206 2207 2208 2209 2210 2211 2212
  CHECK(image.getHeight() == height_ && image.getWidth() == width_);
  CHECK(outV.getHeight() == outGrad.getHeight() &&
        outV.getWidth() == outGrad.getWidth());

  real* tgtGrad = data_;
  real* inData = image.getData();
  real* otData = outV.getData();
  real* otGrad = outGrad.getData();
Q
qijun 已提交
2213 2214 2215 2216 2217

  size_t outStride = outV.getStride();
  real* origOutData = otData;
  real* origOutGrad = otGrad;

Z
zhangjinchao01 已提交
2218
  for (size_t n = 0; n < num; ++n) {
Q
qijun 已提交
2219
    if (!outV.isContiguous()) {
Q
qijun 已提交
2220 2221
      otData = origOutData + n * outStride;
      otGrad = origOutGrad + n * outStride;
Q
qijun 已提交
2222
    }
Z
zhangjinchao01 已提交
2223 2224
    for (size_t c = 0; c < channels; ++c) {
      for (size_t ph = 0; ph < outputH; ++ph) {
2225 2226 2227
        int hstart = ph * strideH - paddingH;
        int hend = std::min(hstart + sizeY, imgSizeH);
        hstart = std::max(hstart, 0);
Z
zhangjinchao01 已提交
2228
        for (size_t pw = 0; pw < outputW; ++pw) {
2229 2230 2231 2232 2233
          int wstart = pw * strideW - paddingW;
          int wend = std::min(wstart + sizeX, imgSizeW);
          wstart = std::max(wstart, 0);
          for (int h = hstart; h < hend; ++h) {
            for (int w = wstart; w < wend; ++w) {
Z
zhangjinchao01 已提交
2234 2235 2236
              tgtGrad[h * imgSizeW + w] =
                  scaleTargets * tgtGrad[h * imgSizeW + w] +
                  scaleOutput * otGrad[ph * outputW + pw] *
2237
                      (inData[h * imgSizeW + w] == otData[ph * outputW + pw]);
Z
zhangjinchao01 已提交
2238 2239 2240 2241 2242
            }
          }
        }
      }
      // offset
2243 2244 2245 2246
      inData += inLength;
      tgtGrad += inLength;
      otData += outLength;
      otGrad += outLength;
Z
zhangjinchao01 已提交
2247 2248 2249 2250
    }
  }
}

2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261
void CpuMatrix::avgPoolForward(Matrix& input,
                               size_t imgSizeH,
                               size_t imgSizeW,
                               size_t channels,
                               size_t sizeX,
                               size_t sizeY,
                               size_t strideH,
                               size_t strideW,
                               size_t outputH,
                               size_t outputW,
                               size_t paddingH,
2262 2263
                               size_t paddingW,
                               bool excludeMode) {
Z
zhangjinchao01 已提交
2264 2265
  // The main loop
  size_t num = input.getHeight();
2266 2267 2268 2269
  size_t inLength = imgSizeH * imgSizeW;
  size_t outLength = outputH * outputW;
  CHECK(inLength * channels == input.getWidth());
  CHECK(outLength * channels * num == height_ * width_);
Z
zhangjinchao01 已提交
2270 2271 2272 2273
  real* tgtData = data_;
  real* inData = input.getData();

  for (size_t n = 0; n < num; ++n) {
Q
qijun 已提交
2274 2275 2276
    if (!isContiguous()) {
      tgtData = data_ + n * getStride();
    }
Z
zhangjinchao01 已提交
2277 2278
    for (size_t c = 0; c < channels; ++c) {
      for (size_t ph = 0; ph < outputH; ++ph) {
2279 2280 2281
        int hstart = ph * strideH - paddingH;
        int hend = std::min(hstart + sizeY, imgSizeH);
        hstart = std::max(hstart, 0);
Z
zhangjinchao01 已提交
2282
        for (size_t pw = 0; pw < outputW; ++pw) {
2283
          int wstart = pw * strideW - paddingW;
2284
          int wend = std::min(wstart + sizeX, imgSizeW);
2285
          wstart = std::max(wstart, 0);
Z
zhangjinchao01 已提交
2286
          tgtData[ph * outputW + pw] = 0;  // clear
2287 2288
          for (int h = hstart; h < hend; ++h) {
            for (int w = wstart; w < wend; ++w) {
2289
              tgtData[ph * outputW + pw] += inData[h * imgSizeW + w];
Z
zhangjinchao01 已提交
2290 2291
            }
          }
2292 2293
          int poolSize =
              excludeMode ? (hend - hstart) * (wend - wstart) : sizeY * sizeX;
2294
          CHECK(poolSize);
2295
          tgtData[ph * outputW + pw] /= poolSize;
Z
zhangjinchao01 已提交
2296 2297 2298
        }
      }
      // compute offset
2299 2300
      inData += inLength;
      tgtData += outLength;
Z
zhangjinchao01 已提交
2301 2302 2303 2304
    }
  }
}

2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316
void CpuMatrix::avgPoolBackward(Matrix& input,
                                size_t imgSizeH,
                                size_t imgSizeW,
                                size_t sizeX,
                                size_t sizeY,
                                size_t strideH,
                                size_t strideW,
                                size_t outputH,
                                size_t outputW,
                                real scaleTargets,
                                real scaleOutput,
                                size_t paddingH,
2317 2318
                                size_t paddingW,
                                bool excludeMode) {
Z
zhangjinchao01 已提交
2319 2320
  size_t num = input.getHeight();
  size_t channels = input.getWidth() / outputH / outputW;
2321 2322 2323
  size_t inLength = imgSizeH * imgSizeW;
  size_t outLength = outputH * outputW;
  CHECK(inLength * channels == getWidth());
Z
zhangjinchao01 已提交
2324 2325 2326 2327
  real* inData = input.getData();
  real* outData = getData();

  for (size_t n = 0; n < num; ++n) {
Q
qijun 已提交
2328 2329 2330
    if (!input.isContiguous()) {
      inData = input.getData() + n * input.getStride();
    }
Z
zhangjinchao01 已提交
2331 2332
    for (size_t c = 0; c < channels; ++c) {
      for (size_t ph = 0; ph < outputH; ++ph) {
2333 2334 2335
        int hstart = ph * strideH - paddingH;
        int hend = std::min(hstart + sizeY, imgSizeH);
        hstart = std::max(hstart, 0);
Z
zhangjinchao01 已提交
2336
        for (size_t pw = 0; pw < outputW; ++pw) {
2337
          int wstart = pw * strideW - paddingW;
2338
          int wend = std::min(wstart + sizeX, imgSizeW);
2339
          wstart = std::max(wstart, 0);
2340 2341
          int poolSize =
              excludeMode ? (hend - hstart) * (wend - wstart) : sizeY * sizeX;
2342 2343 2344 2345 2346
          CHECK(poolSize);

          for (int h = hstart; h < hend; ++h) {
            for (int w = wstart; w < wend; ++w) {
              outData[h * imgSizeW + w] += inData[ph * outputW + pw] / poolSize;
Z
zhangjinchao01 已提交
2347 2348 2349 2350 2351
            }
          }
        }
      }
      // offset
2352 2353
      outData += inLength;
      inData += outLength;
Z
zhangjinchao01 已提交
2354 2355 2356 2357
    }
  }
}

C
chengduoZH 已提交
2358
void CpuMatrix::maxPool3DForward(Matrix& inputMat,
C
chengduoZH 已提交
2359
                                 Matrix& maxPoolIdx,
C
chengduoZH 已提交
2360
                                 size_t channels,
C
chengduoZH 已提交
2361 2362 2363
                                 size_t imgSizeD,
                                 size_t imgSizeH,
                                 size_t imgSizeW,
C
chengduoZH 已提交
2364 2365 2366
                                 size_t outputD,
                                 size_t outputH,
                                 size_t outputW,
C
chengduoZH 已提交
2367 2368 2369 2370 2371 2372 2373 2374 2375 2376
                                 size_t sizeZ,
                                 size_t sizeY,
                                 size_t sizeX,
                                 size_t strideD,
                                 size_t strideH,
                                 size_t strideW,
                                 size_t paddingD,
                                 size_t paddingH,
                                 size_t paddingW) {
  real* inputData = inputMat.getData();
C
chengduoZH 已提交
2377
  real* outData = getData();
C
chengduoZH 已提交
2378
  real* maxPoolIdxData = maxPoolIdx.getData();
C
chengduoZH 已提交
2379
  size_t num = inputMat.getHeight();
2380 2381 2382
  size_t inLength = imgSizeH * imgSizeW * imgSizeD;
  size_t outLength = outputH * outputW * outputD;
  CHECK(inLength == inputMat.getWidth() / channels);
C
chengduoZH 已提交
2383
  CHECK_EQ(num, this->getHeight());
2384
  CHECK_EQ(channels * outLength, this->getWidth());
C
chengduoZH 已提交
2385 2386 2387 2388 2389 2390
  size_t outStride = getStride();

  /* initialize the data_ */
  for (size_t i = 0; i < height_; i++) {
    for (size_t j = 0; j < width_; j++) {
      outData[(i)*outStride + j] = -(real)FLT_MAX;
C
chengduoZH 已提交
2391
      maxPoolIdxData[(i)*outStride + j] = -1;
C
chengduoZH 已提交
2392 2393 2394 2395 2396 2397
    }
  }

  /* pool max one by one */
  for (size_t n = 0; n < num; ++n) {  // frame by frame
    if (!isContiguous()) {
C
chengduoZH 已提交
2398
      outData = getData() + n * outStride;
C
chengduoZH 已提交
2399
      maxPoolIdxData = maxPoolIdx.getData() + n * outStride;
C
chengduoZH 已提交
2400 2401 2402
    }
    for (size_t c = 0; c < channels; ++c) {  // channel by channel
      for (size_t pd = 0; pd < outputD; ++pd) {
2403 2404 2405
        int dstart = pd * strideD - paddingD;
        int dend = std::min(dstart + sizeZ, imgSizeD);
        dstart = std::max(dstart, 0);
C
chengduoZH 已提交
2406
        for (size_t ph = 0; ph < outputH; ++ph) {
2407 2408 2409
          int hstart = ph * strideH - paddingH;
          int hend = std::min(hstart + sizeY, imgSizeH);
          hstart = std::max(hstart, 0);
C
chengduoZH 已提交
2410 2411
          for (size_t pw = 0; pw < outputW; ++pw) {
            int wstart = pw * strideW - paddingW;
2412
            int wend = std::min(wstart + sizeX, imgSizeW);
C
chengduoZH 已提交
2413
            wstart = std::max(wstart, 0);
C
chengduoZH 已提交
2414
            int maxIdx = -1;
C
chengduoZH 已提交
2415
            real maxOutData = outData[(pd * outputH + ph) * outputW + pw];
C
chengduoZH 已提交
2416 2417 2418
            for (int d = dstart; d < dend; ++d) {
              for (int h = hstart; h < hend; ++h) {
                for (int w = wstart; w < wend; ++w) {
C
chengduoZH 已提交
2419
                  if (maxOutData <
2420 2421 2422
                      inputData[(d * imgSizeH + h) * imgSizeW + w]) {
                    maxOutData = inputData[(d * imgSizeH + h) * imgSizeW + w];
                    maxIdx = (d * imgSizeH + h) * imgSizeW + w;
C
chengduoZH 已提交
2423
                  }
C
chengduoZH 已提交
2424 2425 2426
                }
              }
            }
C
chengduoZH 已提交
2427
            outData[(pd * outputH + ph) * outputW + pw] = maxOutData;
C
chengduoZH 已提交
2428
            maxPoolIdxData[(pd * outputH + ph) * outputW + pw] = maxIdx;
C
chengduoZH 已提交
2429 2430 2431 2432
          }
        }
      }
      // compute offset
2433 2434 2435
      inputData += inLength;
      outData += outLength;
      maxPoolIdxData += outLength;
C
chengduoZH 已提交
2436 2437 2438 2439
    }
  }
}

C
chengduoZH 已提交
2440 2441
void CpuMatrix::maxPool3DBackward(Matrix& outGrad,
                                  Matrix& maxPoolIdx,
C
chengduoZH 已提交
2442 2443 2444
                                  size_t imgSizeD,
                                  size_t imgSizeH,
                                  size_t imgSizeW,
C
chengduoZH 已提交
2445 2446 2447
                                  size_t outputD,
                                  size_t outputH,
                                  size_t outputW,
C
chengduoZH 已提交
2448 2449 2450 2451 2452 2453 2454 2455
                                  size_t sizeZ,
                                  size_t sizeY,
                                  size_t sizeX,
                                  size_t strideD,
                                  size_t strideH,
                                  size_t strideW,
                                  size_t paddingD,
                                  size_t paddingH,
C
chengduoZH 已提交
2456 2457 2458
                                  size_t paddingW,
                                  real scaleTargets,
                                  real scaleOutput) {
C
chengduoZH 已提交
2459
  size_t num = getHeight();
2460 2461 2462
  size_t inLength = imgSizeH * imgSizeW * imgSizeD;
  size_t outLength = outputH * outputW * outputD;
  size_t channels = size_t(width_ / inLength);
C
chengduoZH 已提交
2463 2464
  CHECK(maxPoolIdx.getHeight() == outGrad.getHeight() &&
        maxPoolIdx.getWidth() == outGrad.getWidth());
C
chengduoZH 已提交
2465

C
chengduoZH 已提交
2466
  real* tgtGrad = getData();
C
chengduoZH 已提交
2467
  real* otGrad = outGrad.getData();
C
chengduoZH 已提交
2468 2469
  real* maxPoolIdxData = maxPoolIdx.getData();
  size_t outStride = outGrad.getStride();
C
chengduoZH 已提交
2470 2471

  for (size_t n = 0; n < num; ++n) {
C
chengduoZH 已提交
2472
    if (!outGrad.isContiguous()) {
C
chengduoZH 已提交
2473
      otGrad = outGrad.getData() + n * outStride;
C
chengduoZH 已提交
2474
      maxPoolIdxData = maxPoolIdx.getData() + n * outStride;
C
chengduoZH 已提交
2475 2476 2477 2478 2479
    }
    for (size_t c = 0; c < channels; ++c) {
      for (size_t pd = 0; pd < outputD; ++pd) {
        for (size_t ph = 0; ph < outputH; ++ph) {
          for (size_t pw = 0; pw < outputW; ++pw) {
C
chengduoZH 已提交
2480 2481 2482 2483
            const size_t index = (pd * outputH + ph) * outputW + pw;
            const size_t tgtIdx = static_cast<size_t>(maxPoolIdxData[index]);
            tgtGrad[tgtIdx] =
                scaleTargets * tgtGrad[tgtIdx] + scaleOutput * otGrad[index];
C
chengduoZH 已提交
2484 2485 2486 2487
          }
        }
      }
      // offset
2488 2489 2490
      tgtGrad += inLength;
      otGrad += outLength;
      maxPoolIdxData += outLength;
C
chengduoZH 已提交
2491 2492 2493 2494 2495
    }
  }
}

void CpuMatrix::avgPool3DForward(Matrix& input,
C
chengduoZH 已提交
2496
                                 size_t channels,
C
chengduoZH 已提交
2497 2498 2499
                                 size_t imgSizeD,
                                 size_t imgSizeH,
                                 size_t imgSizeW,
C
chengduoZH 已提交
2500 2501 2502
                                 size_t outputD,
                                 size_t outputH,
                                 size_t outputW,
C
chengduoZH 已提交
2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513
                                 size_t sizeZ,
                                 size_t sizeY,
                                 size_t sizeX,
                                 size_t strideD,
                                 size_t strideH,
                                 size_t strideW,
                                 size_t paddingD,
                                 size_t paddingH,
                                 size_t paddingW) {
  // The main loop
  size_t num = input.getHeight();
2514 2515 2516 2517
  size_t inLength = imgSizeH * imgSizeW * imgSizeD;
  size_t outLength = outputH * outputW * outputD;
  CHECK(inLength * channels == input.getWidth());
  CHECK(outLength * channels * num == height_ * width_);
C
chengduoZH 已提交
2518
  real* tgtData = getData();
C
chengduoZH 已提交
2519 2520 2521 2522 2523 2524 2525 2526
  real* inData = input.getData();

  for (size_t n = 0; n < num; ++n) {
    if (!isContiguous()) {
      tgtData = data_ + n * getStride();
    }
    for (size_t c = 0; c < channels; ++c) {
      for (size_t pd = 0; pd < outputD; ++pd) {
2527 2528 2529
        int dstart = pd * strideD - paddingD;
        int dend = std::min(dstart + sizeZ, imgSizeD);
        dstart = std::max(dstart, 0);
C
chengduoZH 已提交
2530
        for (size_t ph = 0; ph < outputH; ++ph) {
2531 2532 2533
          int hstart = ph * strideH - paddingH;
          int hend = std::min(hstart + sizeY, imgSizeH);
          hstart = std::max(hstart, 0);
C
chengduoZH 已提交
2534 2535
          for (size_t pw = 0; pw < outputW; ++pw) {
            int wstart = pw * strideW - paddingW;
2536
            int wend = std::min(wstart + sizeX, imgSizeW);
C
chengduoZH 已提交
2537 2538 2539 2540 2541 2542 2543
            wstart = std::max(wstart, 0);

            tgtData[(pd * outputH + ph) * outputW + pw] = 0;  // clear
            for (int d = dstart; d < dend; ++d) {
              for (int h = hstart; h < hend; ++h) {
                for (int w = wstart; w < wend; ++w) {
                  tgtData[(pd * outputH + ph) * outputW + pw] +=
2544
                      inData[(d * imgSizeH + h) * imgSizeW + w];
C
chengduoZH 已提交
2545 2546 2547
                }
              }
            }
2548 2549
            int poolSize = (dend - dstart) * (hend - hstart) * (wend - wstart);
            CHECK(poolSize);
C
chengduoZH 已提交
2550 2551 2552 2553 2554
            tgtData[(pd * outputH + ph) * outputW + pw] /= poolSize;
          }
        }
      }
      // compute offset
2555 2556
      inData += inLength;
      tgtData += outLength;
C
chengduoZH 已提交
2557 2558 2559 2560 2561 2562 2563 2564
    }
  }
}

void CpuMatrix::avgPool3DBackward(Matrix& input,
                                  size_t imgSizeD,
                                  size_t imgSizeH,
                                  size_t imgSizeW,
C
chengduoZH 已提交
2565 2566 2567
                                  size_t outputD,
                                  size_t outputH,
                                  size_t outputW,
C
chengduoZH 已提交
2568 2569 2570 2571 2572 2573 2574 2575
                                  size_t sizeZ,
                                  size_t sizeY,
                                  size_t sizeX,
                                  size_t strideD,
                                  size_t strideH,
                                  size_t strideW,
                                  size_t paddingD,
                                  size_t paddingH,
C
chengduoZH 已提交
2576 2577 2578
                                  size_t paddingW,
                                  real scaleTargets,
                                  real scaleOutput) {
C
chengduoZH 已提交
2579
  size_t num = input.getHeight();
2580 2581 2582 2583
  size_t inLength = imgSizeH * imgSizeW * imgSizeD;
  size_t outLength = outputH * outputW * outputD;
  size_t channels = input.getWidth() / outLength;
  CHECK(inLength * channels == getWidth());
C
chengduoZH 已提交
2584 2585 2586 2587 2588 2589 2590 2591 2592
  real* inData = input.getData();
  real* outData = getData();

  for (size_t n = 0; n < num; ++n) {
    if (!input.isContiguous()) {
      inData = input.getData() + n * input.getStride();
    }
    for (size_t c = 0; c < channels; ++c) {
      for (size_t pd = 0; pd < outputD; ++pd) {
2593 2594 2595
        int dstart = pd * strideD - paddingD;
        int dend = std::min(dstart + sizeZ, imgSizeD);
        dstart = std::max(dstart, 0);
C
chengduoZH 已提交
2596
        for (size_t ph = 0; ph < outputH; ++ph) {
2597 2598 2599
          int hstart = ph * strideH - paddingH;
          int hend = std::min(hstart + sizeY, imgSizeH);
          hstart = std::max(hstart, 0);
C
chengduoZH 已提交
2600 2601
          for (size_t pw = 0; pw < outputW; ++pw) {
            int wstart = pw * strideW - paddingW;
2602
            int wend = std::min(wstart + sizeX, imgSizeW);
C
chengduoZH 已提交
2603
            wstart = std::max(wstart, 0);
2604
            int poolSize = (dend - dstart) * (hend - hstart) * (wend - wstart);
C
chengduoZH 已提交
2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617
            CHECK(poolSize);
            for (int d = dstart; d < dend; ++d) {
              for (int h = hstart; h < hend; ++h) {
                for (int w = wstart; w < wend; ++w) {
                  outData[(d * imgSizeH + h) * imgSizeW + w] +=
                      inData[(pd * outputH + ph) * outputW + pw] / poolSize;
                }
              }
            }
          }
        }
      }
      // offset
2618 2619
      outData += inLength;
      inData += outLength;
C
chengduoZH 已提交
2620 2621 2622 2623
    }
  }
}

Z
zhangjinchao01 已提交
2624 2625 2626 2627 2628
/**
 * Input: one or more sequences. Each sequence contains some instances.
 * Output: output size is the number of input sequences (NOT input instances).
 * output[i] is set to max_{for each instance in this sequence}{input[i]}
 */
2629 2630
void CpuMatrix::maxSequenceForward(Matrix& input,
                                   const IVector& sequence,
Z
zhangjinchao01 已提交
2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670
                                   IVector& index) {
  CHECK(dynamic_cast<CpuMatrix*>(&input));
  CHECK(dynamic_cast<const CpuIVector*>(&sequence));
  CHECK(dynamic_cast<CpuIVector*>(&index));

  real* outData = getData();
  real* inputData = input.getData();
  const int* starts = sequence.getData();
  int* maxIndex = index.getData();
  size_t numSequences = getHeight();
  size_t dim = getWidth();

  CHECK_EQ(dim, input.getWidth());
  CHECK_EQ(numSequences, sequence.getSize() - 1);
  CHECK_EQ(starts[numSequences], (int)input.getHeight());
  CHECK_EQ(numSequences * dim, index.getSize());

  for (size_t sequenceId = 0; sequenceId < numSequences; ++sequenceId) {
    // current sequence, loop for each input instance
    // (1) first instance: do not need compare, copy value to outV directly
    for (size_t k = 0; k < dim; ++k) {
      outData[sequenceId * dim + k] = inputData[starts[sequenceId] * dim + k];
      maxIndex[sequenceId * dim + k] = starts[sequenceId];
    }
    // (2) other instance in same sequence
    for (int insId = starts[sequenceId] + 1; insId < starts[sequenceId + 1];
         ++insId) {
      // insId is the index on all instances
      for (size_t k = 0; k < dim; ++k) {
        // for each dim
        if (inputData[insId * dim + k] > outData[sequenceId * dim + k]) {
          // update max value and record index
          outData[sequenceId * dim + k] = inputData[insId * dim + k];
          maxIndex[sequenceId * dim + k] = insId;
        }
      }
    }
  }
}

2671 2672
void CpuMatrix::maxSequenceBackward(Matrix& outputGrad,
                                    const IVector& sequence,
Z
zhangjinchao01 已提交
2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709
                                    IVector& index) {
  CHECK(dynamic_cast<CpuMatrix*>(&outputGrad));
  CHECK(dynamic_cast<const CpuIVector*>(&sequence));
  CHECK(dynamic_cast<CpuIVector*>(&index));

  real* inputGrad = getData();
  real* outGrad = outputGrad.getData();
  int* maxIndex = index.getData();
  size_t dim = getWidth();
  size_t numSequences = sequence.getSize() - 1;

  CHECK_EQ(dim, outputGrad.getWidth());
  CHECK_EQ(numSequences, outputGrad.getHeight());
  CHECK_EQ(numSequences * dim, index.getSize());

  for (size_t sequenceId = 0; sequenceId < numSequences; ++sequenceId) {
    // current sequence
    for (size_t j = 0; j < dim; ++j) {
      // each dim
      int insId = maxIndex[sequenceId * dim + j];
      inputGrad[insId * dim + j] += outGrad[sequenceId * dim + j];
    }
  }
}

inline void vecAddTo(real* a, const real* b, size_t len) {
  for (unsigned int i = 0; i < len; ++i) {
    a[i] += b[i];
  }
}

inline void vecAddTo(real* a, const real* b, real scaleB, size_t len) {
  for (unsigned int i = 0; i < len; ++i) {
    a[i] += scaleB * b[i];
  }
}

2710 2711
inline void colVecAddTo(
    real* a, const real* b, size_t len, size_t aWidth, size_t bWidth) {
Z
zhangjinchao01 已提交
2712 2713 2714 2715 2716
  for (unsigned int i = 0; i < len; ++i) {
    a[i * aWidth] += b[i * bWidth];
  }
}

2717 2718
inline void colVecAddTo(
    real* a, real* b, real c, size_t len, size_t aWidth, size_t bWidth) {
Z
zhangjinchao01 已提交
2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750
  for (unsigned int i = 0; i < len; ++i) {
    a[i * aWidth] += b[i * bWidth] * c;
  }
}

void CpuMatrix::addBias(Matrix& b, real scale) {
  CHECK(b.useGpu_ == false) << "Matrix type are not equal";

  CHECK_EQ(b.getHeight(), (size_t)1);
  CHECK_EQ(width_, b.getWidth());
  real* aData = getData();
  real* bData = b.getData();
  size_t numSamples = getHeight();
  size_t dim = getWidth();

  if (scale == 1 && getStride() % 32 == 0) {  // use libaddto
    // @TODO(yuyang18) Make input addr can be unaligned.
    // So merge this if and else
    CHECK_EQ((size_t)aData % 32, 0UL);
    CHECK_EQ((size_t)bData % 32, 0UL);
    for (size_t i = 0; i < numSamples; i++) {
      simd::addTo(aData + i * getStride(), bData, dim);
    }
  } else {
    for (size_t i = 0; i < numSamples; i++) {
      for (size_t j = 0; j < dim; j++) {
        aData[i * getStride() + j] += scale * bData[j];
      }
    }
  }
}

2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768
void CpuMatrix::addSharedBias(Matrix& b, real scale) {
  CHECK_EQ(b.getHeight(), (size_t)1);
  real* aData = getData();
  real* bData = b.getData();
  size_t numSamples = getHeight();
  size_t channel = b.getWidth();
  CHECK_EQ(getWidth() % channel, 0UL);
  size_t dim = getWidth() / channel;

  for (size_t i = 0; i < numSamples; i++) {
    for (size_t c = 0; c < channel; c++) {
      for (size_t j = 0; j < dim; j++) {
        aData[i * getStride() + c * dim + j] += scale * bData[c];
      }
    }
  }
}

Z
zhangjinchao01 已提交
2769 2770 2771 2772 2773
void CpuMatrix::collectBias(Matrix& a, real scale) {
  CHECK_EQ(getHeight(), (size_t)1);
  CHECK_EQ(width_, a.getWidth());
  CpuSparseMatrix* aptr = dynamic_cast<CpuSparseMatrix*>(&a);
  if (!aptr) {
2774
    sumCols(a, /* scaleSum= */ scale, /* scaleDest= */ 1);
Z
zhangjinchao01 已提交
2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785
  } else {
    size_t nnz = aptr->getElementCnt();
    int* cols = aptr->getCols();
    real* A = aptr->getValue();
    real* B = getData();
    for (size_t i = 0; i < nnz; i++) {
      B[cols[i]] += scale * A[i];
    }
  }
}

2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802
void CpuMatrix::collectSharedBias(Matrix& a, real scale) {
  CHECK_EQ(getHeight(), (size_t)1);
  real* B = getData();
  real* A = a.getData();
  size_t numSamples = a.getHeight();
  size_t channel = getWidth();
  CHECK_EQ(a.getWidth() % channel, 0UL);
  size_t dim = a.getWidth() / channel;
  for (size_t i = 0; i < numSamples; i++) {
    for (size_t c = 0; c < channel; c++) {
      for (size_t j = 0; j < dim; j++) {
        B[c] += scale * A[i * channel * dim + c * dim + j];
      }
    }
  }
}

Z
zhangjinchao01 已提交
2803 2804 2805 2806 2807 2808 2809 2810 2811 2812
void CpuMatrix::sequenceAvgForward(Matrix& a,
                                   const IVector& startsPos,
                                   int mode) {
  size_t height = getHeight();
  size_t width = getWidth();
  CHECK_EQ(height, startsPos.getSize() - 1);
  CHECK_EQ(width, a.getWidth());
  real* dst = getData();
  real* src = a.getData();
  const int* starts = startsPos.getData();
X
xuwei06 已提交
2813
  MatrixPtr outMtx = Matrix::create(nullptr, 1, width, false, false);
Z
zhangjinchao01 已提交
2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824
  MatrixPtr dataMtx = Matrix::create(nullptr, 1, width, false, false);
  for (size_t i = 0; i < height; i++) {
    int sequenceLength = starts[i + 1] - starts[i];
    if (0 == sequenceLength) {
      // empty sequence
      continue;
    }
    outMtx->setData(dst + i * width);
    dataMtx->setData(src + starts[i] * width, sequenceLength, width);
    if (mode == 0) {
      // plain average
2825 2826 2827
      outMtx->sumCols(*dataMtx,
                      (real)1 / (real)sequenceLength,
                      /* scaleDest= */ 1);
Z
zhangjinchao01 已提交
2828 2829
    } else if (mode == 1) {
      // sum instead of average
2830
      outMtx->sumCols(*dataMtx, /* scaleSum= */ 1, /* scaleDest= */ 1);
Z
zhangjinchao01 已提交
2831 2832
    } else if (mode == 2) {
      // divide by square root of sequenceLength
2833 2834 2835
      outMtx->sumCols(*dataMtx,
                      (real)1 / std::sqrt(sequenceLength),
                      /* scaleDest= */ 1);
Z
zhangjinchao01 已提交
2836 2837 2838 2839 2840 2841
    } else {
      LOG(FATAL) << "should not reach here";
    }
  }
}

L
Luo Tao 已提交
2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876
void CpuMatrix::sequenceAvgBackward(Matrix& a,
                                    const IVector& startsPos,
                                    int mode) {
  size_t height = a.getHeight();
  size_t width = getWidth();
  CHECK_EQ(height, startsPos.getSize() - 1);
  CHECK_EQ(width, a.getWidth());
  real* dst = getData();
  real* src = a.getData();
  const int* starts = startsPos.getData();
  MatrixPtr outMtx = Matrix::create(nullptr, 1, width, false, false);
  MatrixPtr dataMtx = Matrix::create(nullptr, 1, width, false, false);
  for (size_t i = 0; i < height; ++i) {
    int sequenceLength = starts[i + 1] - starts[i];
    if (0 == sequenceLength) {
      // empty sequence
      continue;
    }
    outMtx->setData(dst + starts[i] * width, sequenceLength, width);
    dataMtx->setData(src + i * width);
    if (mode == 0) {
      // plain average
      outMtx->addBias(*dataMtx, 1.0f / sequenceLength);
    } else if (mode == 1) {
      // sum instead of average
      outMtx->addBias(*dataMtx, 1.0f);
    } else if (mode == 2) {
      // divide by square root of sequenceLength
      outMtx->addBias(*dataMtx, 1.0f / std::sqrt(sequenceLength));
    } else {
      LOG(FATAL) << "should not reach here";
    }
  }
}

Z
zhangjinchao01 已提交
2877
/* this = scaleAB*(a*b) + scaleT*this*/
2878 2879
void CpuMatrix::mul(const Matrix& a,
                    const Matrix& b,
2880
                    real scaleAB,
Z
zhangjinchao01 已提交
2881 2882
                    real scaleT) {
  CHECK(!isTransposed()) << "Not supported";
2883 2884 2885 2886
  const auto a_ptr = dynamic_cast<const CpuMatrix*>(&a);
  const auto b_ptr = dynamic_cast<const CpuMatrix*>(&b);
  const auto a_ptr_s = dynamic_cast<const CpuSparseMatrix*>(&a);
  const auto b_ptr_s = dynamic_cast<const CpuSparseMatrix*>(&b);
Z
zhangjinchao01 已提交
2887

2888 2889 2890 2891 2892 2893
  if (a_ptr && b_ptr) {
    mul((CpuMatrix*)a_ptr, (CpuMatrix*)b_ptr, scaleAB, scaleT);
  } else if (a_ptr_s && b_ptr) {
    mul((CpuSparseMatrix*)a_ptr_s, (CpuMatrix*)b_ptr, scaleAB, scaleT);
  } else if (a_ptr && b_ptr_s) {
    mul((CpuMatrix*)a_ptr, (CpuSparseMatrix*)b_ptr_s, scaleAB, scaleT);
Z
zhangjinchao01 已提交
2894 2895 2896 2897 2898
  } else {
    LOG(FATAL) << "Not supported";
  }
}

2899 2900 2901
void CpuMatrix::mul(CpuSparseMatrix* a,
                    CpuMatrix* b,
                    real scaleAB,
Z
zhangjinchao01 已提交
2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915
                    real scaleT) {
  if (dynamic_cast<CacheRowCpuMatrix*>(b)) {
    return mul(a, dynamic_cast<CacheRowCpuMatrix*>(b), this, scaleAB, scaleT);
  } else if (dynamic_cast<SparseRowCpuMatrix*>(b)) {
    return mul(a, dynamic_cast<SparseRowCpuMatrix*>(b), this, scaleAB, scaleT);
  } else {
    return mul(a, b, this, scaleAB, scaleT);
  }
}

void CpuMatrix::mul(CpuMatrix* a, CpuMatrix* b, real scaleAB, real scaleT) {
  CHECK(!isTransposed()) << "Not supported";

  size_t a_col, b_col, a_row, b_row;
2916
  bool a_trans, b_trans;
Z
zhangjinchao01 已提交
2917 2918 2919
  if (!a->isTransposed()) {
    a_col = a->getWidth();
    a_row = a->getHeight();
2920
    a_trans = false;
Z
zhangjinchao01 已提交
2921 2922 2923
  } else {
    a_col = a->getHeight();
    a_row = a->getWidth();
2924
    a_trans = true;
Z
zhangjinchao01 已提交
2925 2926 2927 2928
  }
  if (!b->isTransposed()) {
    b_col = b->getWidth();
    b_row = b->getHeight();
2929
    b_trans = false;
Z
zhangjinchao01 已提交
2930 2931 2932
  } else {
    b_col = b->getHeight();
    b_row = b->getWidth();
2933
    b_trans = true;
Z
zhangjinchao01 已提交
2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949
  }

  CHECK_EQ(a_col, b_row);
  CHECK_EQ(a_row, getHeight());
  CHECK_EQ(b_col, getWidth());

  real* A = a->getData();
  real* B = b->getData();
  real* C = getData();

  int M = getHeight();
  int N = getWidth();
  int K = a_col;
  int lda = a->getStride();
  int ldb = b->getStride();
  int ldc = getStride();
2950
  BlasGemm<DEVICE_TYPE_CPU, real>::compute(
L
Liu Yiqun 已提交
2951
      a_trans, b_trans, M, N, K, scaleAB, A, lda, B, ldb, scaleT, C, ldc);
Z
zhangjinchao01 已提交
2952 2953
}

2954 2955
void CpuMatrix::mul(
    CpuMatrix* a, CpuMatrix* b, CpuSparseMatrix* c, real scaleAB, real scaleT) {
Z
zhangjinchao01 已提交
2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061
  CHECK(!c->isTransposed()) << "Not supported";
  CHECK_EQ(c->getValueType(), FLOAT_VALUE);

  real* A = a->getData();
  real* B = b->getData();
  real* C = c->getValue();
  int* rows = c->getRows();
  int* cols = c->getCols();
  size_t height = c->getHeight();
  size_t width = c->getWidth();
  if (scaleT == 0) {
    c->zeroMem();
  }

  if (!a->isTransposed() && !b->isTransposed()) {
    size_t m = a->getWidth();
    CHECK_EQ(b->getHeight(), m);
    CHECK_EQ(a->getHeight(), height);
    CHECK_EQ(b->getWidth(), width);
    if (c->getFormat() == SPARSE_CSC) {
      for (size_t i = 0; i < width; i++) {
        size_t start = c->getColStartIdx(i);
        size_t end = c->getColStartIdx(i + 1);
        for (size_t j = start; j < end; j++) {
          real sum = 0;
          size_t rowIdx = rows[j];
          for (size_t k = 0; k < m; k++) {
            sum += A[rowIdx * m + k] * B[k * width + i];
          }
          C[j] = scaleAB * sum + scaleT * C[j];
        }
      }
    } else {
      for (size_t i = 0; i < height; i++) {
        size_t start = c->getRowStartIdx(i);
        size_t end = c->getRowStartIdx(i + 1);
        for (size_t j = start; j < end; j++) {
          real sum = 0;
          size_t colIdx = cols[j];
          for (size_t k = 0; k < m; k++) {
            sum += A[i * m + k] * B[k * width + colIdx];
          }
          C[j] = scaleAB * sum + scaleT * C[j];
        }
      }
    }
  } else if (a->isTransposed() && !b->isTransposed()) {
    size_t m = a->getHeight();
    CHECK_EQ(m, b->getHeight());
    CHECK_EQ(b->getWidth(), width);
    CHECK_EQ(a->getWidth(), height);

    if (c->getFormat() == SPARSE_CSC) {
      for (size_t i = 0; i < width; i++) {
        size_t start = c->getColStartIdx(i);
        size_t end = c->getColStartIdx(i + 1);
        for (size_t j = start; j < end; j++) {
          real sum = 0;
          size_t rowIdx = rows[j];
          for (size_t k = 0; k < m; k++) {
            sum += A[k * height + rowIdx] * B[k * width + i];
          }
          C[j] = scaleAB * sum + scaleT * C[j];
        }
      }
    } else {
      for (size_t i = 0; i < height; i++) {
        int start = c->getRowStartIdx(i);
        int end = c->getRowStartIdx(i + 1);
        for (int j = start; j < end; j++) {
          real sum = 0;
          size_t colIdx = cols[j];
          for (size_t k = 0; k < m; k++) {
            sum += A[k * height + i] * B[k * width + colIdx];
          }
          C[j] = scaleAB * sum + scaleT * C[j];
        }
      }
    }
  } else if (!a->isTransposed() && b->isTransposed()) {
    size_t m = a->getWidth();
    CHECK_EQ(b->getWidth(), m);
    CHECK_EQ(a->getHeight(), height);
    CHECK_EQ(b->getHeight(), width);
    if (c->getFormat() == SPARSE_CSR) {
      for (size_t i = 0; i < height; i++) {
        size_t start = c->getRowStartIdx(i);
        size_t end = c->getRowStartIdx(i + 1);
        for (size_t j = start; j < end; j++) {
          real sum = 0;
          size_t colIdx = cols[j];
          for (size_t k = 0; k < m; k++) {
            sum += A[i * m + k] * B[colIdx * m + k];
          }
          C[j] = scaleAB * sum + scaleT * C[j];
        }
      }
    } else {
      LOG(FATAL) << "Not supported csc format "
                    "when a is not trans and b is trans";
    }
  } else {
    LOG(FATAL) << "Not supported";
  }
}

3062 3063 3064
void CpuMatrix::mul(CpuMatrix* a,
                    CpuSparseMatrix* b,
                    real scaleAB,
Z
zhangjinchao01 已提交
3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101
                    real scaleT) {
  CHECK(!trans_) << "Not supported";
  CHECK(!a->isTransposed()) << "Not supported";
  CHECK(scaleT == 0 || scaleT == 1);

  // TODO(yuyang18): Maybe bug implementation here
  CHECK_EQ(scaleAB, static_cast<real>(1.0));

  real* A = a->getData();
  real* B = b->getValue();
  real* C = getData();
  int* rows = b->getRows();
  int* cols = b->getCols();

  if (scaleT == 0) {
    zeroMem();
  }
  if (b->getFormat() == SPARSE_CSC) {
    if (!b->isTransposed()) {
      size_t m = a->getWidth();
      CHECK_EQ(b->getHeight(), m);
      CHECK_EQ(a->getHeight(), height_);
      CHECK_EQ(b->getWidth(), width_);

      if (b->getValueType() == NO_VALUE) {
        for (size_t j = 0; j < b->getWidth(); ++j) {
          int start = b->getColStartIdx(j);
          int end = b->getColStartIdx(j + 1);
          for (int i = start; i < end; ++i) {
            colVecAddTo(C + j, A + rows[i], height_, width_, a->getWidth());
          }
        }
      } else if (b->getValueType() == FLOAT_VALUE) {
        for (size_t j = 0; j < b->getWidth(); ++j) {
          int start = b->getColStartIdx(j);
          int end = b->getColStartIdx(j + 1);
          for (int i = start; i < end; ++i) {
3102 3103
            colVecAddTo(
                C + j, A + rows[i], B[i], height_, width_, a->getWidth());
Z
zhangjinchao01 已提交
3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124
          }
        }
      }
    } else /*if (b->isTransposed())*/ {
      size_t m = a->getWidth();
      CHECK_EQ(b->getHeight(), width_);
      CHECK_EQ(a->getHeight(), height_);
      CHECK_EQ(b->getWidth(), m);
      if (b->getValueType() == NO_VALUE) {
        for (size_t i = 0; i < b->getWidth(); ++i) {
          int start = b->getColStartIdx(i);
          int end = b->getColStartIdx(i + 1);
          for (int j = start; j < end; ++j) {
            colVecAddTo(C + rows[j], A + i, height_, width_, a->getWidth());
          }
        }
      } else if (b->getValueType() == FLOAT_VALUE) {
        for (size_t i = 0; i < b->getWidth(); ++i) {
          int start = b->getColStartIdx(i);
          int end = b->getColStartIdx(i + 1);
          for (int j = start; j < end; ++j) {
3125 3126
            colVecAddTo(
                C + rows[j], A + i, B[j], height_, width_, a->getWidth());
Z
zhangjinchao01 已提交
3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150
          }
        }
      }
    }
  } else {
    if (!b->isTransposed()) {
      size_t m = a->getWidth();
      CHECK_EQ(b->getHeight(), m);
      CHECK_EQ(a->getHeight(), height_);
      CHECK_EQ(b->getWidth(), width_);

      if (b->getValueType() == NO_VALUE) {
        for (size_t j = 0; j < b->getHeight(); ++j) {
          int start = b->getRowStartIdx(j);
          int end = b->getRowStartIdx(j + 1);
          for (int i = start; i < end; ++i) {
            colVecAddTo(C + cols[i], A + j, height_, width_, a->getWidth());
          }
        }
      } else if (b->getValueType() == FLOAT_VALUE) {
        for (size_t j = 0; j < b->getHeight(); ++j) {
          int start = b->getRowStartIdx(j);
          int end = b->getRowStartIdx(j + 1);
          for (int i = start; i < end; ++i) {
3151 3152
            colVecAddTo(
                C + cols[i], A + j, B[i], height_, width_, a->getWidth());
Z
zhangjinchao01 已提交
3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173
          }
        }
      }
    } else /*if (b->isTransposed())*/ {
      size_t m = a->getWidth();
      CHECK_EQ(b->getHeight(), width_);
      CHECK_EQ(a->getHeight(), height_);
      CHECK_EQ(b->getWidth(), m);
      if (b->getValueType() == NO_VALUE) {
        for (size_t i = 0; i < b->getHeight(); ++i) {
          int start = b->getRowStartIdx(i);
          int end = b->getRowStartIdx(i + 1);
          for (int j = start; j < end; ++j) {
            colVecAddTo(C + i, A + cols[j], height_, width_, a->getWidth());
          }
        }
      } else if (b->getValueType() == FLOAT_VALUE) {
        for (size_t i = 0; i < b->getHeight(); ++i) {
          int start = b->getRowStartIdx(i);
          int end = b->getRowStartIdx(i + 1);
          for (int j = start; j < end; ++j) {
3174 3175
            colVecAddTo(
                C + i, A + cols[j], B[j], height_, width_, a->getWidth());
Z
zhangjinchao01 已提交
3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273
          }
        }
      }
    }
  }
}

void CpuMatrix::selectRows(Matrix& table, IVector& ids) {
  if (dynamic_cast<CacheRowCpuMatrix*>(&table)) {
    selectRowsImp(*dynamic_cast<CacheRowCpuMatrix*>(&table), ids);
  } else if (dynamic_cast<SparseRowCpuMatrix*>(&table)) {
    selectRowsImp(*dynamic_cast<SparseRowCpuMatrix*>(&table), ids);
  } else {
    CHECK(table.isContiguous());
    selectRowsImp(*dynamic_cast<CpuMatrix*>(&table), ids);
  }
}

void CpuMatrix::selectElements(Matrix& table, IVector& ids) {
  CHECK_EQ(table.getHeight(), ids.getSize());
  CHECK_EQ(getHeight(), ids.getSize());
  CHECK_EQ(getWidth(), 1U);
  real* tableData = table.getData();
  int* idsData = ids.getData();
  for (size_t i = 0; i < table.getHeight(); i++) {
    data_[i] += tableData[i * table.getWidth() + idsData[i]];
  }
}

void CpuMatrix::addElements(Matrix& table, IVector& ids) {
  CHECK_EQ(table.getHeight(), ids.getSize());
  CHECK_EQ(getHeight(), ids.getSize());
  CHECK_EQ(getWidth(), 1U);
  real* tableData = table.getData();
  int* idsData = ids.getData();
  for (size_t i = 0; i < table.getHeight(); i++) {
    tableData[i * table.getWidth() + idsData[i]] += data_[i];
  }
}

// this.row[i] += table.row[ids[i]]
template <typename TableMatType>
void CpuMatrix::selectRowsImp(TableMatType& table, IVector& ids) {
  CHECK(!table.useGpu());
  CHECK(!ids.useGpu());
  CHECK_EQ(getHeight(), ids.getSize());
  CHECK_EQ(getWidth(), table.getWidth());
  size_t numSamples = getHeight();
  size_t dim = getWidth();
  real* a = getData();
  size_t tableSize = table.getHeight();
  int* index = ids.getData();

  for (size_t i = 0; i < numSamples; ++i) {
    if (index[i] == -1) continue;
    CHECK_LT(index[i], (int)tableSize);
    CHECK_GE(index[i], 0);
    vecAddTo(a + i * stride_, table.getRow(index[i]), dim);
  }
}

void CpuMatrix::addToRows(Matrix& table, IVector& ids) {
  if (dynamic_cast<CacheRowCpuMatrix*>(&table)) {
    addToRowsImp(*dynamic_cast<CacheRowCpuMatrix*>(&table), ids);
  } else if (dynamic_cast<SparseAutoGrowRowCpuMatrix*>(&table)) {
    addToRowsImp(*dynamic_cast<SparseAutoGrowRowCpuMatrix*>(&table), ids);
  } else if (dynamic_cast<SparseRowCpuMatrix*>(&table)) {
    addToRowsImp(*dynamic_cast<SparseRowCpuMatrix*>(&table), ids);
  } else {
    CHECK(table.isContiguous());
    addToRowsImp(*dynamic_cast<CpuMatrix*>(&table), ids);
  }
}

// table.row[ids[i]] += this.row[i]
template <typename TableMatType>
void CpuMatrix::addToRowsImp(TableMatType& table, IVector& ids) {
  CHECK(!table.useGpu());
  CHECK(!ids.useGpu());
  CHECK_EQ(getHeight(), ids.getSize());
  CHECK_EQ(getWidth(), table.getWidth());
  size_t numSamples = getHeight();
  size_t dim = getWidth();
  real* a = getData();
  size_t tableSize = table.getHeight();
  int* index = ids.getData();

  for (size_t i = 0; i < numSamples; ++i) {
    if (index[i] == -1) continue;
    CHECK_LT(index[i], (int)tableSize);
    CHECK_GE(index[i], 0);
    vecAddTo(table.getRow(index[i]), a + i * stride_, dim);
  }
}

static ThreadLocal<std::vector<const real*>> threadLocalColArray;

template <typename MatBType, typename MatCType>
3274 3275
void CpuMatrix::mul(
    CpuSparseMatrix* a, MatBType* b, MatCType* c, real scaleAB, real scaleT) {
Z
zhangjinchao01 已提交
3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377
  CHECK(!c->isTransposed()) << "Not supported";
  CHECK(!b->isTransposed()) << "Not supported";
  // TODO(yuyang18): Maybe bug implementation here.
  CHECK(scaleAB == 1) << "Not supported";
  CHECK(scaleT == 0 || scaleT == 1) << "Not supported";
  CHECK_EQ(a->getFormat(), SPARSE_CSR) << "Not supported";

  real* B = b->getData();
  real* C = c->getData();
  size_t height = c->getHeight();
  size_t width = c->getWidth();
  int* cols = a->getCols();
  real* values = a->getValue();

  if (scaleT == 0) {
    c->zeroMem();
  }

  if (!a->isTransposed()) {
    size_t m = a->getWidth();
    CHECK_EQ(b->getHeight(), m);
    CHECK_EQ(a->getHeight(), height);
    CHECK_EQ(b->getWidth(), width);

    if (a->getValueType() == NO_VALUE) {
      if (width % 32 == 0) {  // use libaddto
        // @TODO(yuyang18) Make input addr can be unaligned.
        // So merge this if and else
        CHECK_EQ((size_t)B % 32, 0UL);
        CHECK_EQ((size_t)C % 32, 0UL);
        auto& colArray = *threadLocalColArray;
        for (size_t i = 0; i < a->getHeight(); ++i) {
          const int start = a->getRowStartIdx(i);
          const int end = a->getRowStartIdx(i + 1);
          size_t colNum = end - start;
          colArray.resize(colNum);
          for (int j = 0; j < end - start; ++j) {
            colArray[j] = b->getRow(cols[j + start]);
          }
          simd::batchAddTo(c->getRow(i), &colArray[0], colNum, width);
        }

      } else {
        for (size_t i = 0; i < a->getHeight(); ++i) {
          const int start = a->getRowStartIdx(i);
          const int end = a->getRowStartIdx(i + 1);
          for (int j = start; j < end; ++j) {
            vecAddTo(c->getRow(i), b->getRow(cols[j]), width);
          }
        }
      }
    } else if (a->getValueType() == FLOAT_VALUE) {
      for (size_t i = 0; i < a->getHeight(); ++i) {
        const int start = a->getRowStartIdx(i);
        const int end = a->getRowStartIdx(i + 1);
        for (int j = start; j < end; ++j) {
          vecAddTo(c->getRow(i), b->getRow(cols[j]), values[j], width);
        }
      }
    }
  } else /*if (a->isTransposed())*/ {
    size_t m = a->getHeight();
    CHECK_EQ(b->getHeight(), m);
    CHECK_EQ(a->getWidth(), height);
    CHECK_EQ(b->getWidth(), width);
    if (a->getValueType() == NO_VALUE) {
      if (width % 32 == 0) {  // use libaddto
        // @TODO(yuyang18) Make input addr can be unaligned.
        // So merge this if and else
        CHECK_EQ((size_t)B % 32, 0UL);
        CHECK_EQ((size_t)C % 32, 0UL);
        for (size_t i = 0; i < a->getHeight(); ++i) {
          const int start = a->getRowStartIdx(i);
          const int end = a->getRowStartIdx(i + 1);
          for (int j = start; j < end; ++j) {
            simd::addTo(c->getRow(cols[j]), b->getRow(i), width);
          }
        }

      } else {
        for (size_t i = 0; i < a->getHeight(); ++i) {
          const int start = a->getRowStartIdx(i);
          const int end = a->getRowStartIdx(i + 1);
          for (int j = start; j < end; ++j) {
            vecAddTo(c->getRow(cols[j]), b->getRow(i), width);
          }
        }
      }
    } else if (a->getValueType() == FLOAT_VALUE) {
      for (size_t i = 0; i < a->getHeight(); ++i) {
        const int start = a->getRowStartIdx(i);
        const int end = a->getRowStartIdx(i + 1);
        for (int j = start; j < end; ++j) {
          vecAddTo(c->getRow(cols[j]), b->getRow(i), values[j], width);
        }
      }
    }
  }
}

// instantiation mul() called in SparseRowMatrix.cpp
template void CpuMatrix::mul<CpuMatrix, SparseRowCpuMatrix>(
3378 3379 3380 3381
    CpuSparseMatrix* a,
    CpuMatrix* b,
    SparseRowCpuMatrix* c,
    real scaleAB,
Z
zhangjinchao01 已提交
3382 3383
    real scaleT);
template void CpuMatrix::mul<CpuMatrix, SparseAutoGrowRowCpuMatrix>(
3384 3385 3386 3387 3388
    CpuSparseMatrix* a,
    CpuMatrix* b,
    SparseAutoGrowRowCpuMatrix* c,
    real scaleAB,
    real scaleT);
Z
zhangjinchao01 已提交
3389 3390 3391 3392 3393 3394
template void CpuMatrix::mul<CpuMatrix, CacheRowCpuMatrix>(CpuSparseMatrix* a,
                                                           CpuMatrix* b,
                                                           CacheRowCpuMatrix* c,
                                                           real scaleAB,
                                                           real scaleT);

3395
#ifndef PADDLE_MOBILE_INFERENCE
3396 3397 3398
void SharedCpuMatrix::mul(CpuSparseMatrix* a,
                          CpuMatrix* b,
                          real scaleAB,
Z
zhangjinchao01 已提交
3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437
                          real scaleT) {
  CHECK(!isTransposed()) << "Not supported";
  CHECK(!b->isTransposed()) << "Not supported";
  CHECK_EQ(scaleAB, 1) << "Not supported";
  CHECK_EQ(scaleT, 1) << "Not supported";
  CHECK_EQ(a->getFormat(), SPARSE_CSR) << "not supported";

  real* B = b->getData();
  real* C = getData();
  size_t height = getHeight();
  size_t width = getWidth();

  // get real trans
  MatrixPtr aTrans;
  if (a->isTransposed()) {
    aTrans = a->getTmpSparseMatrix(a->getWidth(), a->getHeight());
    a->transpose(aTrans, false);
  }
  a = dynamic_cast<CpuSparseMatrix*>(aTrans.get());

  size_t m = a->getWidth();
  CHECK_EQ(b->getHeight(), m);
  CHECK_EQ(a->getHeight(), height);
  CHECK_EQ(b->getWidth(), width);

  size_t blockSize = (height / blockNum_) + 1;
  CpuMatrixPtr localBuf = *localBuf_;
  if (!localBuf) {
    localBuf = std::make_shared<CpuMatrix>(blockSize, width);
  } else {
    localBuf->resize(blockSize, width);
  }
  localBuf->zeroMem();
  real* localC = localBuf->getData();
  std::vector<int>& blockSeq = *blockSeq_;
  if (blockSeq.size() == 0) {
    for (int k = 0; k < blockNum_; ++k) {
      blockSeq.push_back(k);
    }
3438 3439
    std::shuffle(
        blockSeq.begin(), blockSeq.end(), ThreadLocalRandomEngine::get());
Z
zhangjinchao01 已提交
3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476
  }
  std::vector<int>& localBufRows = *localBufRows_;
  int* cols = a->getCols();
  real* value = a->getValue();

  for (int k = 0; k < blockNum_; ++k) {
    int blockId = blockSeq[k];
    size_t blockBegin = blockId * blockSize;
    size_t blockEnd = (blockId + 1) * blockSize;
    if (blockId == blockNum_ - 1) {
      blockEnd = height;
    }
    if (a->getValueType() == NO_VALUE) {
      for (size_t i = blockBegin; i < blockEnd; ++i) {
        int start = a->getRowStartIdx(i);
        int end = a->getRowStartIdx(i);
        size_t colNum = a->getColNum(i);
        if (colNum == 0) {
          continue;
        }  // skip empty row
        localBufRows.push_back(i);
        size_t bufPos = localBufRows.size() - 1;
        for (int j = start; j < end; ++j) {
          vecAddTo(localC + bufPos * width, B + cols[j] * width, width);
        }
      }
    } else if (a->getValueType() == FLOAT_VALUE) {
      for (size_t i = blockBegin; i < blockEnd; ++i) {
        int start = a->getRowStartIdx(i);
        int end = a->getRowStartIdx(i);
        size_t colNum = a->getColNum(i);
        if (colNum == 0) {
          continue;
        }  // skip empty row
        localBufRows.push_back(i);
        size_t bufPos = localBufRows.size() - 1;
        for (int j = start; j < end; ++j) {
3477 3478
          vecAddTo(
              localC + bufPos * width, B + cols[j] * width, value[j], width);
Z
zhangjinchao01 已提交
3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523
        }
      }
    }

    {
      std::lock_guard<std::mutex> guard(*blockLocks_[blockId]);
      for (size_t i = 0; i < localBufRows.size(); ++i) {
        vecAddTo(C + localBufRows[i] * width, localC + i * width, width);
      }
    }
    memset(localC, 0, localBufRows.size() * width * sizeof(real));
    localBufRows.clear();
  }

  VLOG(2) << " B[0]=" << B[0] << " B[1]=" << B[1] << " C[0]=" << C[0]
          << " C[1]=" << C[1];
}

void SharedCpuMatrix::add(Matrix& b, real p1, real p2) {
  CHECK_EQ(blockNum_, 1);
  std::lock_guard<std::mutex> guard(*blockLocks_[0]);
  CpuMatrix::add(b, p1, p2);
}

void SharedCpuMatrix::add(real p1, real p2) {
  CHECK_EQ(blockNum_, 1);
  std::lock_guard<std::mutex> guard(*blockLocks_[0]);
  CpuMatrix::add(p1, p2);
}

void SharedCpuMatrix::initShared(int blockNum) {
  CHECK_GT(height_ * width_, 1UL * 1024 * 1024)
      << "should not share small matrix";
  initBlock(blockNum);
}

void SharedCpuMatrix::initBlock(int blockNum) {
  CHECK_LE(blockNum, 200) << "should not use large block number";
  blockNum_ = blockNum;
  blockLocks_.resize(blockNum);
  for (auto& locker : blockLocks_) {
    locker.reset(new std::mutex);
  }
}

3524
#endif
Z
zhangjinchao01 已提交
3525 3526 3527 3528 3529 3530
/* Add a (column) vector b to matrix a, column by column */
void CpuMatrix::addColumnVector(const Matrix& b) {
  BaseMatrix::addColVector(const_cast<Matrix&>(b));
}

/* this = a*b */
3531
void CpuMatrix::mul(const Matrix& a, const Matrix& b) {
Z
zhangjinchao01 已提交
3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562
  return mul(a, b, 1.0, 0.0);
}

/* this = scaleAB*(this*b) +  scaleT*this */
void CpuMatrix::rightMul(Matrix& b, real scaleAB, real scaleT) {
  (void)b;
  (void)scaleAB;
  (void)scaleT;
  LOG(FATAL) << "Not implemented";
}

/* this = this* b */
void CpuMatrix::rightMul(Matrix& b) { return rightMul(b, 1.0, 0.0); }

/* this = scaleAB*(a*this) +  scaleT*this */
void CpuMatrix::leftMul(Matrix& a, real scaleAB, real scaleT) {
  (void)a;
  (void)scaleAB;
  (void)scaleT;
  LOG(FATAL) << "Not implemented";
}

/* this = a*this) */
void CpuMatrix::leftMul(Matrix& a) { return leftMul(a, 1.0, 0.0); }

void CpuMatrix::colMerge(Matrix& src) { src.rowSum(*this); }

void CpuMatrix::rowSum(Matrix& sum) {
  CHECK_EQ(sum.getHeight(), getHeight());
  CHECK_EQ(sum.getWidth(), (size_t)1);

3563
  sum.sumRows(*this, /* scaleSum= */ 1, /* scaleDest= */ 0);
Z
zhangjinchao01 已提交
3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594
}

void CpuMatrix::rowMaxId(IVector& maxIds) {
  CHECK(!maxIds.useGpu()) << "Matrix type are not equal";

  size_t numSamples = getHeight();
  CHECK_EQ(maxIds.getSize(), numSamples);

  real* a = getData();
  int* s = maxIds.getData();
  size_t dim = getWidth();

  for (size_t i = 0; i < numSamples; i++) {
    real sm = a[i * dim];
    int maxId = 0;
    for (size_t j = 1; j < dim; j++) {
      if (a[i * dim + j] > sm) {
        maxId = j;
        sm = a[i * dim + j];
      }
    }
    s[i] = maxId;
  }
}

void CpuMatrix::rowMax(Matrix& max) {
  CHECK_EQ(max.getHeight(), getHeight());
  CHECK_EQ(max.getWidth(), (size_t)1);
  max.maxRows(*this);
}

L
Liang Zhao 已提交
3595
/* Get the top k elements of each row of this matrix */
Z
zhangjinchao01 已提交
3596 3597 3598 3599 3600 3601 3602
void CpuMatrix::rowMax(IVector& maxIds, Matrix& maxVal) {
  CHECK(isContiguous());
  CHECK(!maxIds.useGpu() && !maxVal.useGpu()) << "Matrix type are not equal";
  size_t numSamples = getHeight();
  size_t beam = maxVal.getWidth();
  CHECK_EQ(maxIds.getSize(), numSamples * beam);
  CHECK_EQ(maxVal.getHeight(), numSamples);
L
Liang Zhao 已提交
3603
  CHECK_EQ(maxVal.getWidth(), beam);
Z
zhangjinchao01 已提交
3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615

  real* a = getData();
  int* s = maxIds.getData();
  real* t = maxVal.getData();
  size_t dim = getWidth();
  for (size_t i = 0; i < numSamples; i++) {
    std::vector<std::pair<real, size_t>> vec;
    for (size_t j = 0; j < dim; j++) {
      vec.push_back(std::pair<real, size_t>(a[i * dim + j], j));
    }

    std::partial_sort(
3616 3617 3618
        vec.begin(),
        vec.begin() + beam,
        vec.end(),
Z
zhangjinchao01 已提交
3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634
        [](const std::pair<real, size_t>& l, const std::pair<real, size_t>& r) {
          return l.first > r.first;
        });
    for (size_t j = 0; j < beam; j++) {
      t[i * beam + j] = vec[j].first;
      s[i * beam + j] = vec[j].second;
    }
  }
}

void CpuMatrix::colMax(Matrix& max) {
  CHECK_EQ(max.getWidth(), getWidth());
  CHECK_EQ(max.getHeight(), (size_t)1);
  max.maxCols(*this);
}

3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653
void CpuMatrix::colMax(IVector& maxIds, Matrix& maxVal) {
  CHECK(isContiguous());
  CHECK(!maxIds.useGpu() && !maxVal.useGpu()) << "Matrix type are not equal";
  size_t numSamples = getWidth();
  size_t beam = maxVal.getHeight();
  CHECK_EQ(maxIds.getSize(), numSamples * beam);
  CHECK_EQ(maxVal.getWidth(), numSamples);

  real* a = getData();
  int* s = maxIds.getData();
  real* t = maxVal.getData();
  size_t dim = getHeight();
  for (size_t i = 0; i < numSamples; i++) {
    std::vector<std::pair<real, size_t>> vec;
    for (size_t j = 0; j < dim; j++) {
      vec.push_back(std::pair<real, size_t>(a[i + j * numSamples], j));
    }

    std::partial_sort(
3654 3655 3656
        vec.begin(),
        vec.begin() + beam,
        vec.end(),
3657 3658 3659 3660 3661 3662 3663 3664 3665 3666
        [](const std::pair<real, size_t>& l, const std::pair<real, size_t>& r) {
          return l.first > r.first;
        });
    for (size_t j = 0; j < beam; j++) {
      t[i + j * numSamples] = vec[j].first;
      s[i + j * numSamples] = vec[j].second;
    }
  }
}

3667 3668 3669
void CpuMatrix::maxoutForward(Matrix& a,
                              IVector& id,
                              size_t channels,
3670 3671 3672 3673 3674 3675 3676 3677
                              size_t groups) {
  CHECK(dynamic_cast<CpuMatrix*>(&a));
  CHECK(dynamic_cast<CpuIVector*>(&id));
  CHECK_EQ(a.getHeight(), getHeight());

  size_t size = getWidth();
  size_t batchSize = getHeight();
  size_t featLen = size / channels;
Q
qijun 已提交
3678
  const real* input = a.getData();
3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701
  int* idForCpu = id.getData();

  MatrixPtr maxInMat, maxOutMat;
  Matrix::resizeOrCreate(maxInMat, groups, size, false, false);
  Matrix::resizeOrCreate(maxOutMat, 1, size, false, false);

  for (size_t batch_idx = 0; batch_idx < batchSize; ++batch_idx) {
    size_t newIndex = batch_idx * size;
    IVectorPtr tmpId = IVector::create(idForCpu + newIndex, size, false);

    for (size_t i = 0; i < channels; ++i) {
      size_t newFeatLen = i * featLen;
      for (size_t j = 0; j < groups; ++j) {
        maxInMat->subMatrix(j, j + 1, newFeatLen, newFeatLen + featLen)
            ->copyFrom(input + (newIndex + newFeatLen) * groups + j * featLen,
                       featLen);
      }
    }
    maxInMat->colMax(*tmpId, *maxOutMat);
    this->subRowMatrix(batch_idx, batch_idx + 1)->copyFrom(*maxOutMat);
  }
}

3702 3703 3704
void CpuMatrix::maxoutBackward(Matrix& a,
                               IVector& id,
                               size_t channels,
3705 3706 3707 3708 3709 3710 3711 3712 3713
                               size_t groups) {
  CHECK(dynamic_cast<CpuMatrix*>(&a));
  CHECK(dynamic_cast<CpuIVector*>(&id));
  CHECK_EQ(a.getHeight(), getHeight());

  size_t size = a.getWidth();
  size_t batchSize = getHeight();
  size_t featLen = size / channels;
  size_t newFeatLen = groups * featLen;
Q
qijun 已提交
3714 3715
  real* inputG = getData();
  const real* outG = a.getData();
3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729
  int* idForCpu = id.getData();

  for (size_t batch_idx = 0; batch_idx < batchSize; ++batch_idx) {
    size_t newIndex = batch_idx * size;
    int* idData = idForCpu + newIndex;

    for (size_t i = 0; i < size; ++i) {
      int gradIdx =
          idData[i] * featLen + (i / featLen) * newFeatLen + i % featLen;
      (inputG + newIndex * groups)[gradIdx] += (outG + newIndex)[i];
    }
  }
}

Z
zhangjinchao01 已提交
3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754
void CpuMatrix::rowNormalizeL1(Matrix& out) {
  CHECK(!out.useGpu());

  size_t numSamples = getHeight();
  size_t dim = getWidth();
  CHECK_EQ(out.getHeight(), numSamples);
  CHECK_EQ(out.getWidth(), dim);
  real* a = getData();
  real* b = out.getData();
  for (size_t i = 0; i < numSamples; ++i) {
    real s = 0;
    for (size_t j = 0; j < dim; ++j) {
      s += a[i * dim + j];
    }
    // Right now, we just bet that sum won't be zero. If this really happens,
    // we will figure out what should be done then.
    CHECK_GT(s, 0);
    s = 1 / s;
    for (size_t j = 0; j < dim; ++j) {
      b[i * dim + j] = s * a[i * dim + j];
    }
  }
}

/* calulate classification error */
3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768
void CpuMatrix::classificationError(Matrix& output,
                                    IVector& label,
                                    size_t topkSize) {
  size_t numSamples = this->getHeight();
  auto cpuOutput = dynamic_cast<CpuMatrix*>(&output);
  auto cpuLabel = dynamic_cast<CpuIVector*>(&label);
  IVectorPtr cpuTopIds = std::make_shared<CpuIVector>(numSamples * topkSize);
  MatrixPtr cpuTopVal = std::make_shared<CpuMatrix>(numSamples, topkSize);

  CHECK(cpuOutput && cpuLabel) << "Invalid argument pointer";
  CHECK(cpuTopIds && cpuTopVal) << "Allocate cpu memory failed";
  CHECK(cpuLabel->getSize() == numSamples) << "Vector size is not equal";
  CHECK(cpuOutput->getHeight() == numSamples && this->getWidth() == 1)
      << "Matrix dimensions are not equal";
Z
zhangjinchao01 已提交
3769

3770 3771
  // top k matrix classification
  cpuOutput->rowMax(*cpuTopIds, *cpuTopVal);
Z
zhangjinchao01 已提交
3772

3773 3774 3775 3776
  size_t dim = cpuOutput->getWidth();
  real* result = this->getData();
  int* ids = cpuTopIds->getData();
  int* lbl = cpuLabel->getData();
Z
zhangjinchao01 已提交
3777 3778 3779
  for (size_t i = 0; i < numSamples; ++i) {
    CHECK_GE(lbl[i], 0);
    CHECK_LT((size_t)lbl[i], dim);
3780 3781 3782 3783 3784

    for (size_t j = 0; j < topkSize; ++j) {
      if (ids[j + i * topkSize] == lbl[i]) {
        result[i] = 0;
        break;
Z
zhangjinchao01 已提交
3785
      }
3786
      result[i] = 1.0f;
Z
zhangjinchao01 已提交
3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831
    }
  }
}

/* copy -log(output[label]) to this->data[i] */
void CpuMatrix::oneHotCrossEntropy(Matrix& output, IVector& label) {
  CHECK(dynamic_cast<CpuMatrix*>(&output));
  CHECK(dynamic_cast<CpuIVector*>(&label));

  size_t numSamples = getHeight();
  size_t dim = output.getWidth();
  CHECK_EQ(label.getSize(), numSamples);
  CHECK_EQ(output.getHeight(), numSamples);
  CHECK_EQ(getWidth(), (size_t)1);

  real* out = output.getData();
  real* cost = getData();
  int* lbl = label.getData();
  for (size_t i = 0; i < numSamples; ++i, out += dim) {
    CHECK_GE(lbl[i], 0);
    CHECK_LT((size_t)lbl[i], dim);
    cost[i] = -std::log(out[lbl[i]]);
  }
}

/* calculate the error of outputV according to label */
void CpuMatrix::oneHotCrossEntropyBp(Matrix& output, IVector& label) {
  CHECK(dynamic_cast<CpuMatrix*>(&output));
  CHECK(dynamic_cast<CpuIVector*>(&label));
  size_t numSamples = getHeight();
  size_t dim = getWidth();
  CHECK_EQ(output.getWidth(), dim);
  real* out = output.getData();
  real* grad = getData();
  int* lbl = label.getData();
  for (size_t i = 0; i < numSamples; ++i, out += dim, grad += dim) {
    grad[lbl[i]] -= 1 / out[lbl[i]];
  }
}

/*
    We implement the matrix functionality in CostLayer.cpp,
    but we define the scalar function here for sanity check
    deletion of the function does not affect anything neverthelss
*/
3832 3833
void CpuMatrix::oneHotCrossEntropyWithSelfNorm(Matrix& output,
                                               IVector& label,
Z
zhangjinchao01 已提交
3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863
                                               real alpha) {
  CHECK(dynamic_cast<CpuMatrix*>(&output));
  CHECK(dynamic_cast<CpuIVector*>(&label));

  size_t numSamples = getHeight();
  size_t dim = output.getWidth();
  CHECK_EQ(label.getSize(), numSamples);
  CHECK_EQ(output.getHeight(), numSamples);
  CHECK_EQ(getWidth(), (size_t)1);

  real* out = output.getData();
  real* cost = getData();
  int* lbl = label.getData();
  for (size_t i = 0; i < numSamples; ++i, out += dim) {
    CHECK_GE(lbl[i], 0);
    CHECK_LT((size_t)lbl[i], dim);
    real sum = 0;
    for (size_t j = 0; j < dim; ++j) {
      sum += out[j];
    }
    sum = _safelog(sum);
    cost[i] = -_safelog(out[lbl[i]]) + sum + alpha * _square(sum);
  }
}

/*
    We implement the matrix functionality in CostLayer.cpp,
    but we define the scalar function here for sanity check
    deletion of the function does not affect anything neverthelss
*/
3864 3865
void CpuMatrix::oneHotCrossEntropyWithSelfNormBp(Matrix& output,
                                                 IVector& label,
Z
zhangjinchao01 已提交
3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945
                                                 real alpha) {
  CHECK(dynamic_cast<CpuMatrix*>(&output));
  CHECK(dynamic_cast<CpuIVector*>(&label));
  size_t numSamples = getHeight();
  size_t dim = getWidth();
  CHECK_EQ(output.getWidth(), dim);
  real* out = output.getData();
  real* grad = getData();
  int* lbl = label.getData();

  for (size_t i = 0; i < numSamples; ++i, out += dim, grad += dim) {
    grad[lbl[i]] -= 1 / out[lbl[i]];
    real sum = 0;
    for (size_t j = 0; j < dim; ++j) {
      sum += out[j];
    }
    for (size_t j = 0; j < dim; ++j) {
      if (j == (size_t)lbl[i]) {
        grad[j] += -1 / out[j];
      }
      grad[j] += 1 / sum + 2 * alpha * _safelog(sum) / sum;
    }
  }
}

#define FORWARD_LOOP()                      \
  size_t numSamples = getHeight();          \
  size_t dim = getWidth();                  \
  CHECK_EQ(output.getHeight(), numSamples); \
  CHECK_EQ(output.getWidth(), dim);         \
  const real* in = getData();               \
  real* out = output.getData();             \
  for (size_t i = 0; i < numSamples; ++i, in += dim, out += dim)

#define BACKWARD_LOOP()                     \
  size_t numSamples = getHeight();          \
  size_t dim = getWidth();                  \
  CHECK_EQ(output.getHeight(), numSamples); \
  CHECK_EQ(output.getWidth(), dim);         \
  real* grad = getData();                   \
  real* out = output.getData();             \
  for (size_t i = 0; i < numSamples; ++i, grad += dim, out += dim)

void CpuMatrix::softmax(Matrix& output) {
  CHECK(!output.useGpu());

  const float THRESHOLD = -64.0;

  FORWARD_LOOP() {
    real max = -1.0e20;
    for (size_t j = 0; j < dim; ++j) {
      if (in[j] > max) {
        max = in[j];
      }
    }
    for (size_t j = 0; j < dim; ++j) {
      real a = in[j] - max;
      if (a < THRESHOLD) {
        a = THRESHOLD;
      }
      out[j] = a;
    }
    vExp(dim, out, out);

    real sum = 0;
    for (size_t j = 0; j < dim; ++j) {
      sum += out[j];
    }
    sum = 1 / sum;
    for (size_t j = 0; j < dim; ++j) {
      out[j] *= sum;
    }
  }
}

void CpuMatrix::sequenceSoftmax(Matrix& output, const IVector& index) {
  CHECK_EQ(getWidth(), 1UL);
  CHECK_EQ(output.getWidth(), 1UL);
  CHECK(isContiguous());

3946 3947 3948 3949 3950 3951 3952 3953 3954 3955
  MatrixPtr inTmp = Matrix::create(nullptr,
                                   /* height= */ 1,
                                   1,
                                   /* trans= */ false,
                                   false);
  MatrixPtr outTmp = Matrix::create(nullptr,
                                    /* height= */ 1,
                                    1,
                                    /* trans= */ false,
                                    false);
Z
zhangjinchao01 已提交
3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007
  size_t numSequences = index.getSize() - 1;
  auto starts = index.getData();
  for (size_t i = 0; i < numSequences; ++i) {
    size_t offset = starts[i];
    size_t size = starts[i + 1] - starts[i];
    inTmp->setData(getData() + offset, 1UL, size);
    outTmp->setData(output.getData() + offset, 1UL, size);
    inTmp->softmax(*outTmp);
  }
}

void CpuMatrix::softmaxDerivative(Matrix& output, Matrix& sftmaxSum) {
  CHECK(output.useGpu_ == false) << "Matrix type are not equal";
  CHECK_EQ(getHeight(), sftmaxSum.getHeight());

  real* sums = sftmaxSum.getData();

  BACKWARD_LOOP() {
    real sum = sums[i];
    for (size_t j = 0; j < dim; ++j) {
      grad[j] = out[j] * (grad[j] - sum);
    }
  }
}

void CpuMatrix::sumOfSquares(Matrix& output, Matrix& label) {
  CHECK(output.useGpu_ == false && label.useGpu_ == false)
      << "Matrix type are not equal";

  size_t numSamples = getHeight();
  size_t dim = output.getWidth();
  CHECK_EQ(label.getHeight(), numSamples);
  CHECK_EQ(output.getHeight(), numSamples);
  CHECK_EQ(label.getWidth(), dim);
  CHECK_EQ(getWidth(), (size_t)1);
  real* out = output.getData();
  real* cost = getData();

  auto labelptr = dynamic_cast<CpuSparseMatrix*>(&label);
  if (labelptr) {
    // it is a CpuSparseMatrix
    if (labelptr->getFormat() == SPARSE_CSR) {
      // treat label as a SparseMatrix
      for (size_t i = 0; i < numSamples; ++i) {
        for (size_t j = 0; j < dim; ++j) {
          cost[i] += _square(out[i * dim + j]);
        }
      }
      if (labelptr->getValueType() == NO_VALUE) {
        int* cols = labelptr->getCols();
        for (size_t i = 0; i < numSamples; ++i) {
          for (size_t j = labelptr->getRowStartIdx(i);
4008 4009
               j < labelptr->getRowStartIdx(i + 1);
               ++j) {
Z
zhangjinchao01 已提交
4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024
            cost[i] += 1.0 - 2.0 * out[i * dim + cols[j]];
            /*
             * explanation of above line: original codes are follows:
             * cost[i] -= _square(out[i * dim + feature.col]);
             * cost[i] += _square(1.0 - out[i * dim + feature.col]);
             */
          }
        }
      } else if (labelptr->getValueType() == FLOAT_VALUE) {
        int* cols = labelptr->getCols();
        real* values = labelptr->getValue();
        for (size_t i = 0; i < numSamples; ++i) {
          real sum1 = 0;
          real sum2 = 0;
          for (size_t j = labelptr->getRowStartIdx(i);
4025 4026
               j < labelptr->getRowStartIdx(i + 1);
               ++j) {
Z
zhangjinchao01 已提交
4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047
            sum1 += values[j] * values[j];
            sum2 += values[j] * out[i * dim + cols[j]];
            /*
             * explanation of above line: original codes are follows:
             * cost[i] -= _square(out[i * dim + feature.col]);
             * cost[i] += _square(value.col - out[i * dim + feature.col]);
             */
          }
          cost[i] += sum1 - 2.0 * sum2;
        }
      } else {
        LOG(FATAL) << "unsupported sparse matrix value type in sumOfSquares";
        return;
      }
      return;
    } else {
      LOG(FATAL) << "unsupported sparse matrix format in sumOfSquares";
      return;
    }
  }

4048 4049 4050 4051
  BaseMatrix::sumOfSquaredDiffs(output,
                                label,
                                /* scaleSum= */ 1,
                                /* scaleDest= */ 1);
Z
zhangjinchao01 已提交
4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080
}

/* calculate the error of outputV according to label */
void CpuMatrix::sumOfSquaresBp(Matrix& output, Matrix& label) {
  CHECK(output.useGpu_ == false && label.useGpu_ == false)
      << "Matrix type are not equal";

  size_t numSamples = getHeight();
  size_t dim = getWidth();
  CHECK_EQ(output.getWidth(), dim);
  CHECK_EQ(label.getWidth(), dim);

  real* out = output.getData();
  real* grad = getData();

  auto labelptr = dynamic_cast<CpuSparseMatrix*>(&label);
  if (labelptr) {
    // it is a CpuSparseMatrix
    if (labelptr->getFormat() == SPARSE_CSR) {
      // treat label as a SparseMatrix
      for (size_t i = 0; i < numSamples; ++i) {
        for (size_t j = 0; j < dim; ++j) {
          grad[i * dim + j] += 2.0 * out[i * dim + j];
        }
      }
      if (labelptr->getValueType() == NO_VALUE) {
        int* cols = labelptr->getCols();
        for (size_t i = 0; i < numSamples; ++i) {
          for (size_t j = labelptr->getRowStartIdx(i);
4081 4082
               j < labelptr->getRowStartIdx(i + 1);
               ++j) {
Z
zhangjinchao01 已提交
4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096
            grad[i * dim + cols[j]] -= 2.0;
            /*
             * explanation of above line: original codes are follows:
             * grad[i * dim + feature.col] -= 2.0 * out[i * dim + feature.col];
             * grad[i * dim + feature.col] += 2.0 * (out[i * dim + feature.col]
             * - 1);
             */
          }
        }
      } else if (labelptr->getValueType() == FLOAT_VALUE) {
        int* cols = labelptr->getCols();
        real* values = labelptr->getValue();
        for (size_t i = 0; i < numSamples; ++i) {
          for (size_t j = labelptr->getRowStartIdx(i);
4097 4098
               j < labelptr->getRowStartIdx(i + 1);
               ++j) {
Z
zhangjinchao01 已提交
4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131
            grad[i * dim + cols[j]] -= 2.0 * values[j];
            /*
             * explanation of above line: original codes are follows:
             * grad[i * dim + feature.col] -= 2.0 * out[i * dim + feature.col];
             * grad[i * dim + feature.col] += 2.0 * (out[i * dim + feature.col]
             * - value.col);
             */
          }
        }
      } else {
        LOG(FATAL) << "unsupported sparse matrix value type in sumOfSquares";
        return;
      }
      return;
    } else {
      LOG(FATAL) << "unsupported sparse matrix format in sumOfSquares";
      return;
    }
  }

  real* lbl = label.getData();
  size_t ld = getStride();
  size_t outLd = output.getStride();
  size_t lblLd = label.getStride();
  CHECK(lbl);
  for (size_t i = 0; i < numSamples;
       ++i, out += outLd, lbl += lblLd, grad += ld) {
    for (size_t j = 0; j < dim; ++j) {
      grad[j] += 2.0 * (out[j] - lbl[j]);  // positive gradient;
    }
  }
}

4132
void CpuMatrix::smoothL1(Matrix& output, Matrix& label, real destScale) {
G
gaoyuan 已提交
4133 4134 4135 4136 4137 4138 4139 4140 4141
  CHECK(output.useGpu_ == false && label.useGpu_ == false)
      << "Matrix type are not equal";

  size_t numSamples = getHeight();
  size_t dim = output.getWidth();
  CHECK_EQ(label.getHeight(), numSamples);
  CHECK_EQ(output.getHeight(), numSamples);
  CHECK_EQ(label.getWidth(), dim);
  CHECK_EQ(getWidth(), (size_t)1);
D
dangqingqing 已提交
4142

G
gaoyuan 已提交
4143
  real* cost = getData();
D
dangqingqing 已提交
4144
  real* out = output.getData();
G
gaoyuan 已提交
4145 4146
  real* lbl = label.getData();

D
dangqingqing 已提交
4147
  for (size_t i = 0; i < numSamples; ++i, out += dim, lbl += dim) {
G
gaoyuan 已提交
4148
    for (size_t j = 0; j < dim; ++j) {
D
dangqingqing 已提交
4149
      real absVal = std::fabs(out[j] - lbl[j]);
4150
      cost[i] *= destScale;
D
dangqingqing 已提交
4151 4152
      if (absVal < 1.0)
        cost[i] += 0.5 * absVal * absVal;
G
gaoyuan 已提交
4153
      else
D
dangqingqing 已提交
4154
        cost[i] += absVal - 0.5;
G
gaoyuan 已提交
4155 4156 4157 4158
    }
  }
}

4159
void CpuMatrix::smoothL1Bp(Matrix& output, Matrix& label, real destScale) {
G
gaoyuan 已提交
4160 4161 4162 4163 4164 4165 4166 4167
  CHECK(output.useGpu_ == false && label.useGpu_ == false)
      << "Matrix type are not equal";

  size_t numSamples = getHeight();
  size_t dim = output.getWidth();
  CHECK_EQ(label.getHeight(), numSamples);
  CHECK_EQ(output.getHeight(), numSamples);
  CHECK_EQ(label.getWidth(), dim);
D
dangqingqing 已提交
4168 4169
  CHECK_EQ(getWidth(), dim);

G
gaoyuan 已提交
4170 4171
  real* out = output.getData();
  real* lbl = label.getData();
D
dangqingqing 已提交
4172
  real* grad = getData();
G
gaoyuan 已提交
4173

D
dangqingqing 已提交
4174
  for (size_t i = 0; i < numSamples; ++i, out += dim, grad += dim, lbl += dim) {
G
gaoyuan 已提交
4175
    for (size_t j = 0; j < dim; ++j) {
D
dangqingqing 已提交
4176
      real val = out[j] - lbl[j];
4177
      grad[j] *= destScale;
D
dangqingqing 已提交
4178 4179 4180 4181 4182
      if (std::fabs(val) < 1) {
        grad[j] += val;
      } else {
        grad[j] += (real(0) < val) - (val < real(0));
      }
G
gaoyuan 已提交
4183 4184 4185 4186
    }
  }
}

Z
zhangjinchao01 已提交
4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286
void CpuMatrix::tanh(Matrix& output) {
  CHECK(isContiguous());
  CHECK(output.isContiguous());
  size_t numSamples = getHeight();
  size_t dim = getWidth();
  CHECK_EQ(output.getHeight(), numSamples);
  CHECK_EQ(output.getWidth(), dim);
  vTanh(numSamples * dim, getData(), output.getData());
}

void CpuMatrix::tanhDerivative(Matrix& output) {
  BaseMatrix::tanhDerivative(output);
}

void CpuMatrix::softrelu(Matrix& output) {
  CHECK(isContiguous());
  CHECK(output.isContiguous());
  const real THRESHOLD = 40.0;
  FORWARD_LOOP() {  // TODO(yuyang18): SIMD it?
    for (size_t j = 0; j < dim; ++j) {
      real x = in[j];
      if (x > THRESHOLD) {
        x = THRESHOLD;
      } else if (x < -THRESHOLD) {
        x = -THRESHOLD;
      }
      out[j] = x;
    }
  }
  vExp(numSamples * dim, output.getData(), output.getData());
  vLog1p(numSamples * dim, output.getData(), output.getData());
}

void CpuMatrix::softreluDerivative(Matrix& output) {
  CHECK(isContiguous());
  CHECK(output.isContiguous());
  size_t numSamples = getHeight();
  size_t dim = getWidth();
  size_t size = numSamples * dim;
  CHECK_EQ(output.getHeight(), numSamples);
  CHECK_EQ(output.getWidth(), dim);
  real* grad = getData();
  MatrixPtr tmpMat = Matrix::create(numSamples, dim);
  real* tmp = tmpMat->getData();

  vExp(size, output.getData(), tmpMat->getData());

  for (size_t i = 0; i < size; ++i) {
    grad[i] *= (1.0 - 1.0 / tmp[i]);
  }
}

void CpuMatrix::scaledTanh(Matrix& output, real p1, real p2) {
  CHECK(isContiguous());
  CHECK(output.isContiguous());
  size_t numSamples = getHeight();
  size_t dim = getWidth();
  CHECK_EQ(output.getHeight(), numSamples);
  CHECK_EQ(output.getWidth(), dim);

  const real* in = getData();
  real* out = output.getData();

  // out = p2*in
  for (size_t i = 0; i < numSamples * dim; ++i) {
    out[i] = p2 * in[i];
  }

  vTanh(numSamples * dim, out, out);

  // out = p1 * out
  for (size_t i = 0; i < numSamples * dim; ++i) {
    out[i] = p1 * out[i];
  }
}

/* uniform randomization, minimize precision = 1e-5 */
void CpuMatrix::randomizeUniform() {
  CHECK(isContiguous());
  real* data = getData();
  unsigned int* randSeed = ThreadLocalRand::getSeed();
  real recipRandMax = 1.0f / (real)RAND_MAX;
  for (size_t i = 0; i < elementCnt_; ++i) {
    *data++ = rand_r(randSeed) * recipRandMax;
  }
}

void CpuMatrix::print(std::ostream& os) const {
  CHECK(isContiguous());
  for (size_t i = 0; i < height_; ++i) {
    for (size_t j = 0; j < width_; ++j) {
      os << data_[i * width_ + j] << " ";
    }
    os << std::endl;
  }
}

void CpuMatrix::paramReluForward(Matrix& data, Matrix& W) {
  real* input = data.getData();
  real* w = W.getData();
X
xzl 已提交
4287
  real* output = data_;
Z
zhangjinchao01 已提交
4288 4289
  size_t numElements = data.getWidth();
  size_t numSamples = data.getHeight();
H
hedaoyuan 已提交
4290 4291
  size_t paraSize = W.getHeight() * W.getWidth();
  CHECK(!(numElements % paraSize));  // this check from ParameterReluLayer::init
X
xzl 已提交
4292

H
hedaoyuan 已提交
4293
  size_t partial_sum = numElements / paraSize;
X
xzl 已提交
4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310
  if (paraSize == numElements) {
    for (size_t n = 0; n < numSamples * numElements; ++n) {
      output[n] = input[n] > 0 ? input[n] : input[n] * w[n % numElements];
    }
    return;
  }

#if defined(__ARM_NEON__) || defined(__ARM_NEON)
  for (size_t n = 0; n < numSamples; ++n) {
    for (size_t i = 0; i < paraSize; i++) {
      neon::prelu(
          input + i * partial_sum, w[i], output + i * partial_sum, partial_sum);
    }
    input = input + numElements;
    output = output + numElements;
  }
#else
Z
zhangjinchao01 已提交
4311 4312
  for (size_t n = 0, k = 0; n < numSamples; ++n) {
    for (size_t i = 0; i < numElements; ++i, ++k) {
X
xzl 已提交
4313
      output[k] = input[k] > 0 ? input[k] : input[k] * w[i / partial_sum];
Z
zhangjinchao01 已提交
4314 4315
    }
  }
X
xzl 已提交
4316
#endif
Z
zhangjinchao01 已提交
4317 4318 4319 4320 4321 4322 4323 4324
}

void CpuMatrix::paramReluBackwardW(Matrix& oGrad, Matrix& data) {
  real* ograd = oGrad.getData();
  real* input = data.getData();
  real* wgrad = data_;
  size_t numElements = data.getWidth();
  size_t numSamples = data.getHeight();
H
hedaoyuan 已提交
4325 4326 4327
  size_t paraSize = this->getHeight() * this->getWidth();
  CHECK(!(numElements % paraSize));  // this check from ParameterReluLayer::init
  size_t partial_sum = numElements / paraSize;
Z
zhangjinchao01 已提交
4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341
  for (size_t n = 0, k = 0; n < numSamples; ++n) {
    for (size_t i = 0; i < numElements; ++i, ++k) {
      wgrad[i / partial_sum] += ograd[k] * (input[k] > 0 ? 0 : input[k]);
    }
  }
}

void CpuMatrix::paramReluBackwardDiff(Matrix& oGrad, Matrix& data, Matrix& W) {
  real* diff = data_;
  real* input = data.getData();
  real* ograd = oGrad.getData();
  real* w = W.getData();
  size_t numElements = data.getWidth();
  size_t numSamples = data.getHeight();
H
hedaoyuan 已提交
4342 4343 4344
  size_t paraSize = W.getHeight() * W.getWidth();
  CHECK(!(numElements % paraSize));  // this check from ParameterReluLayer::init
  size_t partial_sum = numElements / paraSize;
Z
zhangjinchao01 已提交
4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453
  for (size_t n = 0, k = 0; n < numSamples; ++n) {
    for (size_t i = 0; i < numElements; ++i, ++k) {
      diff[k] += ograd[k] * (input[k] > 0 ? 1 : w[i / partial_sum]);
    }
  }
}

void CpuMatrix::print(std::ostream& os, size_t height, size_t width) const {
  CHECK(isContiguous());
  size_t h = height_ < height ? height_ : height;
  size_t w = width_ < width ? width_ : width;
  os.setf(std::ostream::scientific);
  os << "[";
  for (size_t i = 0; i < h; ++i) {
    for (size_t j = 0; j < w; ++j) {
      os << data_[i * width_ + j] << " ";
    }
    if (i == h - 1) {
      os << "]";
    }
    os << std::endl;
  }
}

void CpuMatrix::printOneRow(std::ostream& os, size_t idx) const {
  CHECK_LT(idx, height_);
  size_t offset = idx * stride_;
  os << data_[offset];
  for (size_t i = 1; i < width_; ++i) {
    os << " " << data_[offset + i];
  }
  os << ";";
}

void CpuMatrix::check(std::ostream& os, Matrix& refMat, bool printDiff) {
  CHECK(isContiguous());
  CHECK(height_ == refMat.getHeight());
  CHECK(width_ == refMat.getWidth());
  CpuMatrix cpuRef(height_, width_);
  cpuRef.copyFrom(refMat);
  size_t diffCnt = 0;
  for (size_t i = 0; i < height_; ++i) {
    for (size_t j = 0; j < width_; ++j) {
      real a = getElement(i, j);
      real b = cpuRef.getElement(i, j);
      if (fabs(a - b) > 0.00001) {
        ++diffCnt;
        if (printDiff) {
          os << "ref= " << a << "  check= " << b << std::endl;
        }
      }
    }
  }
  LOG(INFO) << "the  diffCnt is " << diffCnt;
}

real CpuMatrix::getMin() {
  size_t size = getHeight() * getWidth();
  real* data = getData();
  real res = data[0];
  for (size_t i = 1; i < size; ++i) {
    if (res > data[i]) {
      res = data[i];
    }
  }
  return res;
}

real CpuMatrix::getMax() {
  size_t size = getHeight() * getWidth();
  real* data = getData();
  real res = data[0];
  for (size_t i = 1; i < size; ++i) {
    if (res < data[i]) {
      res = data[i];
    }
  }
  return res;
}

void CpuMatrix::circularConv(Matrix& in0, Matrix& in1) {
  size_t height = this->getHeight();
  size_t width0 = this->getWidth();
  size_t width1 = in1.getWidth();

  CHECK_EQ(height, in0.getHeight());
  CHECK_EQ(width0, in0.getWidth());
  CHECK_EQ(height, in1.getHeight());

  CHECK_EQ(width1 % 2, 1U);

  real* outV = this->getData();
  real* inV0 = in0.getData();
  real* inV1 = in1.getData();

  int leftCtxLen = (width1 - 1) / 2;
  for (size_t x = 0; x < height;
       ++x, outV += width0, inV0 += width0, inV1 += width1) {
    for (size_t i = 0; i < width0; ++i) {  // each dimension of output
      for (size_t j = 0; j < width1; ++j) {
        // iterate over all dimentions of inV1
        int index = i + j - leftCtxLen;
        index = (index + width0) % width0;
        outV[i] += inV0[index] * inV1[j];
      }
    }
  }
}

4454 4455
void CpuMatrix::circularConvDerivative(
    Matrix& outG, Matrix& in0, Matrix& in1, Matrix& inG0, Matrix& inG1) {
Z
zhangjinchao01 已提交
4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474
  size_t height = in0.getHeight();
  size_t width0 = in0.getWidth();
  size_t width1 = in1.getWidth();

  CHECK_EQ(height, in1.getHeight());
  CHECK_EQ(height, inG0.getHeight());
  CHECK_EQ(width0, inG0.getWidth());
  CHECK_EQ(height, inG1.getHeight());
  CHECK_EQ(width1, inG1.getWidth());
  CHECK_EQ(height, outG.getHeight());
  CHECK_EQ(width0, outG.getWidth());

  real* outGV = outG.getData();
  real* inV0 = in0.getData();
  real* inV1 = in1.getData();
  real* inGV0 = inG0.getData();
  real* inGV1 = inG1.getData();

  int leftCtxLen = (width1 - 1) / 2;
4475 4476 4477 4478 4479 4480
  for (size_t x = 0; x < height; ++x,
              outGV += width0,
              inV0 += width0,
              inV1 += width1,
              inGV0 += width0,
              inGV1 += width1) {
Z
zhangjinchao01 已提交
4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548
    for (size_t j = 0; j < width1; ++j) {  // iterate over width1
      for (size_t i = 0; i < width0; ++i) {
        // such over all dimensions of outG
        int index = i + j - leftCtxLen;
        index = (index + width0) % width0;
        inGV0[index] += outGV[i] * inV1[j];
        inGV1[j] += outGV[i] * inV0[index];
      }
    }
  }
}

void CpuMatrix::multiBinaryLabelCrossEntropy(Matrix& output, Matrix& label) {
  CHECK(dynamic_cast<CpuMatrix*>(&output));
  auto labelPtr = dynamic_cast<CpuSparseMatrix*>(&label);
  CHECK(labelPtr);

  size_t numSamples = getHeight();
  size_t dim = output.getWidth();
  CHECK_EQ(numSamples, output.getHeight());
  CHECK_EQ(numSamples, labelPtr->getHeight());
  CHECK_EQ(dim, labelPtr->getWidth());

  real* out = output.getData();
  real* cost = getData();
  for (size_t i = 0; i < numSamples; ++i, out += dim) {
    for (size_t j = 0; j < dim; ++j) {
      CHECK(out[j] > 0 && out[j] < 1.0);
      cost[i] -= std::log(1 - out[j]);
    }

    const int* cols = labelPtr->getRowCols(i);
    for (size_t j = 0; j < labelPtr->getColNum(i); ++j) {
      CHECK_LT(size_t(cols[j]), dim);
      cost[i] -= std::log(out[cols[j]] / (1 - out[cols[j]]));
    }
  }
}

void CpuMatrix::multiBinaryLabelCrossEntropyBp(Matrix& output, Matrix& label) {
  CHECK(dynamic_cast<CpuMatrix*>(&output));
  auto labelPtr = dynamic_cast<CpuSparseMatrix*>(&label);
  CHECK(labelPtr);

  size_t numSamples = getHeight();
  size_t dim = getWidth();
  CHECK_EQ(numSamples, output.getHeight());
  CHECK_EQ(numSamples, labelPtr->getHeight());
  CHECK_EQ(dim, output.getWidth());
  CHECK_EQ(dim, labelPtr->getWidth());

  real* out = output.getData();
  real* grad = getData();
  for (size_t i = 0; i < numSamples; ++i, out += dim, grad += dim) {
    for (size_t j = 0; j < dim; ++j) {
      CHECK(out[j] > 0 && out[j] < 1.0);
      grad[j] += 1.0 / (1 - out[j]);
    }

    const int* cols = labelPtr->getRowCols(i);
    for (size_t j = 0; j < labelPtr->getColNum(i); ++j) {
      CHECK_LT(size_t(cols[j]), dim);
      grad[cols[j]] -= 1.0 / (out[cols[j]] * (1 - out[cols[j]]));
    }
  }
}

/* calculate the classification error for multi binary label */
4549 4550
void CpuMatrix::classificationErrorMulti(Matrix& output,
                                         Matrix& label,
Z
zhangjinchao01 已提交
4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584
                                         real threshold) {
  CHECK(dynamic_cast<CpuMatrix*>(&output));
  auto labelPtr = dynamic_cast<CpuSparseMatrix*>(&label);
  CHECK(labelPtr);

  size_t numSamples = getHeight();
  size_t dim = output.getWidth();
  CHECK_EQ(numSamples, output.getHeight());
  CHECK_EQ(numSamples, labelPtr->getHeight());
  CHECK_EQ(dim, labelPtr->getWidth());

  real* out = output.getData();
  real* result = getData();
  for (size_t i = 0; i < numSamples; ++i, out += dim) {
    real sum = 0.0;
    for (size_t j = 0; j < dim; ++j) {
      if (out[j] >= threshold) {
        sum += 1.0;
      }
    }

    const int* cols = labelPtr->getRowCols(i);
    for (size_t j = 0; j < labelPtr->getColNum(i); ++j) {
      CHECK_LT(size_t(cols[j]), dim);
      if (out[cols[j]] < threshold) {
        sum += 1.0;
      } else {
        sum -= 1.0;
      }
    }
    result[i] = sum / dim;
  }
}

L
liaogang 已提交
4585 4586 4587 4588 4589
void CpuMatrix::bilinearForward(const Matrix& in,
                                const size_t inImgH,
                                const size_t inImgW,
                                const size_t outImgH,
                                const size_t outImgW,
L
liaogang 已提交
4590 4591 4592
                                const size_t numChannels,
                                const real ratioH,
                                const real ratioW) {
L
liaogang 已提交
4593 4594 4595
  CHECK(dynamic_cast<const CpuMatrix*>(&in));

  size_t outputW = getWidth();
L
liaogang 已提交
4596
  size_t batchSize = getHeight();
L
liaogang 已提交
4597 4598
  size_t inputW = in.getWidth();
  size_t inputH = in.getHeight();
L
liaogang 已提交
4599 4600
  size_t inPosOffset = inImgH * inImgW;
  size_t outPosOffset = outImgH * outImgW;
L
liaogang 已提交
4601
  (void)(inputH);
L
liaogang 已提交
4602 4603

  real* outData = getData();
4604
  const real* inData = in.getData();
L
liaogang 已提交
4605 4606 4607 4608

  if (inImgH == outImgH && inImgW == outImgW) {
    this->copyFrom(in);
  } else {
4609
    for (size_t k = 0; k < batchSize; ++k) {  // loop for batches
L
liaogang 已提交
4610 4611 4612
      for (size_t i = 0; i < outImgH; ++i) {  // loop for images
        size_t h = ratioH * i;
        size_t hid = (h < inImgH - 1) ? 1 : 0;
L
liaogang 已提交
4613 4614
        real h1lambda = ratioH * i - h;
        real h2lambda = 1 - h1lambda;
L
liaogang 已提交
4615

L
liaogang 已提交
4616 4617 4618
        for (size_t j = 0; j < outImgW; ++j) {
          size_t w = ratioW * j;
          size_t wid = (w < inImgW - 1) ? 1 : 0;
L
liaogang 已提交
4619 4620
          real w1lambda = ratioW * j - w;
          real w2lambda = 1 - w1lambda;
L
liaogang 已提交
4621 4622 4623
          // calculate four position for bilinear interpolation
          const real* inPos = &inData[k * inputW + h * inImgW + w];
          real* outPos = &outData[k * outputW + i * outImgW + j];
L
liaogang 已提交
4624
          for (size_t c = 0; c < numChannels; ++c) {  // loop for channels
L
liaogang 已提交
4625
            // bilinear interpolation
L
liaogang 已提交
4626
            outPos[0] =
4627 4628 4629
                h2lambda * (w2lambda * inPos[0] + w1lambda * inPos[wid]) +
                h1lambda * (w2lambda * inPos[hid * inImgW] +
                            w1lambda * inPos[hid * inImgW + wid]);
L
liaogang 已提交
4630 4631
            inPos += inPosOffset;
            outPos += outPosOffset;
L
liaogang 已提交
4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643
          }
        }
      }
    }
  }
}

void CpuMatrix::bilinearBackward(const Matrix& out,
                                 const size_t outImgH,
                                 const size_t outImgW,
                                 const size_t inImgH,
                                 const size_t inImgW,
L
liaogang 已提交
4644 4645 4646
                                 const size_t numChannels,
                                 const real ratioH,
                                 const real ratioW) {
L
liaogang 已提交
4647 4648 4649 4650 4651
  CHECK(dynamic_cast<const CpuMatrix*>(&out));

  size_t inputW = getWidth();
  size_t inputH = getHeight();
  size_t outputW = out.getWidth();
L
liaogang 已提交
4652
  size_t batchSize = out.getHeight();
L
liaogang 已提交
4653 4654
  size_t inPosOffset = inImgH * inImgW;
  size_t outPosOffset = outImgH * outImgW;
L
liaogang 已提交
4655
  (void)(inputH);
L
liaogang 已提交
4656 4657 4658 4659 4660

  real* inGrad = getData();
  const real* outGrad = out.getData();

  if (inImgH == outImgH && inImgW == outImgW) {
L
liaogang 已提交
4661
    this->add(const_cast<Matrix&>(out));
L
liaogang 已提交
4662
  } else {
4663
    for (size_t k = 0; k < batchSize; ++k) {  // loop for batches
L
liaogang 已提交
4664 4665 4666
      for (size_t i = 0; i < outImgH; ++i) {  // loop for images
        size_t h = ratioH * i;
        size_t hid = (h < inImgH - 1) ? 1 : 0;
L
liaogang 已提交
4667 4668
        real h1lambda = ratioH * i - h;
        real h2lambda = 1 - h1lambda;
L
liaogang 已提交
4669 4670 4671
        for (size_t j = 0; j < outImgW; ++j) {
          size_t w = ratioW * j;
          size_t wid = (w < inImgW - 1) ? 1 : 0;
L
liaogang 已提交
4672 4673
          real w1lambda = ratioW * j - w;
          real w2lambda = 1 - w1lambda;
L
liaogang 已提交
4674 4675 4676

          real* inPos = &inGrad[k * inputW + h * inImgW + w];
          const real* outPos = &outGrad[k * outputW + i * outImgW + j];
L
liaogang 已提交
4677
          for (size_t c = 0; c < numChannels; ++c) {  // loop for channels
L
liaogang 已提交
4678 4679 4680 4681
            inPos[0] += h2lambda * w2lambda * outPos[0];
            inPos[wid] += h2lambda * w1lambda * outPos[0];
            inPos[hid * inImgW] += h1lambda * w2lambda * outPos[0];
            inPos[hid * inImgW + wid] += h1lambda * w1lambda * outPos[0];
L
liaogang 已提交
4682 4683
            inPos += inPosOffset;
            outPos += outPosOffset;
L
liaogang 已提交
4684 4685 4686 4687 4688 4689 4690
          }
        }
      }
    }
  }
}

C
chengduoZH 已提交
4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751
void CpuMatrix::vol2Col(real* data,
                        int channels,
                        int depth,
                        int height,
                        int width,
                        int filterD,
                        int filterH,
                        int filterW,
                        int strideD,
                        int strideH,
                        int strideW,
                        int paddingD,
                        int paddingH,
                        int paddingW) {
  real* outData = getData();
  int outHeight = (height + 2 * paddingH - filterH) / strideH + 1;
  int outWidth = (width + 2 * paddingW - filterW) / strideW + 1;
  int outDepth = (depth + 2 * paddingD - filterD) / strideD + 1;

  int channelsCol = channels * filterD * filterH * filterW;
  for (int c = 0; c < channelsCol; ++c) {
    int wOffset = c % filterW;
    int hOffset = (c / filterW) % filterH;
    int dOffset = (c / filterW / filterH) % filterD;
    int cIn = c / filterW / filterH / filterD;
    for (int d = 0; d < outDepth; ++d) {
      for (int h = 0; h < outHeight; ++h) {
        for (int w = 0; w < outWidth; ++w) {
          int dPad = d * strideD - paddingD + dOffset;
          int hPad = h * strideH - paddingH + hOffset;
          int wPad = w * strideW - paddingW + wOffset;

          if (hPad >= 0 && hPad < height && wPad >= 0 && wPad < width &&
              dPad >= 0 && dPad < depth)
            outData[((c * outDepth + d) * outHeight + h) * outWidth + w] =
                data[((cIn * depth + dPad) * height + hPad) * width + wPad];
          else
            outData[((c * outDepth + d) * outHeight + h) * outWidth + w] = 0;
        }
      }
    }
  }
}

void CpuMatrix::col2Vol(real* trg,
                        int channels,
                        int depth,
                        int height,
                        int width,
                        int filterD,
                        int filterH,
                        int filterW,
                        int strideD,
                        int strideH,
                        int strideW,
                        int paddingD,
                        int paddingH,
                        int paddingW,
                        real alpha,
                        real beta) {
  real* src = getData();
C
chengduoZH 已提交
4752
  int outDepth = (depth + 2 * paddingD - filterD) / strideD + 1;
C
chengduoZH 已提交
4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779
  int outHeight = (height + 2 * paddingH - filterH) / strideH + 1;
  int outWidth = (width + 2 * paddingW - filterW) / strideW + 1;
  int channelsCol = channels * filterD * filterH * filterW;
  for (int c = 0; c < channelsCol; ++c) {
    int wOffset = c % filterW;
    int hOffset = (c / filterW) % filterH;
    int dOffset = (c / filterW / filterH) % filterD;
    int cIm = c / filterW / filterH / filterD;
    for (int d = 0; d < outDepth; ++d) {
      for (int h = 0; h < outHeight; ++h) {
        for (int w = 0; w < outWidth; ++w) {
          int dPad = d * strideD - paddingD + dOffset;
          int hPad = h * strideH - paddingH + hOffset;
          int wPad = w * strideW - paddingW + wOffset;
          if (hPad >= 0 && hPad < height && wPad >= 0 && wPad < width &&
              dPad >= 0 && dPad < depth)
            trg[((cIm * depth + dPad) * height + hPad) * width + wPad] =
                alpha *
                    src[((c * outDepth + d) * outHeight + h) * outWidth + w] +
                beta *
                    trg[((cIm * depth + dPad) * height + hPad) * width + wPad];
        }
      }
    }
  }
}

Z
zhangjinchao01 已提交
4780 4781 4782 4783 4784 4785 4786 4787
////////////////////////////////////////////////////////////////
//               functions executed via cpu                   //
////////////////////////////////////////////////////////////////

void GpuMatrix::selectElements(Matrix& table, IVector& ids) {
  execViaCpu2(&CpuMatrix::selectElements, *this, table, ids);
}
}  // namespace paddle