Matrix.h 67.4 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 16

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. */

#pragma once

Y
Yu Yang 已提交
17
#include <stdint.h>
Z
zhangjinchao01 已提交
18 19 20
#include <memory>
#include <thread>

X
Xin Pan 已提交
21 22
#include "paddle/legacy/utils/Logging.h"
#include "paddle/legacy/utils/ThreadLocal.h"
Z
zhangjinchao01 已提交
23 24 25

#include <hl_gpu.h>

Y
Yu Yang 已提交
26
#include "BaseMatrix.h"
Z
zhangjinchao01 已提交
27 28
#include "MemoryHandle.h"
#include "Vector.h"
X
Xin Pan 已提交
29 30
#include "paddle/legacy/utils/Common.h"
#include "paddle/legacy/utils/ThreadLocal.h"
Z
zhangjinchao01 已提交
31 32 33

namespace paddle {

X
Xin Pan 已提交
34
/// TODO(tianbing), move to paddle/legacy/function/TensorType.h
Z
zhangjinchao01 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
enum SparseValueType { NO_VALUE = 0, FLOAT_VALUE = 1 };

/**
 * @brief  matrix sparse_format .
 *
 * nnz represents nonzero number in sparse matrix.
 *
 * SPARSE_CSR: row major matrix. length of row is height_ + 1, each element
 * represents row start index in Matrix. length of col and value are nnz.
 *
 * SPARSE_CSC: col major matrix. length of col is width_ + 1, each element
 * represents col start index in Matrix. length of col and value are nnz.
 *
 * @code
 * for example: [0, 1, 0, 2, 0;
 *               1, 0, 0, 0, 0;
 *               0, 0, 0, 2, 5];
 * SPARSE_CSR row   [0, 2, 3, 5];
 *            col   [1, 3, 0, 3, 4];
 *            value [1, 2, 1, 2, 5]
 * SPARSE_CSC col   [0, 1, 2, 2, 4, 5];
 *            row   [1, 0, 0, 2, 2];
 *            value [1, 1, 2, 2, 5]
 * @endcode
 */
X
Xin Pan 已提交
60
/// TODO(tianbing), move to paddle/legacy/function/TensorType.h
Z
zhangjinchao01 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
enum SparseFormat { SPARSE_CSR = 0, SPARSE_CSC = 1 };

class Matrix;
class GpuMatrix;
class CpuMatrix;
class CpuSparseMatrix;
class GpuSparseMatrix;
typedef std::shared_ptr<Matrix> MatrixPtr;
typedef std::shared_ptr<GpuMatrix> GpuMatrixPtr;
typedef std::shared_ptr<CpuMatrix> CpuMatrixPtr;
typedef std::shared_ptr<GpuSparseMatrix> GpuSparseMatrixPtr;
typedef std::shared_ptr<CpuSparseMatrix> CpuSparseMatrixPtr;

/**
 * Copy or assignemnt constructor will share the data as opposed to making a
 * copy of the original data. To make a copy of the orinal data, use copyFrom()
 * instead.
 */
class Matrix : public BaseMatrix {
W
Wu Yi 已提交
80
 protected:
81 82 83 84
  Matrix(MemoryHandlePtr memHandle,
         size_t height,
         size_t width,
         bool trans,
Z
zhangjinchao01 已提交
85 86 87 88
         bool use_gpu);

  Matrix(real* data, size_t height, size_t width, bool trans, bool use_gpu);

89 90 91 92 93
  Matrix(real* data,
         size_t height,
         size_t width,
         size_t stride,
         bool trans,
Z
zhangjinchao01 已提交
94 95 96 97
         bool use_gpu);

  static ThreadLocal<MatrixPtr> tmpMat_;

W
Wu Yi 已提交
98
 public:
Z
zhangjinchao01 已提交
99 100 101
  size_t elementCnt_;  // maximal number of elements which can be held in data_
  MemoryHandlePtr memoryHandle_;

W
Wu Yi 已提交
102
 public:
Z
zhangjinchao01 已提交
103 104
  virtual ~Matrix() {}

105 106 107 108 109 110 111 112 113 114 115 116
  static MatrixPtr create(MemoryHandlePtr memHandle,
                          size_t height,
                          size_t width,
                          bool trans = false);
  static MatrixPtr create(size_t height,
                          size_t width,
                          bool trans = false,
                          bool useGpu = false);
  static MatrixPtr create(real* data,
                          size_t height,
                          size_t width,
                          bool trans = false,
Z
zhangjinchao01 已提交
117
                          bool useGpu = false);
118 119 120 121 122
  static MatrixPtr create(real* data,
                          size_t height,
                          size_t width,
                          size_t stride,
                          bool trans = false,
Z
zhangjinchao01 已提交
123 124
                          bool useGpu = false);

125 126 127
  static MatrixPtr createSparseMatrix(size_t height,
                                      size_t width,
                                      size_t nnz,
Z
zhangjinchao01 已提交
128
                                      SparseValueType valueType = FLOAT_VALUE,
129 130 131 132 133
                                      bool trans = false,
                                      bool useGpu = false);
  static MatrixPtr createSparseMatrix(size_t height,
                                      size_t width,
                                      size_t nnz,
Z
zhangjinchao01 已提交
134 135
                                      SparseValueType valueType = FLOAT_VALUE,
                                      SparseFormat foramt = SPARSE_CSR,
136 137 138 139 140 141 142 143
                                      bool trans = false,
                                      bool useGpu = false);

  static MatrixPtr createSparseMatrix(real* data,
                                      int* row,
                                      int* col,
                                      size_t height,
                                      size_t width,
Z
zhangjinchao01 已提交
144 145
                                      size_t nnz, /* used to allocate space */
                                      SparseValueType valueType, /*value type*/
146 147
                                      SparseFormat format,
                                      bool trans,
Z
zhangjinchao01 已提交
148 149 150
                                      bool useGpu);

  static void resizeOrCreateSparseMatrix(
151 152 153 154 155 156 157 158 159 160 161 162 163 164
      MatrixPtr& matrix,
      size_t height,
      size_t width,
      size_t nnz,
      SparseValueType valueType = FLOAT_VALUE,
      SparseFormat foramt = SPARSE_CSR,
      bool trans = false,
      bool useGpu = false);

  static void resizeOrCreate(MatrixPtr& a,
                             size_t height,
                             size_t width,
                             bool trans = false,
                             bool useGpu = false);
Z
zhangjinchao01 已提交
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201

  /**
   * @brief  set the data buffer used to hold the matrix data.
   *
   * caller should make sure that the size of data is at least
   * sizeof(real)*height*width.
   */
  void setData(real* data) {
    BaseMatrix::setData(data);
    memoryHandle_.reset();
  }

  /// the data should be contiguous
  void setData(real* data, size_t newHeight, size_t newWidth) {
    setData(data);
    height_ = newHeight;
    width_ = newWidth;
    elementCnt_ = newHeight * newWidth;
    stride_ = width_;
  }

  size_t getWidth() const { return width_; }
  size_t getHeight() const { return height_; }
  size_t getStride() const { return stride_; }
  size_t getElementCnt() const { return elementCnt_; }
  virtual real* getData() { return data_; }
  virtual const real* getData() const { return data_; }
  bool isTransposed() const { return trans_; }
  bool isContiguous() const { return stride_ == width_ || height_ == 1; }

  // If sparse matrix, need to dynamic_cast to CpuSparseMatrix/GpuSparseMatrix
  // befor call the following functions.
  // Declare these functions in the base class just easy to call them.
  // And these declarations should be moved to base class of sparse matrix
  // if refactor sparse matrix
  virtual int* getRows() const {
    LOG(FATAL) << "Not implemented";
202
    return nullptr;  //! suppress warning for no return value.
Z
zhangjinchao01 已提交
203 204 205 206
  }

  virtual int* getCols() const {
    LOG(FATAL) << "Not implemented";
207
    return nullptr;  //! suppress warning for no return value.
Z
zhangjinchao01 已提交
208 209 210 211 212 213 214 215 216
  }

  virtual SparseFormat getFormat() const {
    LOG(FATAL) << "Not implemented";
    return SPARSE_CSR;  //! suppress warning for no return value.
  }

  virtual SparseValueType getValueType() const {
    LOG(FATAL) << "Not implemented";
217
    return NO_VALUE;  //! suppress warning for no return value.
Z
zhangjinchao01 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
  }

  /**
   * @brief matrix elment-wise add
   *
   * Named add3 just because add/add2 has been used in BaseMatrix.cu
   * and they are not virtual function.
   */
  virtual void add3(MatrixPtr b) { LOG(FATAL) << "Not implemented"; }

  MemoryHandlePtr getMemoryHandle() const { return memoryHandle_; }

  virtual void zeroMem() { LOG(FATAL) << "Not implemented"; }

  virtual void resetOne() { LOG(FATAL) << "Not implemented"; }

234
  void setDiag(real value);
235

Z
zhangjinchao01 已提交
236 237 238 239 240 241
  virtual void copyFrom(const Matrix& src) { LOG(FATAL) << "Not implemented"; }

