CpuSparseMatrix.h 10.0 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. */

#pragma once
16 17 18

#ifndef PADDLE_MOBILE_INFERENCE

Z
zhangjinchao01 已提交
19 20 21 22 23 24 25
#include <cstddef>
#include "Matrix.h"

namespace paddle {

class CpuSparseMatrix : public Matrix {
public:
26 27
  CpuSparseMatrix(size_t height,
                  size_t width,
Z
zhangjinchao01 已提交
28 29
                  size_t nnz, /* used to allocate space */
                  SparseValueType valueType = FLOAT_VALUE,
30 31 32 33 34 35 36 37 38
                  SparseFormat format = SPARSE_CSR,
                  bool trans = false);

  CpuSparseMatrix(CpuMemHandlePtr memHandle,
                  size_t height,
                  size_t width,
                  size_t nnz,
                  SparseValueType valueType,
                  SparseFormat format,
Z
zhangjinchao01 已提交
39 40
                  bool trans);

41 42 43 44 45 46 47 48
  CpuSparseMatrix(real* data,
                  int* rows,
                  int* cols,
                  size_t height,
                  size_t width,
                  size_t nnz,
                  SparseValueType valueType,
                  SparseFormat format,
Z
zhangjinchao01 已提交
49 50 51 52
                  bool trans);

  ~CpuSparseMatrix() {}

53 54
  void resize(size_t newHeight,
              size_t newWidth,
Z
zhangjinchao01 已提交
55
              size_t newNnz, /* used to allocate space */
56 57
              SparseValueType valueType,
              SparseFormat format);
Z
zhangjinchao01 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
  void resize(size_t newHeight, size_t newWidth);

  MatrixPtr getTranspose();

  SparseValueType getValueType();

  real* getRowValues(size_t i) const {
    if (format_ == SPARSE_CSR) {
      return value_ + rows_[i];
    } else {
      LOG(FATAL) << "SPARSE_CSC not supported";
      return 0;
    }
  }

  int* getRowCols(size_t i) const {
    if (format_ == SPARSE_CSR) {
      return cols_ + rows_[i];
    } else {
      LOG(FATAL) << "SPARSE_CSC not supported";
      return 0;
    }
  }

  /// fill row indices of each value in CSR matrix
  void fillRowIndices(IVectorPtr& outVec) const;

  size_t getColNum(size_t i) const {
    if (format_ == SPARSE_CSR) {
      return rows_[i + 1] - rows_[i];
    } else {
      LOG(FATAL) << "SPARSE_CSC not supported";
      return 0;
    }
  }

  real* getColumn(size_t i) const {
    if (format_ == SPARSE_CSC) {
      return value_ + cols_[i];
    } else {
      LOG(FATAL) << "SPARSE_CSR not supported";
      return 0;
    }
  }

  size_t getColStartIdx(size_t i) const {
    if (format_ == SPARSE_CSC) {
      return cols_[i];
    } else {
      LOG(FATAL) << "SPARSE_CSR not supported";
      return 0;
    }
  }

  size_t getRowStartIdx(size_t i) const {
    if (format_ == SPARSE_CSR) {
      return rows_[i];
    } else {
      LOG(FATAL) << "SPARSE_CSC not supported";
      return 0;
    }
  }

  size_t getRowNum(size_t i) const {
    if (format_ == SPARSE_CSC) {
      return cols_[i + 1] - cols_[i];
    } else {
      LOG(FATAL) << "SPARSE_CSR not supported";
      return 0;
    }
  }

  virtual real getSum() {
    CHECK(isContiguous());
    if (valueType_ == NO_VALUE) {
      return elementCnt_;
    }
    double sum = 0;
    for (size_t i = 0; i < elementCnt_; ++i) {
      sum += value_[i];
    }
    return sum;
  }

H
hedaoyuan 已提交
142
  virtual void square2() {
Z
zhangjinchao01 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 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
    CHECK(isContiguous());
    if (valueType_ == NO_VALUE) {
      return;
    }
    for (size_t i = 0; i < elementCnt_; ++i) {
      value_[i] = value_[i] * value_[i];
    }
  }

  /**
   * only consider nonzero values.
   * the actual min value should compare with 0.0.
   */
  virtual real getMin() {
    CHECK(isContiguous());
    if (valueType_ == NO_VALUE) {
      return (elementCnt_ > 0 ? 1.0 : 0.0);
    }
    real min = value_[0];
    for (size_t i = 1; i < elementCnt_; ++i) {
      min = value_[i] < min ? value_[i] : min;
    }
    return min;
  }

  /**
   * only consider nonzero values.
   * the actual max value should compare with 0.0.
   */
  virtual real getMax() {
    CHECK(isContiguous());
    if (valueType_ == NO_VALUE) {
      return (elementCnt_ > 0 ? 1.0 : 0.0);
    }
    real max = value_[0];
    for (size_t i = 1; i < elementCnt_; ++i) {
      max = value_[i] > max ? value_[i] : max;
    }
    return max;
  }

  void rowMax(IVector& maxIds, Matrix& maxVal);
  int* getRows() const { return rows_; }
  int* getCols() const { return cols_; }
  real* getValue() const { return value_; }
  SparseFormat getFormat() const { return format_; }
  SparseValueType getValueType() const { return valueType_; }

  /**
   * @brief return value_ of sparse matrix
   *
   * Some times CpuSparseMatrix maybe Matrix,
   * if getValue, must dynamic_cast to CpuSparseMatrix,
   * getData is convenient to get value
   */
  real* getData() { return getValue(); }
199
  const real* getData() const { return getValue(); }
Z
zhangjinchao01 已提交
200 201 202 203 204 205 206

