MulOp.cpp 17.5 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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#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, size_t len) {
  for (unsigned int i = 0; i < len; ++i) {
    a[i] += b[i];
  }
}

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

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

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) {
    a[i * aWidth] += b[i * bWidth] * c;
  }
}
}  // namespace
55 56

namespace paddle {
57 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 142 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 199 200 201 202 203 204 205 206 207 208 209 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 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 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 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 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 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
template <>
void MulOp<DEVICE_TYPE_CPU>(CpuSparseMatrix& out,
                            const CpuMatrix& a,
                            const CpuMatrix& b,
                            real scaleAB,
                            real scaleT) {
  /// todo(tianbing), clean the code
  CHECK(!out.isTransposed()) << "Not supported";
  CHECK_EQ(out.getValueType(), FLOAT_VALUE);

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

  if (!a.isTransposed() && !b.isTransposed()) {
    size_t m = a.getWidth();
    CHECK_EQ(b.getHeight(), m);
    CHECK_EQ(a.getHeight(), height);
    CHECK_EQ(b.getWidth(), width);
    if (out.getFormat() == SPARSE_CSC) {
      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[rowIdx * m + k] * B[k * width + i];
          }
          C[j] = scaleAB * sum + scaleT * C[j];
        }
      }
    } else {
      for (size_t i = 0; i < height; i++) {
        size_t start = 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[i * m + k] * B[k * width + colIdx];
          }
          C[j] = scaleAB * sum + scaleT * C[j];
        }
      }
    }
  } else if (a.isTransposed() && !b.isTransposed()) {
    size_t m = a.getHeight();
    CHECK_EQ(m, b.getHeight());
    CHECK_EQ(b.getWidth(), width);
    CHECK_EQ(a.getWidth(), height);

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

template <>
void MulOp<DEVICE_TYPE_CPU>(CpuMatrix& out,
                            const CpuMatrix& a,
                            const CpuMatrix& b,
                            real scaleAB,
                            real scaleT) {
  /// todo(tianbing), clean the code
  CHECK(!out.isTransposed()) << "Not supported";
  CBLAS_TRANSPOSE aTrans = CblasNoTrans;
  size_t aRow = a.getHeight();
  size_t aCol = a.getWidth();
  CBLAS_TRANSPOSE bTrans = CblasNoTrans;
  size_t bRow = b.getHeight();
  size_t bCol = b.getWidth();
  if (a.isTransposed()) {
    aTrans = CblasTrans;
    aRow = a.getWidth();
    aCol = a.getHeight();
  }
  if (b.isTransposed()) {
    bTrans = CblasTrans;
    bRow = b.getWidth();
    bCol = b.getHeight();
  }

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

  const real* A = a.getData();
  const real* B = b.getData();
  real* C = out.getData();

  int M = out.getHeight();
  int N = out.getWidth();
  int K = aCol;
  int lda = a.getStride();
  int ldb = b.getStride();
  int ldc = out.getStride();

  GEMM(aTrans, bTrans, M, N, K, scaleAB, A, lda, B, ldb, scaleT, C, ldc);

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

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

template <>
void MulOp<DEVICE_TYPE_CPU>(CpuMatrix& out,
                            const CpuSparseMatrix& a,
                            const CpuMatrix& b,
                            real scaleAB,
                            real scaleT) {
  /// todo(tianbing), clean the code
  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";

  const real* B = b.getData();
  real* C = out.getData();
  size_t height = out.getHeight();
  size_t width = out.getWidth();
  int* cols = a.getCols();
  real* values = a.getValue();

  if (scaleT == 0) {
    out.zeroMem();
  }

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

    if (a.getValueType() == NO_VALUE) {
      if (width % 32 == 0) {  // use libaddto
        CHECK_EQ((size_t)B % 32, 0UL);
        CHECK_EQ((size_t)C % 32, 0UL);
        auto& colArray = *threadLocalColArray;
        for (size_t i = 0; i < a.getHeight(); ++i) {
          const int start = a.getRowStartIdx(i);
          const int end = a.getRowStartIdx(i + 1);
          size_t colNum = end - start;
          colArray.resize(colNum);
          for (int j = 0; j < end - start; ++j) {
            colArray[j] = const_cast<CpuMatrix&>(b).getRow(cols[j + start]);
          }
          simd::batchAddTo(out.getRow(i), &colArray[0], colNum, width);
        }

      } else {
        for (size_t i = 0; i < a.getHeight(); ++i) {
          const int start = a.getRowStartIdx(i);
          const int end = a.getRowStartIdx(i + 1);
          for (int j = start; j < end; ++j) {
            vecAddTo(out.getRow(i),
                     const_cast<CpuMatrix&>(b).getRow(cols[j]),
                     width);
          }
        }
      }
    } else if (a.getValueType() == FLOAT_VALUE) {
      for (size_t i = 0; i < a.getHeight(); ++i) {
        const int start = a.getRowStartIdx(i);
        const int end = a.getRowStartIdx(i + 1);
        for (int j = start; j < end; ++j) {
          vecAddTo(out.getRow(i),
                   const_cast<CpuMatrix&>(b).getRow(cols[j]),
                   values[j],
                   width);
        }
      }
    }
  } else /*if (a->isTransposed())*/ {
    size_t m = a.getHeight();
    CHECK_EQ(b.getHeight(), m);
    CHECK_EQ(a.getWidth(), height);
    CHECK_EQ(b.getWidth(), width);
    if (a.getValueType() == NO_VALUE) {
      if (width % 32 == 0) {  // use libaddto
        CHECK_EQ((size_t)B % 32, 0UL);
        CHECK_EQ((size_t)C % 32, 0UL);
        for (size_t i = 0; i < a.getHeight(); ++i) {
          const int start = a.getRowStartIdx(i);
          const int end = a.getRowStartIdx(i + 1);
          for (int j = start; j < end; ++j) {
            simd::addTo(out.getRow(cols[j]),
                        const_cast<CpuMatrix&>(b).getRow(i),
                        width);
          }
        }

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

template <>
void MulOp<DEVICE_TYPE_CPU>(CpuMatrix& out,
                            const CpuMatrix& a,
                            const CpuSparseMatrix& b,
                            real scaleAB,
                            real scaleT) {
  /// todo(tianbing), clean the code
  CHECK(!out.trans_) << "Not supported";
  CHECK(!a.isTransposed()) << "Not supported";
  CHECK(scaleT == 0 || scaleT == 1);
  CHECK_EQ(scaleAB, static_cast<real>(1.0));

  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();

  if (scaleT == 0) {
    out.zeroMem();
  }
  /// todo(tianbing), clean the code
  if (b.getFormat() == SPARSE_CSC) {
    if (!b.isTransposed()) {
      size_t m = a.getWidth();
      CHECK_EQ(b.getHeight(), m);
      CHECK_EQ(a.getHeight(), out.height_);
      CHECK_EQ(b.getWidth(), out.width_);

      if (b.getValueType() == NO_VALUE) {
        for (size_t j = 0; j < b.getWidth(); ++j) {
          int start = b.getColStartIdx(j);
          int end = b.getColStartIdx(j + 1);
          for (int i = start; i < end; ++i) {
            colVecAddTo(
                C + j, A + rows[i], out.height_, out.width_, a.getWidth());
          }
        }
      } else if (b.getValueType() == FLOAT_VALUE) {
        for (size_t j = 0; j < b.getWidth(); ++j) {
          int start = b.getColStartIdx(j);
          int end = b.getColStartIdx(j + 1);
          for (int i = start; i < end; ++i) {
            colVecAddTo(C + j,
                        A + rows[i],
                        B[i],
                        out.height_,
                        out.width_,
                        a.getWidth());
          }
        }
      }
    } else /*if (b.isTransposed())*/ {
      size_t m = a.getWidth();
      CHECK_EQ(b.getHeight(), out.width_);
      CHECK_EQ(a.getHeight(), out.height_);
      CHECK_EQ(b.getWidth(), m);
      if (b.getValueType() == NO_VALUE) {
        for (size_t i = 0; i < b.getWidth(); ++i) {
          int start = b.getColStartIdx(i);
          int end = b.getColStartIdx(i + 1);
          for (int j = start; j < end; ++j) {
            colVecAddTo(
                C + rows[j], A + i, out.height_, out.width_, a.getWidth());
          }
        }
      } else if (b.getValueType() == FLOAT_VALUE) {
        for (size_t i = 0; i < b.getWidth(); ++i) {
          int start = b.getColStartIdx(i);
          int end = b.getColStartIdx(i + 1);
          for (int j = start; j < end; ++j) {
            colVecAddTo(C + rows[j],
                        A + i,
                        B[j],
                        out.height_,
                        out.width_,
                        a.getWidth());
          }
        }
      }
    }
  } else {
    if (!b.isTransposed()) {
      size_t m = a.getWidth();
      CHECK_EQ(b.getHeight(), m);
      CHECK_EQ(a.getHeight(), out.height_);
      CHECK_EQ(b.getWidth(), out.width_);

      if (b.getValueType() == NO_VALUE) {
        for (size_t j = 0; j < b.getHeight(); ++j) {
          int start = b.getRowStartIdx(j);
          int end = b.getRowStartIdx(j + 1);
          for (int i = start; i < end; ++i) {
            colVecAddTo(
                C + cols[i], A + j, out.height_, out.width_, a.getWidth());
          }
        }
      } else if (b.getValueType() == FLOAT_VALUE) {
        for (size_t j = 0; j < b.getHeight(); ++j) {
          int start = b.getRowStartIdx(j);
          int end = b.getRowStartIdx(j + 1);
          for (int i = start; i < end; ++i) {
            colVecAddTo(C + cols[i],
                        A + j,
                        B[i],
                        out.height_,
                        out.width_,
                        a.getWidth());
          }
        }
      }
    } else /*if (b.isTransposed())*/ {
      size_t m = a.getWidth();
      CHECK_EQ(b.getHeight(), out.width_);
      CHECK_EQ(a.getHeight(), out.height_);
      CHECK_EQ(b.getWidth(), m);
      if (b.getValueType() == NO_VALUE) {
        for (size_t i = 0; i < b.getHeight(); ++i) {
          int start = b.getRowStartIdx(i);
          int end = b.getRowStartIdx(i + 1);
          for (int j = start; j < end; ++j) {
            colVecAddTo(
                C + i, A + cols[j], out.height_, out.width_, a.getWidth());
          }
        }
      } else if (b.getValueType() == FLOAT_VALUE) {
        for (size_t i = 0; i < b.getHeight(); ++i) {
          int start = b.getRowStartIdx(i);
          int end = b.getRowStartIdx(i + 1);
          for (int j = start; j < end; ++j) {
            colVecAddTo(C + i,
                        A + cols[j],
                        B[j],
                        out.height_,
                        out.width_,
                        a.getWidth());
          }
        }
      }
    }
  }
}
475 476 477 478 479

/**
 * mul operator
 * out = scaleT * out + scaleAB*(in1 * in2)
 *
480 481 482
 * \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)
483 484 485 486 487
 */
template <DeviceType Device>
class MulFunc : public FunctionBase {
public:
  void init(const FuncConfig& config) override {
488 489
    alpha_ = config.get<real>("scaleAB");
    beta_ = config.get<real>("scaleT");
490 491 492
  }

  void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
493 494
    CHECK_EQ((size_t)2, inputs.size());
    CHECK_EQ((size_t)1, outputs.size());
495 496 497 498
    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);
499
    CHECK_EQ(outputs[0].getArgType(), ADD_TO);
500

501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
    /// todo(tianbing), support SparseMatrixArg for out_mat
    auto out_mat = outputs[0].matrix<Device>();
    LOG(INFO) << "out_mat:";
    out_mat.print(std::cout);
    if (!inputs[0].isSparseArg() && !inputs[1].isSparseArg()) {
      LOG(INFO) << "in1_mat:";
      inputs[0].matrix<Device>().print(std::cout);
      LOG(INFO) << "in2_mat:";
      inputs[1].matrix<Device>().print(std::cout);
      MulOp<Device>(out_mat,
                    inputs[0].matrix<Device>(),
                    inputs[1].matrix<Device>(),
                    alpha_,
                    beta_);
      return;
516
    }
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541

    if (!inputs[0].isSparseArg() && inputs[1].isSparseArg()) {
      LOG(INFO) << "in1_mat:";
      inputs[0].matrix<Device>().print(std::cout);
      LOG(INFO) << "in2_mat:";
      inputs[1].sparse().SparseMatrix<Device>().print(std::cout);
      MulOp<Device>(out_mat,
                    inputs[0].matrix<Device>(),
                    inputs[1].sparse().SparseMatrix<Device>(),
                    alpha_,
                    beta_);
      return;
    }

    if (inputs[0].isSparseArg() && !inputs[1].isSparseArg()) {
      LOG(INFO) << "in1_mat:";
      inputs[0].sparse().SparseMatrix<Device>().print(std::cout);
      LOG(INFO) << "in2_mat:";
      inputs[1].matrix<Device>().print(std::cout);
      MulOp<Device>(out_mat,
                    inputs[0].sparse().SparseMatrix<Device>(),
                    inputs[1].matrix<Device>(),
                    alpha_,
                    beta_);
      return;
542
    }
543 544 545
  }

private:
546 547
  real alpha_;
  real beta_;
548 549
};

550
REGISTER_TYPED_FUNC(MulOp, CPU, MulFunc);
551 552 553 554
#ifndef PADDLE_ONLY_CPU
REGISTER_TYPED_FUNC(MulOp, GPU, MulFunc);
#endif
}  // namespace paddle