  virtual void trimFrom(const CpuSparseMatrix& src) {
    LOG(FATAL) << "Not implemented";
  }

242 243
  // For GpuMatrix this is an asynchronous copy interface
  // For CpuMatrix this is an synchronous copy interface
Z
zhangjinchao01 已提交
244 245 246 247
  virtual void copyFrom(const Matrix& src, hl_stream_t stream) {
    LOG(FATAL) << "Not implemented";
  }

248 249 250
  MatrixPtr subMatrix(size_t startRow,
                      size_t endRow,
                      size_t startCol,
Z
zhangjinchao01 已提交
251 252 253 254 255 256 257 258 259 260 261 262
                      size_t endCol);

  MatrixPtr subRowMatrix(size_t startRow, size_t endRow) {
    return subMatrix(startRow, endRow, 0, getWidth());
  }

  MatrixPtr subColMatrix(size_t startCol, size_t endCol) {
    return subMatrix(0, getHeight(), startCol, endCol);
  }

  virtual MatrixPtr subMatrix(size_t startRow, size_t numRows) {
    CHECK_LE(startRow + numRows, getHeight());
263 264 265 266 267
    return Matrix::create(getData() + startRow * getWidth(),
                          numRows,
                          getWidth(),
                          trans_,
                          useGpu_);
Z
zhangjinchao01 已提交
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
  }
  virtual MatrixPtr subMatrix(size_t startRow, size_t numRows, MatrixPtr dest) {
    CHECK_LE(startRow + numRows, getHeight());
    CHECK_EQ(useGpu_, dest->useGpu_);
    dest->setData(this->rowBuf(startRow), numRows, getWidth());
    return dest;
  }

  /**
   * If this is GpuMatrix, src is assumed to be CPU memory
   *
   * If this is CpuMatrix, src is assumed to be CPU memory
   */
  virtual void copyFrom(const real* src, size_t size) {
    LOG(FATAL) << "Not implemented";
  }

  virtual void copyFrom(const real* src, const int64_t* seq) {
    LOG(FATAL) << "Not implemented";
  }

  /**
   * @brief convert a int vector to a real matrix.
   *
   * (1) source and dest are both in CPU.
   *
   * (2) sizes are exactly match.
   */
  virtual void copyFrom(const IVector& src) {
    LOG(FATAL) << "copy data from int vector only available on CpuMatrix.";
  }

300
  virtual void copyByRowIndex(Matrix& b, const IVector& rowIndex) {
Z
zhangjinchao01 已提交
301 302 303 304 305 306 307 308 309 310 311
    LOG(FATAL) << "Not implemented";
  }

  /**
   * @brief Create a matrix with the same type (GpuMatrix, CpuMatrix,
   *        NonValueSparseMatrix, etc.) as this.
   *
   * If height and width is zero, the new matrix will have the same size
   * as this, otherwise the new matrix will have the specified size.
   *
   */
312 313
  virtual MatrixPtr clone(size_t height = 0,
                          size_t width = 0,
Z
zhangjinchao01 已提交
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
                          bool useGpu = false) {
    LOG(FATAL) << "Not implemented";
    return nullptr;
  }

  virtual real* getRowBuf(size_t row) {
    LOG(FATAL) << "Not implemented";
    return nullptr;
  }

  virtual real getElement(size_t x, size_t y) const {
    LOG(FATAL) << "Not implemented";
    return 0;
  }

  virtual real getSum() {
    LOG(FATAL) << "Not implemented";
    return 0;
  }

  virtual void accumulateColSum(Matrix& src) {
    LOG(FATAL) << "Not implemented";
  }

  virtual real getAbsSum() {
    LOG(FATAL) << "Not implemented";
    return 0;
  }

  /**
   * @note Original data may not be preserved after resize().
   */
  virtual void resize(size_t newHeight, size_t newWidth) = 0;

  /**
   * @note This should only be used for sparse matrix.
   */
351 352
  virtual void resize(size_t newHeight,
                      size_t newWidth,
Z
zhangjinchao01 已提交
353
                      size_t newNnz, /* total item used to allocate space */
354 355
                      SparseValueType valueType,
                      SparseFormat format) = 0;
Z
zhangjinchao01 已提交
356 357 358 359 360 361 362

  /**
   * @brief This should only be used for sparse matrix.
   *
   * Currently must be called for each row in order.
   * The matrix is not valid until setRow is called for the last row.
   */
363 364 365
  virtual void setRow(size_t row,
                      size_t colNum,
                      const unsigned int* cols,
Z
zhangjinchao01 已提交
366 367 368 369 370 371 372 373 374 375
                      const real* values) = 0;

  virtual MatrixPtr getTranspose() = 0;

  /**
   * @brief  hard transpose.
   *
   * allocate matTrans' memory outside, then set memAlloc as false;
   * else set as true.
   */
376 377 378 379 380
  virtual void transpose(MatrixPtr& matTrans, bool memAlloc) {
    LOG(FATAL) << "Not implemented";
  }

  /**
H
Haonan 已提交
381 382 383 384 385 386 387 388 389 390 391
   * @brief  rotate 90 degrees in clock-wise if clockWise=true;
   *         otherwise rotate in anti clock-wise
   * clock-wise:
   * \f[
   *   y(j,i) = x(M-i-1,j)
   * \f]
   * anti clock-wise:
   * \f[
   *   y(j,i) = x(i, N-1-j)
   * \f]
   * where \f$x\f$ is (M x N) input, and \f$y\f$ is (N x M) output.
392
   *
H
Haonan 已提交
393
   * allocate matRot' memory outside, then set memAlloc as false;
394 395 396
   * else set as true.
   */
  virtual void rotate(MatrixPtr& matRot, bool memAlloc, bool clockWise) {
Z
zhangjinchao01 已提交
397 398 399
    LOG(FATAL) << "Not implemented";
  }

L
lzhao4ever 已提交
400 401
  virtual MatrixPtr getInverse() {
    LOG(FATAL) << "Not implemented";
402
    return nullptr;
L
lzhao4ever 已提交
403 404 405 406 407 408 409 410
  }

  /**
   * @brief  inverse.
   *
   * if allocate matInv's memory outside, then set memAlloc as false;
   * else set as true.
   */
411
  virtual void inverse(MatrixPtr& matInv, bool memAlloc) {
L
lzhao4ever 已提交
412 413 414
    LOG(FATAL) << "Not implemented";
  }

W
Wu Yi 已提交
415
 public:
Z
zhangjinchao01 已提交
416 417 418 419 420 421 422 423 424 425 426 427 428 429
  /// Only set all variables to 0 or NULL but not free them.
  virtual void clear() {
    height_ = 0;
    width_ = 0;
    data_ = NULL;
  }

  void reshape(size_t height, size_t width);

  /// add b to each sample of this.
  virtual void addBias(Matrix& b, real scale) {
    LOG(FATAL) << "Not implemented";
  }

430 431 432 433
  virtual void addSharedBias(Matrix& b, real scale) {
    LOG(FATAL) << "Not implemented";
  }

H
hedaoyuan 已提交
434
  void addBias(Matrix& b, real scale, bool sharedBias) {
435 436 437 438 439 440 441
    if (!sharedBias) {
      addBias(b, scale);
    } else {
      addSharedBias(b, scale);
    }
  }

Z
zhangjinchao01 已提交
442 443 444 445 446
  /// add each sample from a to this.
  virtual void collectBias(Matrix& a, real scale) {
    LOG(FATAL) << "Not implemented";
  }

447 448 449 450
  virtual void collectSharedBias(Matrix& a, real scale) {
    LOG(FATAL) << "Not implemented";
  }

H
hedaoyuan 已提交
451
  void collectBias(Matrix& a, real scale, bool sharedBias) {
452 453 454 455 456 457 458
    if (!sharedBias) {
      collectBias(a, scale);
    } else {
      collectSharedBias(a, scale);
    }
  }

459 460 461
  virtual void sequenceAvgForward(Matrix& a,
                                  const IVector& startsPos,
                                  int mode) {
Z
zhangjinchao01 已提交
462 463 464
    LOG(FATAL) << "Not implemented";
  }

L
Luo Tao 已提交
465 466 467 468 469 470
  virtual void sequenceAvgBackward(Matrix& a,
                                   const IVector& startsPos,
                                   int mode) {
    LOG(FATAL) << "Not implemented";
  }

Z
zhangjinchao01 已提交
471 472 473 474 475
  /**
   * @code
   * this = scaleAB*(a*b) + scaleT*this
   * @endcode
   */
476 477
  virtual void mul(const Matrix& a,
                   const Matrix& b,
478
                   real scaleAB,
Z
zhangjinchao01 已提交
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
                   real scaleT) {
    LOG(FATAL) << "Not implemented";
  }

  /// Add a vector (column) b to matrix a, column by column.
  virtual void addColumnVector(const Matrix& b) {
    LOG(FATAL) << "Not implemented";
  }