  /**
   * @brief only set value_ of FLOAT_VALUE sparse matrix to zero
   */
  void zeroMem();

  /// mem MUST be alloced outside (memAlloc=false)
207
  void transpose(MatrixPtr& matTrans, bool memAlloc);
Z
zhangjinchao01 已提交
208

209
  void mul(const Matrix& A, const Matrix& B, real alpha, real beta);
Z
zhangjinchao01 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236

  /**
   * @brief sparseMatrix += denseMatrix
   *
   *  Named add3 just because add/add2 has been used in BaseMatrix.cu
   *  and they are not virtual function.
   *
   *  Only add value of same (row, col) index in dense matrix
   *  and do not use others values whoes postions are not in sparse matirx.
   *
   * @param[in]  b   dense matrix
   */
  void add3(CpuMatrix* b);
  void add3(MatrixPtr b);

  /**
   * @brief sparseMatrix[i,j] += bias[j], (j is the col index of sparse matrix)
   *
   * @param[in]  b      bias, dense matrix and height = 1
   * @param[in]  scale  scale of b
   */
  void addBias(Matrix& b, real scale);

  void print(std::ostream& os) const;

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

237 238 239
  void setRow(size_t row,
              size_t colNum,
              const unsigned int* cols,
Z
zhangjinchao01 已提交
240 241
              const real* values);

W
wangmeng28 已提交
242 243 244 245 246 247 248 249 250
  /**
   * @brief this_row = b_row * c_row[cCol]
   *
   * @param[in]  cCol   the column of matrix c used to scale each row of b
   * @param[in]  b      CpuSparseMatrix
   * @param[in]  c      Matrix
   */
  void rowScale(size_t cCol, CpuSparseMatrix& b, Matrix& c);

Z
zhangjinchao01 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
  void randomizeUniform();

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

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

  void copyFrom(const Matrix& src);

  /**
   * Get a temporary matrix. This is threadsafe. It should be only used
   * temporarily, i.e. do not store it or use it as return value.
   *
   * @note  Do NOT use large amount of tmp matrix.
   */
  CpuSparseMatrixPtr getTmpSparseMatrix(size_t height, size_t width);

  virtual MatrixPtr subMatrix(size_t startRow, size_t numRows);

269 270
  void copyFrom(std::vector<int>& rows,
                std::vector<int>& cols,
Z
zhangjinchao01 已提交
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 300 301 302 303 304 305 306 307 308 309 310 311 312 313
                std::vector<real>& values);

  void copyFrom(const CpuMatrix& src);

  void copyFrom(const CpuSparseMatrix& src);

  // trim the large size
  void trimFrom(const CpuSparseMatrix& src);

  void copyRow(int offsets, size_t colNum, const sparse_non_value_t* row);

  void copyRow(int offsets, size_t colNum, const sparse_float_value_t* row);

  template <class T>
  void copyFrom(int64_t* ids, int64_t* indices, T* data);

  template <class T>
  void copyFrom(int64_t* indices, T* data);

  void copyFrom(const real* data, size_t len) {
    LOG(FATAL) << "not supported!";
  }

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

protected:
  void sparseResize();
  /*for csr , record row start position, for csc, record row index for every no
   * zero value*/
  int* rows_;
  /*for csc , record col start position, for csr, record col index for every no
   * zero value*/
  int* cols_;
  real* value_;               /*nonzero value*/
  SparseFormat format_;       /* matrix format */
  SparseValueType valueType_; /*with value or not  */
  static const size_t DEFAULT_AVG_WIDTH = 20;

  static ThreadLocal<std::vector<CpuSparseMatrixPtr>> cpuLocalMats_;

  // BaseMatrixT interface
public:
314
  bool isSparse() const { return true; }
Z
zhangjinchao01 已提交
315 316

private:
H
hedaoyuan 已提交
317
  using Matrix::mul;
Z
zhangjinchao01 已提交
318
  using Matrix::copyFrom;
H
hedaoyuan 已提交
319 320 321
  using Matrix::rowMax;
  using Matrix::print;
  using Matrix::subMatrix;
Z
zhangjinchao01 已提交
322 323
};
}  // namespace paddle
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 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377

#else

#include "Matrix.h"

namespace paddle {

class CpuSparseMatrix : public Matrix {
public:
  CpuSparseMatrix(size_t height,
                  size_t width,
                  size_t nnz, /* used to allocate space */
                  SparseValueType valueType = FLOAT_VALUE,
                  SparseFormat format = SPARSE_CSR,
                  bool trans = false)
      : Matrix(NULL, height, width, trans, false) {}

  CpuSparseMatrix(real* data,
                  int* rows,
                  int* cols,
                  size_t height,
                  size_t width,
                  size_t nnz,
                  SparseValueType valueType,
                  SparseFormat format,
                  bool trans)
      : Matrix(NULL, height, width, trans, false) {}

  real* getValue() const { return nullptr; }
  size_t getColStartIdx(size_t i) const { return 0; }
  size_t getRowStartIdx(size_t i) const { return 0; }
  size_t getColNum(size_t i) const { return 0; }
  int* getRowCols(size_t i) const { return nullptr; }

  CpuSparseMatrixPtr getTmpSparseMatrix(size_t height, size_t width) {
    return nullptr;
  }

  void resize(size_t newHeight,
              size_t newWidth,
              size_t newNnz, /* used to allocate space */
              SparseValueType valueType,
              SparseFormat format) {}
  void resize(size_t newHeight, size_t newWidth) {}
  MatrixPtr getTranspose() { return nullptr; }
  void setRow(size_t row,
              size_t colNum,
              const unsigned int* cols,
              const real* values) {}
};

}  // namespace paddle

#endif