MulOp.cpp 11.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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

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

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

#include "MulOp.h"
16 17
/// todo(tianbing), delete it
#include <iostream>
18 19 20 21 22 23 24 25 26 27 28 29 30
#include "paddle/math/MathFunctions.h"
#include "paddle/math/SIMDFunctions.h"
#include "paddle/utils/ThreadLocal.h"

#ifndef PADDLE_TYPE_DOUBLE
#define GEMM paddle::gemm<float>
#else
#define GEMM paddle::gemm<double>
#endif

namespace {
inline void vecAddTo(real* a, const real* b, real scaleB, size_t len) {
  for (unsigned int i = 0; i < len; ++i) {
X
xutianbing 已提交
31
    a[i] += (1.0 == scaleB) ? b[i] : scaleB * b[i];
32 33 34 35 36 37
  }
}

inline void colVecAddTo(
    real* a, real* b, real c, size_t len, size_t aWidth, size_t bWidth) {
  for (unsigned int i = 0; i < len; ++i) {
X
xutianbing 已提交
38
    a[i * aWidth] += (1.0 == c) ? b[i * bWidth] : b[i * bWidth] * c;
39 40 41
  }
}
}  // namespace
42 43

namespace paddle {
44 45 46 47 48 49 50 51
template <>
void MulOp<DEVICE_TYPE_CPU>(CpuSparseMatrix& out,
                            const CpuMatrix& a,
                            const CpuMatrix& b,
                            real scaleAB,
                            real scaleT) {
  CHECK(!out.isTransposed()) << "Not supported";
  CHECK_EQ(out.getValueType(), FLOAT_VALUE);
X
xutianbing 已提交
52 53
  CHECK(!a.isTransposed() || !b.isTransposed())
      << "Not support both a and b are transpose matrices";
X
xutianbing 已提交
54 55 56 57 58 59 60 61 62

  size_t height = out.getHeight();
  size_t width = out.getWidth();
  size_t aRow = !a.isTransposed() ? a.getHeight() : a.getWidth();
  size_t aCol = !a.isTransposed() ? a.getWidth() : a.getHeight();
  size_t bRow = !b.isTransposed() ? b.getHeight() : b.getWidth();
  size_t bCol = !b.isTransposed() ? b.getWidth() : b.getHeight();
  /// C = A * B, for matrix format
  CHECK(aCol == bRow && aRow == height && bCol == width);
63

X
xutianbing 已提交
64 65 66
  if (scaleT == 0) {
    out.zeroMem();
  }
67 68 69 70 71 72
  const real* A = a.getData();
  const real* B = b.getData();
  real* C = out.getValue();
  int* rows = out.getRows();
  int* cols = out.getCols();

X
xutianbing 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
  /// SPARSE_CSC, {a any, b not trans}
  if (out.getFormat() == SPARSE_CSC) {
    /// b not trans and a any
    CHECK(!b.isTransposed());
    size_t m = !a.isTransposed() ? a.getWidth() : a.getHeight();
    for (size_t i = 0; i < width; i++) {
      size_t start = out.getColStartIdx(i);
      size_t end = out.getColStartIdx(i + 1);
      for (size_t j = start; j < end; j++) {
        real sum = 0;
        size_t rowIdx = rows[j];
        for (size_t k = 0; k < m; k++) {
          sum +=
              (!a.isTransposed() ? A[rowIdx * m + k] : A[k * height + rowIdx]) *
              B[k * width + i];
88
        }
X
xutianbing 已提交
89
        C[j] = scaleAB * sum + scaleT * C[j];
90 91
      }
    }
X
xutianbing 已提交
92 93 94
    return;
  }

X
xutianbing 已提交
95 96 97 98
  /// SPARSE_CSR, {a any, b not trans} or {a not trans, b trans}
  if (out.getFormat() == SPARSE_CSR) {
    /// a and b can not both transpose
    CHECK(!(a.isTransposed() && b.isTransposed()));
99
    size_t m = a.getWidth();
X
xutianbing 已提交
100 101 102 103 104 105 106 107 108 109
    for (size_t i = 0; i < height; i++) {
      size_t start = out.getRowStartIdx(i);
      size_t end = out.getRowStartIdx(i + 1);
      for (size_t j = start; j < end; j++) {
        real sum = 0;
        size_t colIdx = cols[j];
        for (size_t k = 0; k < m; k++) {
          sum +=
              (!a.isTransposed() ? A[i * m + k] : A[k * height + i]) *
              (!b.isTransposed() ? B[k * width + colIdx] : B[colIdx * m + k]);
110
        }
X
xutianbing 已提交
111
        C[j] = scaleAB * sum + scaleT * C[j];
112 113
      }
    }
X
xutianbing 已提交
114
    return;
115 116 117 118 119 120 121 122 123
  }
}

template <>
void MulOp<DEVICE_TYPE_CPU>(CpuMatrix& out,
                            const CpuMatrix& a,
                            const CpuMatrix& b,
                            real scaleAB,
                            real scaleT) {
X
xutianbing 已提交
124 125 126 127 128 129 130
  CHECK(!out.isTransposed()) << "out matrix transpose not supported";
  CBLAS_TRANSPOSE aTrans = a.isTransposed() ? CblasTrans : CblasNoTrans;
  size_t aRow = a.isTransposed() ? a.getWidth() : a.getHeight();
  size_t aCol = a.isTransposed() ? a.getHeight() : a.getWidth();
  CBLAS_TRANSPOSE bTrans = b.isTransposed() ? CblasTrans : CblasNoTrans;
  size_t bRow = b.isTransposed() ? b.getWidth() : b.getHeight();
  size_t bCol = b.isTransposed() ? b.getHeight() : b.getWidth();
131 132 133 134 135 136

  /// C = A * B, for matrix format
  CHECK_EQ(aCol, bRow);
  CHECK_EQ(aRow, out.getHeight());
  CHECK_EQ(bCol, out.getWidth());

X
xutianbing 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149
  GEMM(aTrans,
       bTrans,
       out.getHeight(),
       out.getWidth(),
       aCol,
       scaleAB,
       a.getData(),
       a.getStride(),
       b.getData(),
       b.getStride(),
       scaleT,
       out.getData(),
       out.getStride());
150 151 152 153 154 155 156 157 158 159 160 161 162 163
}

template <>
void MulOp<DEVICE_TYPE_CPU>(CpuMatrix& out,
                            const CpuSparseMatrix& a,
                            const CpuMatrix& b,
                            real scaleAB,
                            real scaleT) {
  CHECK(!out.isTransposed()) << "Not supported";
  CHECK(!b.isTransposed()) << "Not supported";
  CHECK(scaleT == 0 || scaleT == 1) << "Not support";
  CHECK_EQ(scaleAB, static_cast<real>(1.0)) << "Not supported";
  CHECK_EQ(a.getFormat(), SPARSE_CSR) << "Not supported";

X
xutianbing 已提交
164 165 166 167 168 169 170
  if (!a.isTransposed()) {
    CHECK(b.getHeight() == a.getWidth() && a.getHeight() == out.getHeight() &&
          b.getWidth() == out.getWidth());
  } else {
    CHECK(b.getHeight() == a.getHeight() && a.getWidth() == out.getHeight() &&
          b.getWidth() == out.getWidth());
  }
171 172 173 174

  if (scaleT == 0) {
    out.zeroMem();
  }
X
xutianbing 已提交
175 176 177 178 179 180
  const real* B = b.getData();
  real* C = out.getData();
  if (out.getWidth() % 32 == 0) {
    CHECK_EQ((size_t)B % 32, 0UL);
    CHECK_EQ((size_t)C % 32, 0UL);
  }
181

X
xutianbing 已提交
182 183 184 185 186 187 188 189 190 191 192
  int* cols = a.getCols();
  real* values = a.getValue();
  for (size_t i = 0; i < a.getHeight(); ++i) {
    const int start = a.getRowStartIdx(i);
    const int end = a.getRowStartIdx(i + 1);
    for (int j = start; j < end; ++j) {
      vecAddTo(!a.isTransposed() ? out.getRow(i) : out.getRow(cols[j]),
               !a.isTransposed() ? const_cast<CpuMatrix&>(b).getRow(cols[j])
                                 : const_cast<CpuMatrix&>(b).getRow(i),
               (a.getValueType() == FLOAT_VALUE) ? values[j] : (real)1.0,
               out.getWidth());
193 194 195 196 197 198 199 200 201 202 203 204 205 206
    }
  }
}

template <>
void MulOp<DEVICE_TYPE_CPU>(CpuMatrix& out,
                            const CpuMatrix& a,
                            const CpuSparseMatrix& b,
                            real scaleAB,
                            real scaleT) {
  CHECK(!out.trans_) << "Not supported";
  CHECK(!a.isTransposed()) << "Not supported";
  CHECK(scaleT == 0 || scaleT == 1);
  CHECK_EQ(scaleAB, static_cast<real>(1.0));
X
xutianbing 已提交
207 208 209 210 211 212 213
  if (!b.isTransposed()) {  /// b is not Transpose
    CHECK(b.getHeight() == a.getWidth() && a.getHeight() == out.getHeight() &&
          b.getWidth() == out.getWidth());
  } else {
    CHECK(b.getHeight() == out.getWidth() && a.getHeight() == out.getHeight() &&
          b.getWidth() == a.getWidth());
  }
214

X
xutianbing 已提交
215 216 217
  if (scaleT == 0) {
    out.zeroMem();
  }
218 219 220 221 222 223
  real* A = const_cast<real*>(a.getData());
  real* B = const_cast<real*>(b.getValue());
  real* C = out.getData();
  int* rows = b.getRows();
  int* cols = b.getCols();

X
xutianbing 已提交
224
  /// b.getFormat() == SPARSE_CSC
225
  if (b.getFormat() == SPARSE_CSC) {
X
xutianbing 已提交
226 227 228 229 230 231 232 233 234 235
    for (size_t j = 0; j < b.getWidth(); ++j) {
      int start = b.getColStartIdx(j);
      int end = b.getColStartIdx(j + 1);
      for (int i = start; i < end; ++i) {
        colVecAddTo(!b.isTransposed() ? C + j : C + rows[i],
                    !b.isTransposed() ? A + rows[i] : A + j,
                    (b.getValueType() == NO_VALUE) ? (real)1.0 : B[i],
                    out.getHeight(),
                    out.getWidth(),
                    a.getWidth());
236 237
      }
    }
X
xutianbing 已提交
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
    return;
  }

  /// b.getFormat() == SPARSE_CSR
  if (b.getFormat() == SPARSE_CSR) {
    for (size_t j = 0; j < b.getHeight(); ++j) {
      int start = b.getRowStartIdx(j);
      int end = b.getRowStartIdx(j + 1);
      for (int i = start; i < end; ++i) {
        colVecAddTo(!b.isTransposed() ? C + cols[i] : C + j,
                    !b.isTransposed() ? A + j : A + cols[i],
                    (b.getValueType() == NO_VALUE) ? (real)1.0 : B[i],
                    out.getHeight(),
                    out.getWidth(),
                    a.getWidth());
253 254
      }
    }
X
xutianbing 已提交
255
    return;
256 257
  }
}
258 259 260 261 262

/**
 * mul operator
 * out = scaleT * out + scaleAB*(in1 * in2)
 *
263 264 265
 * \param outputs[0]      output matrix, M * N
 * \param inputs[0]       first input (sparse) matrix,  M * K (if non-trans)
 * \param inputs[1]       second input matrix, K * N (if non-trans)
266 267 268 269 270
 */
template <DeviceType Device>
class MulFunc : public FunctionBase {
public:
  void init(const FuncConfig& config) override {
271 272
    alpha_ = config.get<real>("scaleAB");
    beta_ = config.get<real>("scaleT");
273 274 275
  }