  /**
   * @code
   * For j < codeLength:
   *   this(i, j) += vec(index(i, j), 0)
   * where index(i, j) = ((codes(i) + numClasses) >> (j + 1)) - 1
   * @endcode
   */
495 496
  virtual void addByBitCode(size_t numClasses,
                            const IVector& codes,
Z
zhangjinchao01 已提交
497 498 499 500 501 502 503 504 505 506 507 508 509 510
                            const Matrix& vec) {
    (void)numClasses;
    (void)codes;
    (void)vec;
    LOG(FATAL) << "Not implemeted";
  }

  /**
   * @code
   * For j < codeLength:
   *   vec(index(i, j), 0) += this(i, j)
   * where index is same as the index for addByBitCode
   * @endcode
   */
511 512
  virtual void addByBitCodeBackward(size_t numClasses,
                                    const IVector& codes,
Z
zhangjinchao01 已提交
513 514 515 516 517 518 519 520 521 522 523 524 525 526
                                    Matrix& vec) {
    (void)numClasses;
    (void)codes;
    (void)vec;
    LOG(FATAL) << "Not implemeted";
  }

  /**
   * @code
   * For j < codeLength:
   *   this(i, j) += <mat.row(index(i, j)), input.row(i)>
   * where index is same as the index for addByBitCode
   * @endcode
   */
527 528 529 530
  virtual void mulByBitCode(size_t numClasses,
                            const IVector& codes,
                            const Matrix& mat,
                            const Matrix& input) {
Z
zhangjinchao01 已提交
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
    (void)numClasses;
    (void)codes;
    (void)mat;
    (void)input;
    LOG(FATAL) << "Not implemeted";
  }

  /**
   * @code
   * For j < codeLength:
   *   mat.row(index(i, j)) += this(i, j) * input.row(i)
   * where index is same as the index for addByBitCode
   * @endcode
   */
  virtual void mulByBitCodeBackwardWeight(size_t numClasses,
546 547
                                          const IVector& codes,
                                          Matrix& mat,
Z
zhangjinchao01 已提交
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
                                          const Matrix& input) {
    (void)numClasses;
    (void)codes;
    (void)mat;
    (void)input;
    LOG(FATAL) << "Not implemeted";
  }

  /**
   * @code
   * For j < codeLength:
   *   input.row(i) += this(i, j) * mat.row(index(i, j))
   * where index is same as the index for addByBitCode
   * @endcode
   */
  virtual void mulByBitCodeBackwardError(size_t numClasses,
                                         const IVector& codes,
565 566
                                         const Matrix& mat,
                                         Matrix& input) {
Z
zhangjinchao01 已提交
567 568 569 570 571 572 573 574 575 576 577 578 579 580
    (void)numClasses;
    (void)codes;
    (void)mat;
    (void)input;
    LOG(FATAL) << "Not implemeted";
  }

  /**
   * @code
   * For j < codeLength
   *   sum(i, 0) = scaleSum * \sum_j  bit(i, j) * this(i, j)
   * where bit(i, j) = ((codes(i) + numClasses) & 2^j) ? 1 : 0
   * @endcode
   */
581 582 583
  virtual void sumByBitCode(size_t numClasses,
                            IVector& codes,
                            Matrix& sum,
Z
zhangjinchao01 已提交
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
                            real scaleSum) {
    (void)numClasses;
    (void)codes;
    (void)sum;
    (void)scaleSum;
    LOG(FATAL) << "Not implemeted";
  }

  /**
   * @code
   * For j < codeLength
   *  this(i, j) -= bit(i, j)
   * where bit(i, j) is same as that for sumByBitCode
   * @endcode
   */
  virtual void subByBitCode(size_t numClasses_, IVector& codes) {
    (void)numClasses_;
    (void)codes;
    LOG(FATAL) << "Not implemeted";
  }

  /**
   * add the sum of each row of this to mat
   */
  virtual void rowSum(Matrix& sum) {
    (void)sum;
    LOG(FATAL) << "Not implemeted";
  }

  /**
   * set the max of each row of this to mat
   */
  virtual void rowMax(Matrix& max) {
    (void)max;
    LOG(FATAL) << "Not implemeted";
  }

621 622 623
  /**
   * set the max of each column of this to mat
   */
Z
zhangjinchao01 已提交
624 625
  virtual void colMax(Matrix& max) { LOG(FATAL) << "not implemented"; }

626 627 628 629 630 631 632 633 634 635 636
  /**
   * @brief Get the top k elements of each column of this matrix.
   *
   * The row ids and values of these elements are stored in
   * maxIds and max respectively. where k is the size of maxIds.
   * And note that the top k elements are not sorted.
   */
  virtual void colMax(IVector& maxIds, Matrix& maxVal) {
    LOG(FATAL) << "not implemented";
  }

637 638 639
  virtual void maxoutForward(Matrix& a,
                             IVector& id,
                             size_t channels,
640 641 642 643
                             size_t groups) {
    LOG(FATAL) << "not implemented";
  }

644 645 646
  virtual void maxoutBackward(Matrix& a,
                              IVector& id,
                              size_t channels,
647 648 649 650
                              size_t groups) {
    LOG(FATAL) << "not implemented";
  }

Z
zhangjinchao01 已提交
651 652 653 654 655 656
  virtual void rowMaxId(IVector& maxIds) { LOG(FATAL) << "Not implemented"; }

  /**
   * @brief Get the top k elements of each row of this matrix.
   *
   * The column ids and values of these elements are stored in
657 658
   * maxIds and max respectively. where k is the size of maxIds.
   * And note that the top k elements are not sorted.
Z
zhangjinchao01 已提交
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
   */
  virtual void rowMax(IVector& maxIds, Matrix& max) {
    LOG(FATAL) << "Not implemented";
  }

  /// normalize each row so that the sum of each row is 1.
  virtual void rowNormalizeL1(Matrix& out) {
    (void)out;
    LOG(FATAL) << "Not implemeted";
  }

  /**
   * @code
   *  this = a*b
   * @endcode
   */
675
  virtual void mul(const Matrix& a, const Matrix& b) {
Z
zhangjinchao01 已提交
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
    LOG(FATAL) << "Not implemented";
  }

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

  /**
   * @code
   * this = this* b
   * @endcode
   */
  virtual void rightMul(Matrix& b) { LOG(FATAL) << "Not implemented"; }

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

  /**
   * @code
   * this = a*this)
   * @endcode
   */
  virtual void leftMul(Matrix& a) { LOG(FATAL) << "Not implemented"; }

  /// merge the element for each col.
  virtual void colMerge(Matrix& src) { LOG(FATAL) << "Not implemented"; }

  /// copy -log(output[label]) to this->data[i].
  virtual void oneHotCrossEntropy(Matrix& output, IVector& label) {
    LOG(FATAL) << "Not implemented";
  }

  /// calculate the error of outputV according to label.
  virtual void oneHotCrossEntropyBp(Matrix& outputV, IVector& label) {
    LOG(FATAL) << "Not implemented";
  }

  /// copy -log(output[label]) to this->data[i].
725 726
  virtual void oneHotCrossEntropyWithSelfNorm(Matrix& output,
                                              IVector& label,
Z
zhangjinchao01 已提交
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
                                              real alpha) {
    LOG(FATAL) << "Not implemented";
  }

  /// calculate the error of outputV according to label.
  virtual void oneHotCrossEntropyWithSelfNormBp(Matrix& outputV,
                                                IVector& label,
                                                real alpha) {
    LOG(FATAL) << "Not implemented";
  }

  /**
   * \f[
   *  a[i] = \sum_{j=-(N-1)/2}^{(N-1)/2} b_{i+j} * c_{j}
   * \f]
742
   *
Z
zhangjinchao01 已提交
743 744 745 746 747 748 749 750 751
   * b contains M elements,
   * c contains N elements (N is odd),
   * b's index arithmetic is computed modulo M,
   * c's index arithmetic is computed modulo N.
   */
  virtual void circularConv(Matrix& b, Matrix& c) {
    LOG(FATAL) << "Not implemented";
  }

752 753 754 755
  virtual void circularConvDerivative(Matrix& output,
                                      Matrix& prevOut1,
                                      Matrix& prevOut2,
                                      Matrix& prevGrad1,
Z
zhangjinchao01 已提交
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
                                      Matrix& prevGrad2) {
    LOG(FATAL) << "Not implemented";
  }

  /* output_ij = exp(this_{ij}) / (sum_j exp(this_ij)) */
  virtual void softmax(Matrix& output) {
    (void)output;
    LOG(FATAL) << "Not implemeted";
  }
  virtual void sequenceSoftmax(Matrix& output, const IVector& index) {
    (void)output;
    LOG(FATAL) << "Not implemeted";
  }

  virtual void softmaxBackward(Matrix& outputV) {
    (void)outputV;
    LOG(FATAL) << "Not implemeted";
  }

  /*
    sum_i = sum_j this_ij * output_ij
    this_ij = output_ij* (this_ij - sum_i)
  */
  virtual void softmaxDerivative(Matrix& output, Matrix& sftmaxSum) {
    LOG(FATAL) << "Not implemented";
  }

  /// calculate the sum of squares diff cost.
  virtual void sumOfSquares(Matrix& output, Matrix& label) {
    LOG(FATAL) << "Not implemented";
  }

  /// gradient of sumOfSquares.
  virtual void sumOfSquaresBp(Matrix& outputV, Matrix& label) {
    LOG(FATAL) << "Not implemented";
  }

793
  virtual void smoothL1(Matrix& output, Matrix& label, real destScale) {
G
gaoyuan 已提交
794 795 796
    LOG(FATAL) << "Not implemented";
  }

797
  virtual void smoothL1Bp(Matrix& outputV, Matrix& label, real destScale) {
G
gaoyuan 已提交
798 799 800
    LOG(FATAL) << "Not implemented";
  }

Z
zhangjinchao01 已提交
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
  virtual void tanh(Matrix& output) { LOG(FATAL) << "Not implemented"; }

  virtual void tanhDerivative(Matrix& output) {
    LOG(FATAL) << "Not implemented";
  }

  virtual void softrelu(Matrix& output) { LOG(FATAL) << "Not implemented"; }

  virtual void softreluDerivative(Matrix& output) {
    LOG(FATAL) << "Not implemented";
  }

  virtual void scaledTanh(Matrix& output, real p1, real p2) {
    LOG(FATAL) << "Not implemented";
  }

  /// print out the values of elements to os
  virtual void print(std::ostream& os) const {
    LOG(FATAL) << "Not implemented";
  }

  /**
   * print a part of the matrix
   * from the (top,left) value to the (height, width) value (not included)
   */
  virtual void print(std::ostream& os, size_t height, size_t width) const {
    LOG(FATAL) << "Not implemented";
  }

  /// print one row to os
  virtual void printOneRow(std::ostream& os, size_t idx) const {
    LOG(FATAL) << "Not implemented";
  }

  virtual void check(std::ostream& os, Matrix& refMat, bool printDiff = true) {}

  virtual real getMin() {
    LOG(FATAL) << "Not implemented";
    return 0;
  }
  virtual real getMax() {
    LOG(FATAL) << "Not implemented";
    return 0;
  }

  virtual void randomizeUniform() { LOG(FATAL) << "Not implemented"; }

  /**
   * @brief  calulate the error of classification
   *
   * output[i] = 1 if row i is an error.
   *
   * output[i] = 0 if row i is correct.
854
   *
Z
zhangjinchao01 已提交
855
   */
856 857 858
  virtual void classificationError(Matrix& output,
                                   IVector& label,
                                   size_t topkSize = 1) {
Z
zhangjinchao01 已提交
859 860 861
    LOG(FATAL) << "Not implemented";
  }

X
xzl 已提交
862
  virtual void upsampleForward(Matrix& input,
X
xzl 已提交
863 864 865 866 867 868
                               Matrix& mask,
                               size_t imgSizeH,
                               size_t imgSizeW,
                               size_t channels,
                               size_t outputH,
                               size_t outputW) {
X
xzl 已提交
869 870 871 872
    LOG(FATAL) << "Not implemeted";
  }

  virtual void upsampleBackward(Matrix& outputGrad,
X
xzl 已提交
873 874 875 876 877 878
                                Matrix& mask,
                                size_t imgSizeH,
                                size_t imgSizeW,
                                size_t channels,
                                size_t outputH,
                                size_t outputW) {
X
xzl 已提交
879 880 881
    LOG(FATAL) << "Not implemeted";
  }

Z
zhangjinchao01 已提交
882 883
  /**
   * Pooling forward operation, pick out the largest element
884
   * in the sizeX of value, if the maskMatP is not NULL, it will
X
xzl 已提交
885 886 887 888 889 890 891 892 893 894 895 896 897 898
   * also caculate the location indices.
   */
  virtual void 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,
899
                              MatrixPtr maskMatP = NULL) {
X
xzl 已提交
900 901 902
    LOG(FATAL) << "Not implemeted";
  }

Z
zhangjinchao01 已提交
903
  /// Pooling backward operation.
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
  virtual void 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 已提交
919 920 921 922
    LOG(FATAL) << "Not implemeted";
  }

  /// Pooling forward operation, caculate the average of sizeX elements.
923 924 925 926 927 928 929 930 931 932 933
  virtual void 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,
934 935
                              size_t paddingW,
                              bool excludeMode = true) {
Z
zhangjinchao01 已提交
936 937 938
    LOG(FATAL) << "Not implemeted";
  }

939 940 941 942 943 944 945 946 947 948 949 950
  virtual void 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,
951 952
                               size_t paddingW,
                               bool excludeMode = true) {
Z
zhangjinchao01 已提交
953 954
    LOG(FATAL) << "Not implemeted";
  }
955

Z
zhangjinchao01 已提交
956
  /**
C
chengduoZH 已提交
957 958
   * Pooling 3D forward operation, pick out the largest element
   * in the sizeX of value
Z
zhangjinchao01 已提交
959
   */
C
chengduoZH 已提交
960
  virtual void maxPool3DForward(Matrix& inputMat,
C
chengduoZH 已提交
961
                                Matrix& maxPoolIdx,
C
chengduoZH 已提交
962
                                size_t channels,
C
chengduoZH 已提交
963 964 965
                                size_t imgSizeD,
                                size_t imgSizeH,
                                size_t imgSizeW,
C
chengduoZH 已提交
966 967 968
                                size_t outputD,
                                size_t outputH,
                                size_t outputW,
C
chengduoZH 已提交
969 970 971 972 973 974 975 976 977 978 979 980
                                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) {
    LOG(FATAL) << "Not implemeted";
  }

C
chengduoZH 已提交
981 982
  virtual void maxPool3DBackward(Matrix& outGrad,
                                 Matrix& maxPoolIdx,
C
chengduoZH 已提交
983 984 985
                                 size_t imgSizeD,
                                 size_t imgSizeH,
                                 size_t imgSizeW,
C
chengduoZH 已提交
986 987 988
                                 size_t outputD,
                                 size_t outputH,
                                 size_t outputW,
C
chengduoZH 已提交
989 990 991 992 993 994 995 996
                                 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 已提交
997 998 999
                                 size_t paddingW,
                                 real scaleTargets,
                                 real scaleOutput) {
C
chengduoZH 已提交
1000 1001 1002 1003
    LOG(FATAL) << "Not implemeted";
  }

  virtual void avgPool3DForward(Matrix& input,
C
chengduoZH 已提交
1004
                                size_t channels,
C
chengduoZH 已提交
1005 1006 1007
                                size_t imgSizeD,
                                size_t imgSizeH,
                                size_t imgSizeW,
C
chengduoZH 已提交
1008 1009 1010
                                size_t outputD,
                                size_t outputH,
                                size_t outputW,
C
chengduoZH 已提交
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
                                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) {
    LOG(FATAL) << "Not implemeted";
  }

  virtual void avgPool3DBackward(Matrix& input,
                                 size_t imgSizeD,
                                 size_t imgSizeH,
                                 size_t imgSizeW,
C
chengduoZH 已提交
1027 1028 1029
                                 size_t outputD,
                                 size_t outputH,
                                 size_t outputW,
C
chengduoZH 已提交
1030 1031 1032 1033 1034 1035 1036 1037
                                 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 已提交
1038 1039 1040
                                 size_t paddingW,
                                 real scaleTargets,
                                 real scaleOutput) {
C
chengduoZH 已提交
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
    LOG(FATAL) << "Not implemeted";
  }

  /**
 * 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_input[i].
 */
1052 1053
  virtual void maxSequenceForward(Matrix& input,
                                  const IVector& sequence,
Z
zhangjinchao01 已提交
1054 1055 1056 1057
                                  IVector& index) {
    LOG(FATAL) << "Not implemeted";
  }

1058 1059
  virtual void maxSequenceBackward(Matrix& outputGrad,
                                   const IVector& sequence,
Z
zhangjinchao01 已提交
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 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
                                   IVector& index) {
    LOG(FATAL) << "Not implemeted";
  }

  /**
   * @code
   * this.row[i] += table.row[ids[i]]
   * if ids[i] == -1, it will be ignored
   * @endcode
   */
  virtual void selectRows(Matrix& table, IVector& ids) {
    (void)table;
    (void)ids;
    LOG(FATAL) << "Not implemented";
  }

  /**
   * @code
   * this[i] = table[i, id[i]]
   * @endcode
   */
  virtual void selectElements(Matrix& table, IVector& ids) {
    LOG(FATAL) << "Not implemented";
  }

  /**
   * @code
   * table.row[ids[i]] += this.row[i]
   * if ids[i] == -1, it will be ignored
   * @endcode
   */
  virtual void addToRows(Matrix& table, IVector& ids) {
    (void)table;
    (void)ids;
    LOG(FATAL) << "Not implemented";
  }

  /**
   * @code
   * table[i, id[i]] += this[i]
   * @endcode
   */
  virtual void addElements(Matrix& table, IVector& ids) {
    LOG(FATAL) << "Not implemented";
  }
  /**
   * @brief  cross entropy for multi binary labels
   *
   * @code
   * this[i] = -sum(label[i][j]*log(output[i][j])
   *           + (1-label[i][j])*log(1-output[i][j]))
1111
   * @endcode
Z
zhangjinchao01 已提交
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
   */
  virtual void multiBinaryLabelCrossEntropy(Matrix& output, Matrix& label) {
    LOG(FATAL) << "Not implemented";
  }

  /**
   * @brief  The gradient of cross entropy for multi binary labels on output
   *
   * @code
   * this[i][j] = -label[i][j]/output[i][j]
   *              + (1-label[i][j])/(1-output[i][j])
1123
   * @endcode
Z
zhangjinchao01 已提交
1124 1125 1126 1127 1128 1129 1130
   */
  virtual void multiBinaryLabelCrossEntropyBp(Matrix& output, Matrix& label) {
    LOG(FATAL) << "Not implemented";
  }

  /**
   * @brief  Calculate the classification error for multi binary labels
1131
   *
Z
zhangjinchao01 已提交
1132 1133 1134 1135
   * @code
   * this[i] = sum((output[i][j] >= threshold && label[i][j] == 0)
   *            || (output[i][j] < threshold && label[i][j] == 1))
   *            / output->getWidth()
1136
   * @endcode
Z
zhangjinchao01 已提交
1137
   */