  void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
276 277
    CHECK_EQ((size_t)2, inputs.size());
    CHECK_EQ((size_t)1, outputs.size());
278 279 280 281
    CHECK(inputs[0].data() && inputs[1].data() && outputs[0].data());
    CHECK_EQ(inputs[0].shape().ndims(), (size_t)2);
    CHECK_EQ(inputs[1].shape().ndims(), (size_t)2);
    CHECK_EQ(outputs[0].shape().ndims(), (size_t)2);
282
    CHECK_EQ(outputs[0].getArgType(), ADD_TO);
283

X
xutianbing 已提交
284
    auto outMat = outputs[0].matrix<Device>();
285 286 287
    /// matrix = matrix * matrix
    if (!inputs[0].isSparseArg() && !inputs[1].isSparseArg() &&
        !outputs[0].isSparseArg()) {
X
xutianbing 已提交
288
      MulOp<Device>(outMat,
289 290 291 292 293
                    inputs[0].matrix<Device>(),
                    inputs[1].matrix<Device>(),
                    alpha_,
                    beta_);
      return;
294
    }
295

296 297 298
    /// matrix = matrix * sparse matrix
    if (!inputs[0].isSparseArg() && inputs[1].isSparseArg() &&
        !outputs[0].isSparseArg()) {
X
xutianbing 已提交
299
      MulOp<Device>(outMat,
300 301 302 303 304 305 306
                    inputs[0].matrix<Device>(),
                    inputs[1].sparse().SparseMatrix<Device>(),
                    alpha_,
                    beta_);
      return;
    }

307 308 309
    /// matrix = sparse matrix * matrix
    if (inputs[0].isSparseArg() && !inputs[1].isSparseArg() &&
        !outputs[0].isSparseArg()) {
X
xutianbing 已提交
310
      MulOp<Device>(outMat,
311 312 313 314 315
                    inputs[0].sparse().SparseMatrix<Device>(),
                    inputs[1].matrix<Device>(),
                    alpha_,
                    beta_);
      return;
316
    }
317 318

    /// sparse matrix = matrix * matrix
X
xutianbing 已提交
319
    auto outSparseMat = outputs[0].sparse().SparseMatrix<Device>();
320 321
    if (!inputs[0].isSparseArg() && !inputs[1].isSparseArg() &&
        outputs[0].isSparseArg()) {
322 323 324 325 326 327 328
      /*
      LOG(INFO) << "input0";
      inputs[0].matrix<Device>().print(std::cout);
      LOG(INFO) << "input1";
      inputs[1].matrix<Device>().print(std::cout);
      LOG(INFO) << "output sparse matrix";
      outSparseMat.print(std::cout); */
X
xutianbing 已提交
329
      MulOp<Device>(outSparseMat,
330 331 332 333 334 335
                    inputs[0].matrix<Device>(),
                    inputs[1].matrix<Device>(),
                    alpha_,
                    beta_);
      return;
    }
336 337 338
  }

private:
339 340
  real alpha_;
  real beta_;
341 342
};

343
REGISTER_TYPED_FUNC(MulOp, CPU, MulFunc);
344 345 346 347
#ifndef PADDLE_ONLY_CPU
REGISTER_TYPED_FUNC(MulOp, GPU, MulFunc);
#endif
}  // namespace paddle