1138 1139
  virtual void classificationErrorMulti(Matrix& output,
                                        Matrix& label,
Z
zhangjinchao01 已提交
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
                                        real threshold) {
    LOG(FATAL) << "Not implemented";
  }

  virtual void paramReluForward(Matrix& data, Matrix& W) {
    LOG(FATAL) << "Not implemented";
  }
  virtual void paramReluBackwardW(Matrix& oGrad, Matrix& data) {
    LOG(FATAL) << "Not implemented";
  }
  virtual void paramReluBackwardDiff(Matrix& oGrad, Matrix& data, Matrix& W) {
    LOG(FATAL) << "Not implemented";
  }
H
hedaoyuan 已提交
1153

C
chengduoZH 已提交
1154
  virtual void vol2Col(real* data,
C
chengduoZH 已提交
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
                       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) {
    LOG(FATAL) << "Not implemeted";
  }
C
chengduoZH 已提交
1170

C
chengduoZH 已提交
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
  virtual void 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) {
    LOG(FATAL) << "Not implemeted";
  }
C
chengduoZH 已提交
1189

L
liaogang 已提交
1190 1191 1192 1193 1194
  virtual void bilinearForward(const Matrix& in,
                               const size_t inImgH,
                               const size_t inImgW,
                               const size_t outImgH,
                               const size_t outImgW,
L
liaogang 已提交
1195 1196 1197
                               const size_t numChannels,
                               const real ratioH,
                               const real ratioW) {
L
liaogang 已提交
1198 1199 1200 1201 1202 1203 1204
    LOG(FATAL) << "Not implemented";
  }
  virtual void bilinearBackward(const Matrix& out,
                                const size_t outImgH,
                                const size_t outImgW,
                                const size_t inImgH,
                                const size_t inImgW,
L
liaogang 已提交
1205 1206 1207
                                const size_t numChannels,
                                const real ratioH,
                                const real ratioW) {
L
liaogang 已提交
1208 1209
    LOG(FATAL) << "Not implemented";
  }
1210 1211

  template <typename ExpressionType>
H
hedaoyuan 已提交
1212 1213 1214 1215 1216 1217 1218
  void operator=(const ExpressionType& expr) {
    if (useGpu_) {
      TensorGpuApply<real>(*this, expr);
    } else {
      TensorCpuApply<real>(*this, expr);
    }
  }
1219 1220 1221 1222

  bool isEmpty() const { return data_ == nullptr; }

  explicit operator bool() const { return !isEmpty(); }
Z
zhangjinchao01 已提交
1223 1224 1225 1226 1227 1228 1229 1230
};

inline std::ostream& operator<<(std::ostream& os, const Matrix& mat) {
  mat.print(os);
  return os;
}

class GpuMatrix : public Matrix {
W
Wu Yi 已提交
1231
 public:
Z
zhangjinchao01 已提交
1232 1233 1234 1235 1236
  GpuMatrix();

  GpuMatrix(size_t height, size_t width, bool trans = false);
  GpuMatrix(real* data, size_t height, size_t width, bool trans = false)
      : Matrix(data, height, width, trans, true) {}
1237 1238 1239 1240
  GpuMatrix(real* data,
            size_t height,
            size_t width,
            size_t stride,
Z
zhangjinchao01 已提交
1241 1242
            bool trans = false)
      : Matrix(data, height, width, stride, trans, true) {}
1243 1244 1245
  GpuMatrix(GpuMemHandlePtr dataHandle,
            size_t height,
            size_t width,
Z
zhangjinchao01 已提交
1246 1247 1248 1249 1250 1251
            bool trans = false)
      : Matrix(dataHandle, height, width, trans, true) {}
  ~GpuMatrix();

  void zeroMem();
  void resetOne();
1252
  void setDiag(real value);
Z
zhangjinchao01 已提交
1253 1254

  void resize(size_t newHeight, size_t newWidth);
1255 1256
  void resize(size_t newHeight,
              size_t newWidth,
Z
zhangjinchao01 已提交
1257
              size_t newNnz, /* used to allocate space */
1258 1259
              SparseValueType valueType,
              SparseFormat format) {
Z
zhangjinchao01 已提交
1260 1261
    LOG(FATAL) << "Only Support Sparse Matrix";
  }
1262 1263 1264
  void setRow(size_t row,
              size_t colNum,
              const unsigned int* cols,
Z
zhangjinchao01 已提交
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
              const real* values) {
    LOG(FATAL) << "Only Support Sparse Matrix";
  }

  /**
   * Copy the data from cpu_memory buffer
   */
  void copyFrom(const real* hostSrc, size_t size);

  void copyFrom(const real* hostSrc, const int64_t* seq);

  void copyFrom(const Matrix& src, hl_stream_t stream);

  void copyFrom(const Matrix& src);

  void copyFrom(const IVector& src);

1282
  void copyByRowIndex(Matrix& b, const IVector& rowIndex);
Z
zhangjinchao01 已提交
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294

  MatrixPtr clone(size_t height, size_t width, bool useGpu = false);

  real getElement(size_t x, size_t y) const;

  real* getRow(size_t row) { return BaseMatrix::rowBuf(row); }
  virtual real* getRowBuf(size_t row) { return getRow(row); }

  real getSum();
  void accumulateColSum(Matrix& src);
  real getAbsSum();

1295 1296 1297
  real getMin();
  real getMax();

Z
zhangjinchao01 已提交
1298
  MatrixPtr getTranspose();
1299 1300
  void transpose(MatrixPtr& matTrans, bool memAlloc);
  void rotate(MatrixPtr& matRot, bool memAlloc, bool clockWise);
Z
zhangjinchao01 已提交
1301

L
lzhao4ever 已提交
1302
  MatrixPtr getInverse();
1303
  void inverse(MatrixPtr& matInv, bool memAlloc);
L
lzhao4ever 已提交
1304

Z
zhangjinchao01 已提交
1305 1306
  /// add b to each sample of this.
  void addBias(Matrix& b, real scale);
1307
  void addSharedBias(Matrix& b, real scale);
Z
zhangjinchao01 已提交
1308 1309 1310 1311 1312 1313 1314

  /**
   * @code
   * add each sample from a to this.
   * @endcode
   */
  void collectBias(Matrix& a, real scale);
1315
  void collectSharedBias(Matrix& a, real scale);
Z
zhangjinchao01 已提交
1316 1317

  void sequenceAvgForward(Matrix& a, const IVector& startsPos, int mode);
L
Luo Tao 已提交
1318
  void sequenceAvgBackward(Matrix& a, const IVector& startsPos, int mode);
Z
zhangjinchao01 已提交
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347

  /**
   * @code
   * this.row[i] += table.row[ids[i]]
   * @endcode
   */
  virtual void selectRows(Matrix& table, IVector& ids);

  /**
   * @code
   * this[i] = table[i, id[i]]
   * @endcode
   */
  virtual void selectElements(Matrix& table, IVector& ids);

  /**
   * @code
   * table.row[ids[i]] += this.row[i]
   * @endcode
   */
  virtual void addToRows(Matrix& table, IVector& ids);

  void addColumnVector(const Matrix& b);

  /**
   * @code
   * this = scaleAB*(a*b) + scaleT*this
   * @endcode
   */
1348
  void mul(const Matrix& a, const Matrix& b, real scaleAB, real scaleT);
Z
zhangjinchao01 已提交
1349 1350 1351 1352 1353 1354

  /**
   * @code
   * this = a*b
   * @endcode
   */
1355
  void mul(const Matrix& a, const Matrix& b);
Z
zhangjinchao01 已提交
1356 1357 1358

  void mul(const GpuMatrix& a, const GpuMatrix& b, real scaleAB, real scaleT);

1359 1360 1361
  void mul(const GpuSparseMatrix& a,
           const GpuMatrix& b,
           real scaleAB,
Z
zhangjinchao01 已提交
1362 1363
           real scaleT);

1364 1365 1366
  void mul(const GpuMatrix& a,
           const GpuSparseMatrix& b,
           real scaleAB,
Z
zhangjinchao01 已提交
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
           real scaleT);

  /**
   * @code
   * this = scaleAB*(this*b) +  scaleT*this
   * @endcode
   */
  void rightMul(Matrix& b, real scaleAB, real scaleT);

  /**
   * @code
   * this = this* b
   * @endcode
   */
  void rightMul(Matrix& b);

  /**
   * @code
   * this = scaleAB*(a*this) +  scaleT*this
   * @endcode
   */
  void leftMul(Matrix& a, real scaleAB, real scaleT);

  /**
   * @code
   * this = a*this
   * @endcode
   */
  void leftMul(Matrix& a);

  void colMerge(Matrix& src);
  void rowSum(Matrix& sum);
  void rowMax(Matrix& max);
  void rowMax(IVector& maxIds, Matrix& max);
  void colMax(Matrix& max);
1402 1403 1404
  void colMax(IVector& maxIds, Matrix& max);
  void maxoutForward(Matrix& a, IVector& id, size_t channels, size_t groups);
  void maxoutBackward(Matrix& a, IVector& id, size_t channels, size_t groups);
Z
zhangjinchao01 已提交
1405 1406 1407

  void oneHotCrossEntropy(Matrix& output, IVector& label);
  void oneHotCrossEntropyBp(Matrix& outputV, IVector& label);
1408 1409
  void oneHotCrossEntropyWithSelfNorm(Matrix& output,
                                      IVector& label,
Z
zhangjinchao01 已提交
1410
                                      real alpha);
1411 1412
  void oneHotCrossEntropyWithSelfNormBp(Matrix& outputV,
                                        IVector& label,
Z
zhangjinchao01 已提交
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
                                        real alpha);

  void softmax(Matrix& output);
  void sequenceSoftmax(Matrix& output, const IVector& index);
  void softmaxBackward(Matrix& outputV);
  void softmaxDerivative(Matrix& output, Matrix& sftmaxSum);

  /// calculate the sum of squares diff cost.
  void sumOfSquares(Matrix& output, Matrix& label);

  /// gradient of sumOfSquares.
  void sumOfSquaresBp(Matrix& outputV, Matrix& label);
  void tanh(Matrix& output);
  void tanhDerivative(Matrix& output);
  void softrelu(Matrix& output);
  void softreluDerivative(Matrix& output);
  void scaledTanh(Matrix& output, real p1, real p2);

  virtual void print(std::ostream& os) const;
  virtual void print(std::ostream& os, size_t height, size_t width) const;

  void paramReluForward(Matrix& data, Matrix& W);
  void paramReluBackwardW(Matrix& oGrad, Matrix& data);
  void paramReluBackwardDiff(Matrix& oGrad, Matrix& data, Matrix& W);

  void check(std::ostream& os, Matrix& refMat, bool printDiff = true);
  void randomizeUniform();

1441
  void classificationError(Matrix& output, IVector& label, size_t topkSize = 1);
Z
zhangjinchao01 已提交
1442

X
xzl 已提交
1443
  void upsampleForward(Matrix& input,
X
xzl 已提交
1444 1445 1446 1447 1448 1449
                       Matrix& mask,
                       size_t imgSizeH,
                       size_t imgSizeW,
                       size_t channels,
                       size_t outputH,
                       size_t outputW);
X
xzl 已提交
1450 1451

  void upsampleBackward(Matrix& outputGrad,
X
xzl 已提交
1452 1453 1454 1455 1456 1457
                        Matrix& mask,
                        size_t imgSizeH,
                        size_t imgSizeW,
                        size_t channels,
                        size_t outputH,
                        size_t outputW);
X
xzl 已提交
1458

X
xzl 已提交
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
  void 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,
1471
                      MatrixPtr maskMatP);
X
xzl 已提交
1472

1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
  void 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);

  void 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,
1500 1501
                      size_t paddingW,
                      bool excludeMode = true);
1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514

  void 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,
1515 1516
                       size_t paddingW,
                       bool excludeMode = true);
1517

C
chengduoZH 已提交
1518
  void maxPool3DForward(Matrix& inputMat,
C
chengduoZH 已提交
1519
                        Matrix& maxPoolIdx,
C
chengduoZH 已提交
1520
                        size_t channels,
C
chengduoZH 已提交
1521 1522 1523
                        size_t imgSizeD,
                        size_t imgSizeH,
                        size_t imgSizeW,
C
chengduoZH 已提交
1524 1525 1526
                        size_t outputD,
                        size_t outputH,
                        size_t outputW,
C
chengduoZH 已提交
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
                        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 已提交
1537 1538
  void maxPool3DBackward(Matrix& outGrad,
                         Matrix& maxPoolIdx,
C
chengduoZH 已提交
1539 1540 1541
                         size_t imgSizeD,
                         size_t imgSizeH,
                         size_t imgSizeW,
C
chengduoZH 已提交
1542 1543 1544
                         size_t outputD,
                         size_t outputH,
                         size_t outputW,
C
chengduoZH 已提交
1545 1546 1547 1548 1549 1550 1551 1552
                         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 已提交
1553 1554 1555
                         size_t paddingW,
                         real scaleTargets,
                         real scaleOutput);
C
chengduoZH 已提交
1556 1557

  void avgPool3DForward(Matrix& input,
C
chengduoZH 已提交
1558
                        size_t channels,
C
chengduoZH 已提交
1559 1560 1561
                        size_t imgSizeD,
                        size_t imgSizeH,
                        size_t imgSizeW,
C
chengduoZH 已提交
1562 1563 1564
                        size_t outputD,
                        size_t outputH,
                        size_t outputW,
C
chengduoZH 已提交
1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
                        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);

  void avgPool3DBackward(Matrix& input,
                         size_t imgSizeD,
                         size_t imgSizeH,
                         size_t imgSizeW,
C
chengduoZH 已提交
1579 1580 1581
                         size_t outputD,
                         size_t outputH,
                         size_t outputW,
C
chengduoZH 已提交
1582 1583 1584 1585 1586 1587 1588 1589
                         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 已提交
1590 1591 1592
                         size_t paddingW,
                         real scaleTargets,
                         real scaleOutput);
C
chengduoZH 已提交
1593

1594 1595
  void maxSequenceForward(Matrix& input,
                          const IVector& sequence,
Z
zhangjinchao01 已提交
1596 1597
                          IVector& index);

1598 1599
  void maxSequenceBackward(Matrix& outputGrad,
                           const IVector& sequence,
Z
zhangjinchao01 已提交
1600 1601
                           IVector& index);

L
liaogang 已提交
1602 1603 1604 1605 1606
  void bilinearForward(const Matrix& in,
                       const size_t inImgH,
                       const size_t inImgW,
                       const size_t outImgH,
                       const size_t outImgW,
L
liaogang 已提交
1607 1608 1609
                       const size_t numChannels,
                       const real ratioH,
                       const real ratioW);
L
liaogang 已提交
1610 1611 1612 1613 1614 1615

  void bilinearBackward(const Matrix& out,
                        const size_t outImgH,
                        const size_t outImgW,
                        const size_t inImgH,
                        const size_t inImgW,
L
liaogang 已提交
1616 1617 1618
                        const size_t numChannels,
                        const real ratioH,
                        const real ratioW);
1619

C
chengduoZH 已提交
1620
  void vol2Col(real* data,
C
chengduoZH 已提交
1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
               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);
C
chengduoZH 已提交
1634 1635

  void col2Vol(real* trg,
C
chengduoZH 已提交
1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
               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);
C
chengduoZH 已提交
1651

1652 1653 1654
  void multiBinaryLabelCrossEntropy(Matrix& output, Matrix& label);

  void multiBinaryLabelCrossEntropyBp(Matrix& output, Matrix& label);
1655 1656

  template <typename ExpressionType>
H
hedaoyuan 已提交
1657 1658 1659
  void operator=(const ExpressionType& expr) {
    TensorGpuApply<real>(*this, expr);
  }
Z
zhangjinchao01 已提交
1660 1661 1662
};

class CpuMatrix : public Matrix {
W
Wu Yi 已提交
1663
 private:
1664 1665 1666
  MatrixPtr sftmaxSum_;
  MatrixPtr sftmaxDot_;

W
Wu Yi 已提交
1667
 public:
Z
zhangjinchao01 已提交
1668 1669 1670
  CpuMatrix(size_t height, size_t width, bool trans = false);
  CpuMatrix(real* data, size_t height, size_t width, bool trans = false)
      : Matrix(data, height, width, trans, false) {}
1671 1672 1673 1674
  CpuMatrix(real* data,
            size_t height,
            size_t width,
            size_t stride,
Z
zhangjinchao01 已提交
1675 1676 1677
            bool trans = false)
      : Matrix(data, height, width, stride, trans, false) {}

1678 1679 1680
  CpuMatrix(CpuMemHandlePtr dataHandle,
            size_t height,
            size_t width,
Z
zhangjinchao01 已提交
1681 1682 1683 1684 1685 1686 1687
            bool trans = false)
      : Matrix(dataHandle, height, width, trans, false) {}

  ~CpuMatrix();

  void zeroMem();
  void resetOne();
1688 1689
  void setDiag(real value);

Z
zhangjinchao01 已提交
1690
  void resize(size_t newHeight, size_t newWidth);
1691 1692
  void resize(size_t newHeight,
              size_t newWidth,
Z
zhangjinchao01 已提交
1693
              size_t newNnz, /* used to allocate space */
1694 1695
              SparseValueType valueType,
              SparseFormat format) {
Z
zhangjinchao01 已提交
1696 1697
    LOG(FATAL) << "Only Support Sparse Matrix";
  }
1698 1699 1700
  void setRow(size_t row,
              size_t colNum,
              const unsigned int* cols,
Z
zhangjinchao01 已提交
1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
              const real* values) {
    LOG(FATAL) << "Only Support Sparse Matrix";
  }

  real getElement(size_t x, size_t y) const;
  real getSum();
  void accumulateColSum(Matrix& src);
  real getAbsSum();

  MatrixPtr getTranspose();
1711 1712
  void transpose(MatrixPtr& matTrans, bool memAlloc);
  void rotate(MatrixPtr& matRot, bool memAlloc, bool clockWise);
Z
zhangjinchao01 已提交
1713

L
lzhao4ever 已提交
1714
  MatrixPtr getInverse();
1715
  void inverse(MatrixPtr& matInv, bool memAlloc);
L
lzhao4ever 已提交
1716

Z
zhangjinchao01 已提交
1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
  void copyFrom(const Matrix& src);

  void copyFrom(const Matrix& src, hl_stream_t stream);

  void copyFrom(const real* cpuSrc, size_t size);

  void copyFrom(const real* cpuSrc, const int64_t* seq);

  void copyFrom(const IVector& src);

  void copyFrom(CpuSparseMatrix& src);

1729
  void copyByRowIndex(Matrix& b, const IVector& rowIndex);
Z
zhangjinchao01 已提交
1730 1731 1732

  MatrixPtr clone(size_t height, size_t width, bool useGpu = false);

X
xzl 已提交
1733
  void upsampleForward(Matrix& input,
X
xzl 已提交
1734 1735 1736 1737 1738 1739
                       Matrix& mask,
                       size_t imgSizeH,
                       size_t imgSizeW,
                       size_t channels,
                       size_t outputH,
                       size_t outputW);
X
xzl 已提交
1740 1741

  void upsampleBackward(Matrix& outputGrad,
X
xzl 已提交
1742 1743 1744 1745 1746 1747
                        Matrix& mask,
                        size_t imgSizeH,
                        size_t imgSizeW,
                        size_t channels,
                        size_t outputH,
                        size_t outputW);
X
xzl 已提交
1748

X
xzl 已提交
1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
  void 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,
1761
                      MatrixPtr maskMatP);
X
xzl 已提交
1762

1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
  void 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);

  void 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,
1790 1791
                      size_t paddingW,
                      bool excludeMode = true);
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804

  void 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,
1805 1806
                       size_t paddingW,
                       bool excludeMode = true);
1807

C
chengduoZH 已提交
1808
  void maxPool3DForward(Matrix& inputMat,
C
chengduoZH 已提交
1809
                        Matrix& maxPoolIdx,
C
chengduoZH 已提交
1810
                        size_t channels,
C
chengduoZH 已提交
1811 1812 1813
                        size_t imgSizeD,
                        size_t imgSizeH,
                        size_t imgSizeW,
C
chengduoZH 已提交
1814 1815 1816
                        size_t outputD,
                        size_t outputH,
                        size_t outputW,
C
chengduoZH 已提交
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826
                        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 已提交
1827 1828
  void maxPool3DBackward(Matrix& outGrad,
                         Matrix& maxPoolIdx,
C
chengduoZH 已提交
1829 1830 1831
                         size_t imgSizeD,
                         size_t imgSizeH,
                         size_t imgSizeW,
C
chengduoZH 已提交
1832 1833 1834
                         size_t outputD,
                         size_t outputH,
                         size_t outputW,
C
chengduoZH 已提交
1835 1836 1837 1838 1839 1840 1841 1842
                         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 已提交
1843 1844 1845
                         size_t paddingW,
                         real scaleTargets,
                         real scaleOutput);
C
chengduoZH 已提交
1846 1847

  void avgPool3DForward(Matrix& input,
C
chengduoZH 已提交
1848
                        size_t channels,
C
chengduoZH 已提交
1849 1850 1851
                        size_t imgSizeD,
                        size_t imgSizeH,
                        size_t imgSizeW,
C
chengduoZH 已提交
1852 1853 1854
                        size_t outputD,
                        size_t outputH,
                        size_t outputW,
C
chengduoZH 已提交
1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868
                        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);

  void avgPool3DBackward(Matrix& input,
                         size_t imgSizeD,
                         size_t imgSizeH,
                         size_t imgSizeW,
C
chengduoZH 已提交
1869 1870 1871
                         size_t outputD,
                         size_t outputH,
                         size_t outputW,
C
chengduoZH 已提交
1872 1873 1874 1875 1876 1877 1878 1879
                         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 已提交
1880 1881 1882
                         size_t paddingW,
                         real scaleTargets,
                         real scaleOutput);
1883 1884 1885

  void maxSequenceForward(Matrix& input,
                          const IVector& sequence,
Z
zhangjinchao01 已提交
1886 1887
                          IVector& index);

1888 1889
  void maxSequenceBackward(Matrix& outputGrad,
                           const IVector& sequence,
Z
zhangjinchao01 已提交
1890 1891 1892 1893 1894
                           IVector& index);

  real* getRow(size_t row) { return BaseMatrix::rowBuf(row); }
  virtual real* getRowBuf(size_t row) { return getRow(row); }

W
Wu Yi 已提交
1895
 public:
Z
zhangjinchao01 已提交
1896 1897
  /// add b to each sample of this.
  void addBias(Matrix& b, real scale);
1898
  void addSharedBias(Matrix& b, real scale);
Z
zhangjinchao01 已提交
1899 1900 1901

  /// add each sample of a to this.
  void collectBias(Matrix& a, real scale);
1902
  void collectSharedBias(Matrix& a, real scale);
Z
zhangjinchao01 已提交
1903 1904

  void sequenceAvgForward(Matrix& a, const IVector& startsPos, int mode);
L
Luo Tao 已提交
1905
  void sequenceAvgBackward(Matrix& a, const IVector& startsPos, int mode);
Z
zhangjinchao01 已提交
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917

  /**
   * @code
   * this.row[i] += table.row[ids[i]]
   * @endcode
   */
  virtual void selectRows(Matrix& table, IVector& ids);

  /**
   * @code
   * table.row[ids[i]] += this.row[i]
   * @endcode
1918
   */
Z
zhangjinchao01 已提交
1919 1920 1921 1922 1923 1924
  virtual void addToRows(Matrix& table, IVector& ids);

  /**
   * @code
   * this[i] = table[i, id[i]]
   * @endcode
1925
   */
Z
zhangjinchao01 已提交
1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947
  virtual void selectElements(Matrix& table, IVector& ids);

  /**
   * @code
   * table[i, id[i]] += this[i]
   * @endcode
   */
  virtual void addElements(Matrix& table, IVector& ids);

  /**
   * use abstract getRow() to get row from table.
   *
   * Define table as template instead of virtual class for performance sake.
   * internal used by above two virtual funcs.
   */
  template <typename TableMatType>
  void selectRowsImp(TableMatType& table, IVector& ids);
  template <typename TableMatType>
  void addToRowsImp(TableMatType& table, IVector& ids);

  void addColumnVector(const Matrix& b);

1948
  void mul(const Matrix& a, const Matrix& b, real scaleAB, real scaleT);
Z
zhangjinchao01 已提交
1949 1950 1951 1952
  void mul(CpuMatrix* a, CpuMatrix* b, real scaleAB, real scaleT);

  void mul(CpuMatrix* a, CpuSparseMatrix* b, real scaleAB, real scaleT);

1953 1954 1955 1956
  static void mul(CpuMatrix* a,
                  CpuMatrix* b,
                  CpuSparseMatrix* c,
                  real scaleAB,
Z
zhangjinchao01 已提交
1957 1958 1959 1960 1961 1962 1963 1964 1965
                  real scaleT);

  /**
   * c = a * b
   *
   * use abstract getRow() to get row from B,C.
   * Define B,C as template instead of virtual class for performance sake.
   */
  template <typename MatBType, typename MatCType>
1966 1967
  static void mul(
      CpuSparseMatrix* a, MatBType* b, MatCType* c, real scaleAB, real scaleT);
Z
zhangjinchao01 已提交
1968 1969 1970

  virtual void mul(CpuSparseMatrix* a, CpuMatrix* b, real scaleAB, real scaleT);

1971
  void mul(const Matrix& a, const Matrix& b);
Z
zhangjinchao01 已提交
1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983

  void rightMul(Matrix& b, real scaleAB, real scaleT);
  void rightMul(Matrix& b);

  void leftMul(Matrix& a, real scaleAB, real scaleT);
  void leftMul(Matrix& a);
  void colMerge(Matrix& src);
  void rowSum(Matrix& sum);
  void rowMaxId(IVector& maxIds);
  void rowMax(Matrix& max);
  void rowMax(IVector& maxIds, Matrix& maxVal);
  void colMax(Matrix& max);
1984 1985 1986
  void colMax(IVector& maxIds, Matrix& maxVal);
  void maxoutForward(Matrix& a, IVector& id, size_t channels, size_t groups);
  void maxoutBackward(Matrix& a, IVector& id, size_t channels, size_t groups);
Z
zhangjinchao01 已提交
1987 1988 1989 1990
  void rowNormalizeL1(Matrix& out);

  void oneHotCrossEntropy(Matrix& output, IVector& label);
  void oneHotCrossEntropyBp(Matrix& outputV, IVector& label);
1991 1992
  void oneHotCrossEntropyWithSelfNorm(Matrix& output,
                                      IVector& label,
Z
zhangjinchao01 已提交
1993
                                      real alpha);
1994 1995
  void oneHotCrossEntropyWithSelfNormBp(Matrix& outputV,
                                        IVector& label,
Z
zhangjinchao01 已提交
1996 1997 1998
                                        real alpha);

  void circularConv(Matrix& b, Matrix& c);
1999 2000 2001 2002
  void circularConvDerivative(Matrix& output,
                              Matrix& prevOut1,
                              Matrix& prevOut2,
                              Matrix& prevGrad1,
Z
zhangjinchao01 已提交
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
                              Matrix& prevGrad2);

  void softmax(Matrix& output);
  void sequenceSoftmax(Matrix& output, const IVector& index);
  void softmaxDerivative(Matrix& output, Matrix& sftmaxSum);

  /// calculate the sum of squares diff cost.
  void sumOfSquares(Matrix& output, Matrix& label);

  /// gradient of sumOfSquares.
  void sumOfSquaresBp(Matrix& outputV, Matrix& label);

2015 2016
  void smoothL1(Matrix& output, Matrix& label, real destScale);
  void smoothL1Bp(Matrix& output, Matrix& label, real destScale);
G
gaoyuan 已提交
2017

Z
zhangjinchao01 已提交
2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
  void tanh(Matrix& output);
  void tanhDerivative(Matrix& output);

  void softrelu(Matrix& output);
  void softreluDerivative(Matrix& output);
  void scaledTanh(Matrix& output, real p1, real p2);

  void print(std::ostream& os) const;
  void print(std::ostream& os, size_t height, size_t width) const;
  void printOneRow(std::ostream& os, size_t idx) const;

  void paramReluForward(Matrix& data, Matrix& W);
  void paramReluBackwardW(Matrix& oGrad, Matrix& data);
  void paramReluBackwardDiff(Matrix& oGrad, Matrix& data, Matrix& W);

  void check(std::ostream& os, Matrix& refMat, bool printDiff = true);

  real getMin();
  real getMax();

  void randomizeUniform();

2040
  void classificationError(Matrix& output, IVector& label, size_t topkSize = 1);
Z
zhangjinchao01 已提交
2041 2042 2043

  void addByBitCode(size_t numClasses, const IVector& codes, const Matrix& vec);

2044 2045
  void addByBitCodeBackward(size_t numClasses,
                            const IVector& codes,
Z
zhangjinchao01 已提交
2046 2047
                            Matrix& vec);

2048 2049 2050
  void mulByBitCode(size_t numClasses,
                    const IVector& codes,
                    const Matrix& mat,
Z
zhangjinchao01 已提交
2051 2052
                    const Matrix& input);

2053 2054 2055 2056
  void mulByBitCodeBackwardWeight(size_t numClasses,
                                  const IVector& codes,
                                  Matrix& mat,
                                  const Matrix& input);
Z
zhangjinchao01 已提交
2057

2058 2059 2060 2061
  void mulByBitCodeBackwardError(size_t numClasses,
                                 const IVector& codes,
                                 const Matrix& mat,
                                 Matrix& input);
Z
zhangjinchao01 已提交
2062

2063 2064 2065
  void sumByBitCode(size_t numClasses,
                    IVector& codes,
                    Matrix& sum,
Z
zhangjinchao01 已提交
2066 2067 2068 2069 2070 2071 2072
                    real scaleSum);

  void subByBitCode(size_t numClasses_, IVector& codes);

  void multiBinaryLabelCrossEntropy(Matrix& output, Matrix& label);
  void multiBinaryLabelCrossEntropyBp(Matrix& output, Matrix& label);
  void classificationErrorMulti(Matrix& output, Matrix& label, real threshold);
H
hedaoyuan 已提交
2073

L
liaogang 已提交
2074 2075 2076 2077 2078
  void bilinearForward(const Matrix& in,
                       const size_t inImgH,
                       const size_t inImgW,
                       const size_t outImgH,
                       const size_t outImgW,
L
liaogang 已提交
2079 2080 2081
                       const size_t numChannels,
                       const real ratioH,
                       const real ratioW);
L
liaogang 已提交
2082 2083 2084 2085 2086 2087

  void bilinearBackward(const Matrix& out,
                        const size_t outImgH,
                        const size_t outImgW,
                        const size_t inImgH,
                        const size_t inImgW,
L
liaogang 已提交
2088 2089 2090
                        const size_t numChannels,
                        const real ratioH,
                        const real ratioW);
2091

C
chengduoZH 已提交
2092 2093
  void vol2Col(real* data,
               int channels,
C
chengduoZH 已提交
2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105
               int depth,
               int height,
               int width,
               int filterD,
               int filterH,
               int filterW,
               int strideD,
               int strideH,
               int strideW,
               int paddingD,
               int paddingH,
               int paddingW);
C
chengduoZH 已提交
2106 2107

  void col2Vol(real* trg,
C
chengduoZH 已提交
2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122
               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);
C
chengduoZH 已提交
2123

2124
  template <typename ExpressionType>
H
hedaoyuan 已提交
2125 2126 2127
  void operator=(const ExpressionType& expr) {
    TensorCpuApply<real>(*this, expr);
  }
Z
zhangjinchao01 已提交
2128 2129 2130
};

class SharedCpuMatrix : public CpuMatrix {
W
Wu Yi 已提交
2131
 public:
H
hedaoyuan 已提交
2132
#ifndef PADDLE_MOBILE_INFERENCE
Z
zhangjinchao01 已提交
2133 2134 2135 2136 2137
  /* blockNum is number of partitions of the matrix  */
  SharedCpuMatrix(int blockNum, size_t height, size_t width, bool trans = false)
      : CpuMatrix(height, width, trans) {
    initShared(blockNum);
  }
2138 2139
  SharedCpuMatrix(
      int blockNum, real* data, size_t height, size_t width, bool trans = false)
Z
zhangjinchao01 已提交
2140 2141 2142 2143
      : CpuMatrix(data, height, width, trans) {
    initShared(blockNum);
  }

2144 2145 2146 2147 2148
  SharedCpuMatrix(int blockNum,
                  CpuMemHandlePtr dataHandle,
                  size_t height,
                  size_t width,
                  bool trans = false)
Z
zhangjinchao01 已提交
2149 2150 2151 2152
      : CpuMatrix(dataHandle, height, width, trans) {
    initShared(blockNum);
  }

2153 2154 2155 2156
  SharedCpuMatrix(CpuMemHandlePtr dataHandle,
                  size_t height,
                  size_t width,
                  bool trans = false)
Z
zhangjinchao01 已提交
2157 2158 2159 2160 2161 2162
      : CpuMatrix(dataHandle, height, width, trans) {
    initBlock(1);
  }

  ~SharedCpuMatrix() {}

W
Wu Yi 已提交
2163
 public:
Z
zhangjinchao01 已提交
2164
  virtual void mul(CpuSparseMatrix* a, CpuMatrix* b, real scaleAB, real scaleT);
Y
Yu Yang 已提交
2165 2166
  virtual void add(Matrix& b, real p1, real p2);
  virtual void add(real p1, real p2);
Z
zhangjinchao01 已提交
2167

W
Wu Yi 已提交
2168
 private:
H
hedaoyuan 已提交
2169
  using Matrix::mul;
Z
zhangjinchao01 已提交
2170 2171 2172 2173 2174 2175 2176 2177
  void initShared(int blockNum);
  void initBlock(int blockNum);

  int blockNum_;
  std::vector<std::unique_ptr<std::mutex>> blockLocks_;
  ThreadLocal<CpuMatrixPtr> localBuf_;
  ThreadLocal<std::vector<int>> localBufRows_;
  ThreadLocal<std::vector<int>> blockSeq_;
2178
#endif
Z
zhangjinchao01 已提交
2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
};

typedef struct { unsigned int col; } sparse_non_value_t;

typedef struct {
  unsigned int col;
  float value;
} sparse_float_value_t;

}  // namespace paddle
#include "ExecViaCpu.h"