blas_impl.h 28.6 KB
Newer Older
Y
Yu Yang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
//   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// 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
T
tensor-tang 已提交
15
#include <cmath>
T
tensor-tang 已提交
16
#include <limits>
Y
Yu Yang 已提交
17
#include <vector>
Y
Yu Yang 已提交
18 19 20 21 22 23 24 25 26
#include "paddle/fluid/operators/math/math_function.h"

namespace paddle {
namespace operators {
namespace math {

template <typename T>
struct CBlas;

27 28 29 30 31 32 33 34
template <>
struct CBlas<int8_t> {
  template <typename... ARGS>
  static void VCOPY(ARGS... args) {
    PADDLE_THROW("Blas VCOPY don't support int8_t");
  }
};

35
#ifdef PADDLE_WITH_MKLML
Y
Yu Yang 已提交
36 37
template <>
struct CBlas<float> {
Y
Yu Yang 已提交
38 39
  template <typename... ARGS>
  static void GEMM(ARGS... args) {
40
    platform::dynload::cblas_sgemm(args...);
Y
Yu Yang 已提交
41
  }
Y
Yu Yang 已提交
42

T
tensor-tang 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
  template <typename... ARGS>
  static float *GEMM_ALLOC(ARGS... args) {
    return platform::dynload::cblas_sgemm_alloc(args...);
  }

  template <typename... ARGS>
  static void GEMM_PACK(ARGS... args) {
    platform::dynload::cblas_sgemm_pack(args...);
  }

  template <typename... ARGS>
  static void GEMM_COMPUTE(ARGS... args) {
    platform::dynload::cblas_sgemm_compute(args...);
  }

  template <typename... ARGS>
  static void GEMM_FREE(ARGS... args) {
    platform::dynload::cblas_sgemm_free(args...);
  }

T
tensor-tang 已提交
63 64 65 66 67 68
#ifdef PADDLE_WITH_LIBXSMM
  template <typename... ARGS>
  static void SMM_GEMM(ARGS... args) {
    libxsmm_sgemm(args...);
  }
#endif
T
tensor-tang 已提交
69

Y
Yu Yang 已提交
70 71
  template <typename... ARGS>
  static void AXPY(ARGS... args) {
72 73 74 75 76 77 78 79 80 81 82 83 84
    platform::dynload::cblas_saxpy(args...);
  }

  template <typename... ARGS>
  static void VCOPY(ARGS... args) {
    platform::dynload::cblas_scopy(args...);
  }

  template <typename... ARGS>
  static void GEMV(ARGS... args) {
    platform::dynload::cblas_sgemv(args...);
  }

T
tensor-tang 已提交
85 86 87 88 89
  template <typename... ARGS>
  static float DOT(ARGS... args) {
    return platform::dynload::cblas_sdot(args...);
  }

T
tensor-tang 已提交
90 91 92 93 94
  template <typename... ARGS>
  static void SCAL(ARGS... args) {
    platform::dynload::cblas_sscal(args...);
  }

J
Jacek Czaja 已提交
95 96 97 98 99
  template <typename... ARGS>
  static float ASUM(ARGS... args) {
    return platform::dynload::cblas_sasum(args...);
  }

100 101 102
  template <typename... ARGS>
  static void GEMM_BATCH(ARGS... args) {
    platform::dynload::cblas_sgemm_batch(args...);
Y
Yu Yang 已提交
103 104
  }

105 106
  template <typename... ARGS>
  static void VADD(ARGS... args) {
107 108
    platform::dynload::vsAdd(args...);
  }
T
tensor-tang 已提交
109

110 111 112 113 114
  template <typename... ARGS>
  static void VSUB(ARGS... args) {
    platform::dynload::vsSub(args...);
  }

T
tensor-tang 已提交
115 116 117 118
  template <typename... ARGS>
  static void VMUL(ARGS... args) {
    platform::dynload::vsMul(args...);
  }
T
tensor-tang 已提交
119

120 121 122 123 124
  template <typename... ARGS>
  static void VDIV(ARGS... args) {
    platform::dynload::vsDiv(args...);
  }

T
tensor-tang 已提交
125 126 127 128
  template <typename... ARGS>
  static void VEXP(ARGS... args) {
    platform::dynload::vsExp(args...);
  }
T
tensor-tang 已提交
129 130

  template <typename... ARGS>
T
tensor-tang 已提交
131
  static void VSQUARE(ARGS... args) {
T
tensor-tang 已提交
132 133 134 135 136 137 138
    platform::dynload::vsSqr(args...);
  }

  template <typename... ARGS>
  static void VPOW(ARGS... args) {
    platform::dynload::vsPowx(args...);
  }
Y
Use mkl  
Yu Yang 已提交
139 140 141 142 143

  template <typename... ARGS>
  static void VINV(ARGS... args) {
    platform::dynload::vsInv(args...);
  }
Y
Yihua Xu 已提交
144 145 146 147 148

  template <typename... ARGS>
  static void VMERF(ARGS... args) {
    platform::dynload::vmsErf(args...);
  }
149
#if !defined(_WIN32)
150 151 152 153
  template <typename... ARGS>
  static void CSRMM(ARGS... args) {
    platform::dynload::mkl_scsrmm(args...);
  }
154
#endif
G
Guo Sheng 已提交
155 156 157 158 159

  template <typename... ARGS>
  static void TRSM(ARGS... args) {
    platform::dynload::cblas_strsm(args...);
  }
160 161 162 163 164 165 166 167 168
};

template <>
struct CBlas<double> {
  template <typename... ARGS>
  static void GEMM(ARGS... args) {
    platform::dynload::cblas_dgemm(args...);
  }

T
tensor-tang 已提交
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
  template <typename... ARGS>
  static double *GEMM_ALLOC(ARGS... args) {
    return platform::dynload::cblas_dgemm_alloc(args...);
  }

  template <typename... ARGS>
  static void GEMM_PACK(ARGS... args) {
    platform::dynload::cblas_dgemm_pack(args...);
  }

  template <typename... ARGS>
  static void GEMM_COMPUTE(ARGS... args) {
    platform::dynload::cblas_dgemm_compute(args...);
  }

  template <typename... ARGS>
  static void GEMM_FREE(ARGS... args) {
    platform::dynload::cblas_dgemm_free(args...);
  }

T
tensor-tang 已提交
189 190 191 192 193 194
#ifdef PADDLE_WITH_LIBXSMM
  template <typename... ARGS>
  static void SMM_GEMM(ARGS... args) {
    libxsmm_dgemm(args...);
  }
#endif
T
tensor-tang 已提交
195

196 197 198
  template <typename... ARGS>
  static void AXPY(ARGS... args) {
    platform::dynload::cblas_daxpy(args...);
199 200 201 202
  }

  template <typename... ARGS>
  static void VCOPY(ARGS... args) {
203
    platform::dynload::cblas_dcopy(args...);
204 205
  }

Y
Yu Yang 已提交
206 207
  template <typename... ARGS>
  static void GEMV(ARGS... args) {
208
    platform::dynload::cblas_dgemv(args...);
Y
Yu Yang 已提交
209 210
  }

T
tensor-tang 已提交
211 212 213 214 215
  template <typename... ARGS>
  static double DOT(ARGS... args) {
    return platform::dynload::cblas_ddot(args...);
  }

T
tensor-tang 已提交
216 217 218 219 220
  template <typename... ARGS>
  static void SCAL(ARGS... args) {
    platform::dynload::cblas_dscal(args...);
  }

J
Jacek Czaja 已提交
221 222 223 224 225
  template <typename... ARGS>
  static double ASUM(ARGS... args) {
    return platform::dynload::cblas_dasum(args...);
  }

Y
Yu Yang 已提交
226 227
  template <typename... ARGS>
  static void GEMM_BATCH(ARGS... args) {
228 229 230 231 232 233 234
    platform::dynload::cblas_dgemm_batch(args...);
  }

  template <typename... ARGS>
  static void VADD(ARGS... args) {
    platform::dynload::vdAdd(args...);
  }
T
tensor-tang 已提交
235

236 237 238 239 240
  template <typename... ARGS>
  static void VSUB(ARGS... args) {
    platform::dynload::vdSub(args...);
  }

T
tensor-tang 已提交
241 242 243 244
  template <typename... ARGS>
  static void VMUL(ARGS... args) {
    platform::dynload::vdMul(args...);
  }
T
tensor-tang 已提交
245

246 247 248 249 250
  template <typename... ARGS>
  static void VDIV(ARGS... args) {
    platform::dynload::vdDiv(args...);
  }

T
tensor-tang 已提交
251 252 253 254
  template <typename... ARGS>
  static void VEXP(ARGS... args) {
    platform::dynload::vdExp(args...);
  }
T
tensor-tang 已提交
255 256

  template <typename... ARGS>
T
tensor-tang 已提交
257
  static void VSQUARE(ARGS... args) {
T
tensor-tang 已提交
258 259 260 261 262 263 264
    platform::dynload::vdSqr(args...);
  }

  template <typename... ARGS>
  static void VPOW(ARGS... args) {
    platform::dynload::vdPowx(args...);
  }
Y
Use mkl  
Yu Yang 已提交
265 266 267 268 269

  template <typename... ARGS>
  static void VINV(ARGS... args) {
    platform::dynload::vdInv(args...);
  }
Y
Yihua Xu 已提交
270 271 272 273 274

  template <typename... ARGS>
  static void VMERF(ARGS... args) {
    platform::dynload::vmdErf(args...);
  }
275
#if !defined(_WIN32)
276 277 278 279
  template <typename... ARGS>
  static void CSRMM(ARGS... args) {
    platform::dynload::mkl_dcsrmm(args...);
  }
280
#endif
G
Guo Sheng 已提交
281 282 283 284 285

  template <typename... ARGS>
  static void TRSM(ARGS... args) {
    platform::dynload::cblas_dtrsm(args...);
  }
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
};

#else

template <>
struct CBlas<float> {
  template <typename... ARGS>
  static void GEMM(ARGS... args) {
    cblas_sgemm(args...);
  }

  template <typename... ARGS>
  static void AXPY(ARGS... args) {
    cblas_saxpy(args...);
  }

  template <typename... ARGS>
  static void VCOPY(ARGS... args) {
    cblas_scopy(args...);
  }

  template <typename... ARGS>
  static void GEMV(ARGS... args) {
    cblas_sgemv(args...);
Y
Yu Yang 已提交
310
  }
G
Guo Sheng 已提交
311 312 313 314 315

  template <typename... ARGS>
  static void TRSM(ARGS... args) {
    cblas_strsm(args...);
  }
Y
Yu Yang 已提交
316 317 318 319
};

template <>
struct CBlas<double> {
Y
Yu Yang 已提交
320 321 322 323
  template <typename... ARGS>
  static void GEMM(ARGS... args) {
    cblas_dgemm(args...);
  }
Y
Yu Yang 已提交
324 325 326 327 328 329

  template <typename... ARGS>
  static void AXPY(ARGS... args) {
    cblas_daxpy(args...);
  }

330 331 332 333 334
  template <typename... ARGS>
  static void VCOPY(ARGS... args) {
    cblas_dcopy(args...);
  }

Y
Yu Yang 已提交
335 336 337 338
  template <typename... ARGS>
  static void GEMV(ARGS... args) {
    cblas_dgemv(args...);
  }
G
Guo Sheng 已提交
339 340 341 342 343

  template <typename... ARGS>
  static void TRSM(ARGS... args) {
    cblas_dtrsm(args...);
  }
Y
Yu Yang 已提交
344
};
345
#endif
T
tensor-tang 已提交
346

Y
Yu Yang 已提交
347 348
template <>
struct CBlas<platform::float16> {
Y
Yu Yang 已提交
349
  static void GEMM(...) { PADDLE_THROW("float16 GEMM not supported on CPU"); }
T
tensor-tang 已提交
350 351 352
  static void SMM_GEMM(...) {
    PADDLE_THROW("float16 SMM_GEMM not supported on CPU");
  }
T
tensor-tang 已提交
353
  static void VMUL(...) { PADDLE_THROW("float16 VMUL not supported on CPU"); }
T
tensor-tang 已提交
354
  static void VEXP(...) { PADDLE_THROW("float16 VEXP not supported on CPU"); }
T
tensor-tang 已提交
355 356 357
  static void VSQUARE(...) {
    PADDLE_THROW("float16 VSQUARE not supported on CPU");
  }
T
tensor-tang 已提交
358
  static void VPOW(...) { PADDLE_THROW("float16 VPOW not supported on CPU"); }
T
tensor-tang 已提交
359
  static void DOT(...) { PADDLE_THROW("float16 DOT not supported on CPU"); };
T
tensor-tang 已提交
360
  static void SCAL(...) { PADDLE_THROW("float16 SCAL not supported on CPU"); };
J
Jacek Czaja 已提交
361
  static void ASUM(...) { PADDLE_THROW("float16 ASUM not supported on CPU"); };
Y
Yu Yang 已提交
362 363 364 365 366
#ifdef PADDLE_WITH_MKLML
  static void GEMM_BATCH(...) {
    PADDLE_THROW("float16 GEMM_BATCH not supported on CPU");
  }
#endif
Y
Yu Yang 已提交
367
};
T
tensor-tang 已提交
368

T
tensor-tang 已提交
369
#ifdef PADDLE_WITH_MKLML
T
tensor-tang 已提交
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
template <>
template <typename T>
T *Blas<platform::CPUDeviceContext>::GEMM_ALLOC(const CBLAS_IDENTIFIER id,
                                                const int M, const int N,
                                                const int K) const {
  return CBlas<T>::GEMM_ALLOC(id, M, N, K);
}

template <>
template <typename T>
void Blas<platform::CPUDeviceContext>::GEMM_PACK(const CBLAS_IDENTIFIER id,
                                                 const CBLAS_TRANSPOSE trans,
                                                 int M, int N, int K,
                                                 const T alpha, const T *src,
                                                 const int ld, T *dst) const {
  CBlas<T>::GEMM_PACK(CblasRowMajor, id, trans, M, N, K, alpha, src, ld, dst);
}

template <>
template <typename T>
void Blas<platform::CPUDeviceContext>::GEMM_COMPUTE(
    int transA, int transB, int M, int N, int K, const T *A, const int lda,
    const T *B, const int ldb, T beta, T *C, const int ldc) const {
  CBlas<T>::GEMM_COMPUTE(CblasRowMajor, transA, transB, M, N, K, A, lda, B, ldb,
                         beta, C, ldc);
}

template <>
template <typename T>
void Blas<platform::CPUDeviceContext>::GEMM_FREE(T *data) const {
  CBlas<T>::GEMM_FREE(data);
}
T
tensor-tang 已提交
402
#endif
T
tensor-tang 已提交
403

T
tensor-tang 已提交
404 405 406 407 408 409 410 411 412
template <>
template <typename T>
void Blas<platform::CPUDeviceContext>::GEMM(CBLAS_TRANSPOSE transA,
                                            CBLAS_TRANSPOSE transB, int M,
                                            int N, int K, T alpha, const T *A,
                                            const T *B, T beta, T *C) const {
  int lda = (transA == CblasNoTrans) ? K : M;
  int ldb = (transB == CblasNoTrans) ? N : K;
  int ldc = N;
T
tensor-tang 已提交
413 414
  CBlas<T>::GEMM(CblasRowMajor, transA, transB, M, N, K, alpha, A, lda, B, ldb,
                 beta, C, ldc);
Y
Yu Yang 已提交
415 416 417 418
}

template <>
template <typename T>
Y
Yu Yang 已提交
419 420 421 422
void Blas<platform::CPUDeviceContext>::GEMM(bool transA, bool transB, int M,
                                            int N, int K, T alpha, const T *A,
                                            int lda, const T *B, int ldb,
                                            T beta, T *C, int ldc) const {
T
tensor-tang 已提交
423 424 425 426 427 428 429 430 431 432 433 434 435 436
  CBlas<T>::GEMM(CblasRowMajor, transA == false ? CblasNoTrans : CblasTrans,
                 transB == false ? CblasNoTrans : CblasTrans, M, N, K, alpha, A,
                 lda, B, ldb, beta, C, ldc);
}

template <>
template <typename T>
void Blas<platform::CPUDeviceContext>::GEMM(CBLAS_TRANSPOSE transA,
                                            CBLAS_TRANSPOSE transB, int M,
                                            int N, int K, T alpha, const T *A,
                                            int lda, const T *B, int ldb,
                                            T beta, T *C, int ldc) const {
  CBlas<T>::GEMM(CblasRowMajor, transA, transB, M, N, K, alpha, A, lda, B, ldb,
                 beta, C, ldc);
Y
Yu Yang 已提交
437 438
}

Y
Yu Yang 已提交
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
template <typename DeviceContext>
template <typename T>
void Blas<DeviceContext>::MatMul(const framework::Tensor &mat_a, bool trans_a,
                                 const framework::Tensor &mat_b, bool trans_b,
                                 T alpha, framework::Tensor *mat_out,
                                 T beta) const {
  auto dim_a = mat_a.dims();
  auto dim_b = mat_b.dims();
  auto dim_out = mat_out->dims();
  PADDLE_ENFORCE(dim_a.size() == 2 && dim_b.size() == 2 && dim_out.size() == 2,
                 "The input and output of matmul be matrix");
  PADDLE_ENFORCE(
      mat_a.place() == mat_b.place() && mat_a.place() == mat_out->place(),
      "The places of matrices must be same");

  int M = dim_out[0];
  int N = dim_out[1];
  int K = !trans_a ? dim_a[1] : dim_a[0];

  CBLAS_TRANSPOSE transA = !trans_a ? CblasNoTrans : CblasTrans;
  CBLAS_TRANSPOSE transB = !trans_b ? CblasNoTrans : CblasTrans;

  this->GEMM(transA, transB, M, N, K, alpha, mat_a.data<T>(), mat_b.data<T>(),
             beta, mat_out->data<T>());
}

Y
Yu Yang 已提交
465 466 467 468 469 470 471
template <>
template <typename T>
void Blas<platform::CPUDeviceContext>::AXPY(int n, T alpha, const T *x,
                                            T *y) const {
  CBlas<T>::AXPY(n, alpha, x, 1, y, 1);
}

472 473 474 475 476 477 478 479 480 481 482 483 484
template <>
template <typename T>
void Blas<platform::CPUDeviceContext>::VCOPY(int n, const T *x, T *y) const {
  CBlas<T>::VCOPY(n, x, 1, y, 1);
}

template <>
template <typename T>
void Blas<platform::CPUDeviceContext>::VADD(int n, const T *x, const T *y,
                                            T *z) const {
#ifdef PADDLE_WITH_MKLML
  CBlas<T>::VADD(n, x, y, z);
#else
485 486 487 488 489 490
  if (x == z) {
    this->template AXPY<T>(n, 1., y, z);
  } else {
    this->template VCOPY<T>(n, y, z);
    this->template AXPY<T>(n, 1., x, z);
  }
491 492 493
#endif
}

494 495 496 497 498 499 500 501 502 503 504 505 506 507
template <>
template <typename T>
void Blas<platform::CPUDeviceContext>::VSUB(int n, const T *x, const T *y,
                                            T *z) const {
#ifdef PADDLE_WITH_MKLML
  CBlas<T>::VSUB(n, x, y, z);
#else
  // try to find if openblas support vsub
  for (int i = 0; i < n; ++i) {
    z[i] = x[i] - y[i];
  }
#endif
}

T
tensor-tang 已提交
508 509 510 511 512 513 514 515 516 517
template <>
template <typename T>
void Blas<platform::CPUDeviceContext>::VMUL(int n, const T *x, const T *y,
                                            T *z) const {
#ifdef PADDLE_WITH_MKLML
  CBlas<T>::VMUL(n, x, y, z);
#else
  // try to find if openblas support vmul
  for (int i = 0; i < n; ++i) {
    z[i] = x[i] * y[i];
518 519 520 521 522 523 524 525 526 527 528 529 530 531
  }
#endif
}

template <>
template <typename T>
void Blas<platform::CPUDeviceContext>::VDIV(int n, const T *x, const T *y,
                                            T *z) const {
#ifdef PADDLE_WITH_MKLML
  CBlas<T>::VDIV(n, x, y, z);
#else
  // try to find if openblas support vdiv
  for (int i = 0; i < n; ++i) {
    z[i] = x[i] / y[i];
T
tensor-tang 已提交
532 533 534 535
  }
#endif
}

T
tensor-tang 已提交
536 537 538 539 540 541 542 543 544 545 546 547 548
template <>
template <typename T>
void Blas<platform::CPUDeviceContext>::VEXP(int n, const T *x, T *y) const {
#ifdef PADDLE_WITH_MKLML
  CBlas<T>::VEXP(n, x, y);
#else
  // try to find if openblas support vexp
  for (int i = 0; i < n; ++i) {
    y[i] = std::exp(x[i]);
  }
#endif
}

T
tensor-tang 已提交
549 550
template <>
template <typename T>
T
tensor-tang 已提交
551
void Blas<platform::CPUDeviceContext>::VSQUARE(int n, const T *x, T *y) const {
T
tensor-tang 已提交
552
#ifdef PADDLE_WITH_MKLML
T
tensor-tang 已提交
553
  CBlas<T>::VSQUARE(n, x, y);
T
tensor-tang 已提交
554 555
#else
  for (int i = 0; i < n; ++i) {
T
tensor-tang 已提交
556
    y[i] = x[i] * x[i];
T
tensor-tang 已提交
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
  }
#endif
}

template <>
template <typename T>
void Blas<platform::CPUDeviceContext>::VPOW(int n, const T *x, T a,
                                            T *y) const {
#ifdef PADDLE_WITH_MKLML
  CBlas<T>::VPOW(n, x, a, y);
#else
  for (int i = 0; i < n; ++i) {
    y[i] = std::pow(x[i], a);
  }
#endif
}

T
tensor-tang 已提交
574 575 576 577
template <>
template <typename T>
T Blas<platform::CPUDeviceContext>::DOT(int n, const T *x, const T *y) const {
#ifdef PADDLE_WITH_MKLML
T
tensor-tang 已提交
578
  return CBlas<T>::DOT(n, x, 1, y, 1);
T
tensor-tang 已提交
579 580 581 582 583 584 585 586 587 588
#else
  // try to find if openblas support cblas_dot
  T sum = 0;
  for (int i = 0; i < n; ++i) {
    sum += x[i] * y[i];
  }
  return sum;
#endif
}

T
tensor-tang 已提交
589 590
template <>
template <typename T>
T
tensor-tang 已提交
591
void Blas<platform::CPUDeviceContext>::SCAL(int n, const T a, T *x) const {
T
tensor-tang 已提交
592 593 594 595 596 597 598 599 600 601
#ifdef PADDLE_WITH_MKLML
  CBlas<T>::SCAL(n, a, x, 1);
#else
  // try to find if openblas support cblas_scal
  for (int i = 0; i < n; ++i) {
    x[i] = a * x[i];
  }
#endif
}

J
Jacek Czaja 已提交
602 603 604 605 606
template <>
template <typename T>
T Blas<platform::CPUDeviceContext>::ASUM(int n, T *x, int inc) const {
  auto sum = static_cast<T>(0.0);
#ifdef PADDLE_WITH_MKLML
607
  sum = CBlas<T>::ASUM(n, x, inc);
J
Jacek Czaja 已提交
608
#else
J
Jacek Czaja 已提交
609
  // TODO(jczaja): check if openblas does provide cblas_sasum/cblas_dasum
J
Jacek Czaja 已提交
610 611 612 613 614 615 616
  for (int c = 0; c < n; ++c) {
    sum += x[c];
  }
#endif
  return sum;
}

Y
Yu Yang 已提交
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
template <>
template <typename T>
void Blas<platform::CPUDeviceContext>::GEMV(bool trans_a, int M, int N, T alpha,
                                            const T *A, const T *B, T beta,
                                            T *C) const {
  CBLAS_TRANSPOSE transA = !trans_a ? CblasNoTrans : CblasTrans;
  CBlas<T>::GEMV(CblasRowMajor, transA, M, N, alpha, A, N, B, 1, beta, C, 1);
}

template <>
template <typename T>
void Blas<platform::CPUDeviceContext>::BatchedGEMM(
    CBLAS_TRANSPOSE transA, CBLAS_TRANSPOSE transB, int M, int N, int K,
    T alpha, const T *A, const T *B, T beta, T *C, int batchCount,
    int64_t strideA, int64_t strideB) const {
#ifdef PADDLE_WITH_MKLML
  int lda = (transA == CblasNoTrans) ? K : M;
  int ldb = (transB == CblasNoTrans) ? N : K;
  int ldc = N;
  auto a_array = std::vector<const T *>(batchCount);
  auto b_array = std::vector<const T *>(batchCount);
  auto c_array = std::vector<T *>(batchCount);
  for (int k = 0; k < batchCount; ++k) {
    a_array[k] = &A[k * strideA];
    b_array[k] = &B[k * strideB];
    c_array[k] = &C[k * M * N];
  }

  CBlas<T>::GEMM_BATCH(CblasRowMajor, &transA, &transB, &M, &N, &K, &alpha,
                       a_array.data(), &lda, b_array.data(), &ldb, &beta,
                       c_array.data(), &ldc, 1 /* group_count */, &batchCount);
#else
  for (int k = 0; k < batchCount; ++k) {
Y
yuyang18 已提交
650 651 652
    auto *Ak = &A[k * strideA];
    auto *Bk = &B[k * strideB];
    auto *Ck = &C[k * M * N];
Y
Yu Yang 已提交
653 654 655 656 657
    this->template GEMM<T>(transA, transB, M, N, K, alpha, Ak, Bk, beta, Ck);
  }
#endif
}

658 659 660 661
#if defined(PADDLE_WITH_MKLML) && !defined(PADDLE_WITH_CUDA)
template <>
template <typename T>
void Blas<platform::CPUDeviceContext>::BatchedGEMMWithHead(
662 663 664 665 666 667
    CBLAS_TRANSPOSE transA, CBLAS_TRANSPOSE transB, int W1, int H1, int W2,
    int H2, T alpha, const T *A, const T *B, T beta, T *C, int batchCount,
    int64_t strideA, int64_t strideB, int64_t head_number,
    bool split_b_vertical) const {
  int lda = (transA == CblasNoTrans) ? W1 : H1;
  int ldb = (transB == CblasNoTrans) ? W2 : H2;
668 669 670 671
  auto a_array = std::vector<const T *>(batchCount);
  auto b_array = std::vector<const T *>(batchCount);
  auto c_array = std::vector<T *>(batchCount);

672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
  if (split_b_vertical) {
    int ldc = W2;
    int sub_width = W2 / head_number;

    for (int i = 0; i < head_number; i++) {
      int sub_matA_offset = (transA == CblasNoTrans)
                                ? i * (W1 / head_number)
                                : i * (W1 / head_number) * H1;
      int sub_matB_offset = (transB == CblasNoTrans)
                                ? i * (W2 / head_number)
                                : i * (W2 / head_number) * H2;
      int sub_matC_offset = i * W2 / head_number;
      for (int k = 0; k < batchCount; ++k) {
        a_array[k] = &A[k * strideA] + sub_matA_offset;
        b_array[k] = &B[k * strideB] + sub_matB_offset;
        c_array[k] = &C[k * H1 * W2] + sub_matC_offset;
      }

      CBlas<T>::GEMM_BATCH(CblasRowMajor, &transA, &transB, &H1, &sub_width,
                           &H2, &alpha, a_array.data(), &lda, b_array.data(),
                           &ldb, &beta, c_array.data(), &ldc,
                           1 /* group_count */, &batchCount);
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
  } else {
    PADDLE_ENFORCE_EQ(W1, H2);
    int ldc = W2 * head_number;
    int sub_width = W1 / head_number;

    for (int i = 0; i < head_number; i++) {
      int sub_matA_offset = (transA == CblasNoTrans)
                                ? i * (W1 / head_number)
                                : i * (W1 / head_number) * H1;
      int sub_matB_offset = (transB == CblasNoTrans)
                                ? i * (W1 / head_number) * W2
                                : i * (W1 / head_number);
      int sub_matC_offset = i * W2;
      for (int k = 0; k < batchCount; ++k) {
        a_array[k] = &A[k * strideA] + sub_matA_offset;
        b_array[k] = &B[k * strideB] + sub_matB_offset;
        c_array[k] = &C[k * H1 * head_number * W2] + sub_matC_offset;
      }

      CBlas<T>::GEMM_BATCH(CblasRowMajor, &transA, &transB, &H1, &W2,
                           &sub_width, &alpha, a_array.data(), &lda,
                           b_array.data(), &ldb, &beta, c_array.data(), &ldc,
                           1 /* group_count */, &batchCount);
    }
720 721 722 723
  }
}
#endif

T
tensor-tang 已提交
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
template <typename DeviceContext>
template <typename T>
void Blas<DeviceContext>::MatMul(const int M, const int N, const int K,
                                 const T *A, const T *B, T *C) const {
  this->template GEMM<T>(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, N, K,
                         static_cast<T>(1), A, K, B, N, static_cast<T>(0), C,
                         N);
}

template <>
template <typename T>
void Blas<platform::CPUDeviceContext>::MatMul(const int M, const int N,
                                              const int K, const T *A,
                                              const T *B, T *C) const {
#ifdef PADDLE_WITH_LIBXSMM
  // Refer to https://github.com/hfp/libxsmm/blob/master/README.md
  // But the threshold is custom constexpr int LIBXSMM_THRESHOLD = 20 * 20 * 20;

  // Since the matrix is very small,
  // so the unit of calculation is already very fast,
  // and the if( M*N*K < LIBXSMM_THRESHOLD) would be overhead,
  // use xsmm directly.
  // Note: SMM use ColMajor
  const char transa = 'N';
  const char transb = 'N';
  const T alpha = static_cast<T>(1);
  const T beta = static_cast<T>(0);
  CBlas<T>::SMM_GEMM(&transa, &transb, &N, &M, &K, &alpha, B, &N, A, &K, &beta,
                     C, &N);
  return;
#endif

  CBlas<T>::GEMM(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, N, K,
                 static_cast<T>(1), A, K, B, N, static_cast<T>(0), C, N);
}

Y
Yu Yang 已提交
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
template <typename DeviceContext>
template <typename T>
void Blas<DeviceContext>::MatMul(const framework::Tensor &mat_a,
                                 const MatDescriptor &dim_a,
                                 const framework::Tensor &mat_b,
                                 const MatDescriptor &dim_b, T alpha,
                                 framework::Tensor *mat_out, T beta) const {
  PADDLE_ENFORCE_EQ(dim_a.width_, dim_b.height_);
  CBLAS_TRANSPOSE transA = !dim_a.trans_ ? CblasNoTrans : CblasTrans;
  CBLAS_TRANSPOSE transB = !dim_b.trans_ ? CblasNoTrans : CblasTrans;
  if (dim_a.batch_size_ == 0 && dim_b.batch_size_ == 0) {
    this->template GEMM<T>(transA, transB, dim_a.height_, dim_b.width_,
                           dim_a.width_, alpha, mat_a.data<T>(),
                           mat_b.data<T>(), beta, mat_out->data<T>());
  } else {
    PADDLE_ENFORCE(dim_a.batch_size_ == dim_b.batch_size_ ||
776 777 778 779 780
                       dim_a.batch_size_ == 0 || dim_b.batch_size_ == 0,
                   "dim_a.batch_size should be equal to dim_b.batch_size, or "
                   "one of dim_a.batch_size and dim_b.batch_size should be 0. "
                   "But got dim_a.batch_size = %d, dim_b.batch_size = %d.",
                   dim_a.batch_size_, dim_b.batch_size_);
Y
Yu Yang 已提交
781 782 783 784 785 786 787
    this->template BatchedGEMM<T>(
        transA, transB, dim_a.height_, dim_b.width_, dim_a.width_, alpha,
        mat_a.data<T>(), mat_b.data<T>(), beta, mat_out->data<T>(),
        dim_a.batch_size_ == 0 ? dim_b.batch_size_ : dim_a.batch_size_,
        dim_a.stride_, dim_b.stride_);
  }
}
788 789 790 791 792 793 794 795 796 797 798 799

#if defined(PADDLE_WITH_MKLML) && !defined(PADDLE_WITH_CUDA)
/*
 * Multiple two matrixes with multiple heads
 *
 * A new parameter, i.e head_number is added compared to normal MatMul.
 * The head_number describes the number of heads a matrix is vertically
 * split.
 *
 * When user calls this API, the multiplication of two big matrixes is split
 * into multiplication of several (head_number_) small matrixes. e.g. if Mat A
 * is [3, 24] and Mat B is [24, 4], when multiple A and B with head_number as
T
tianshuo78520a 已提交
800 801
 * 4, Mat A will be split as 4 matrix of [3, 6] and Mat B will be
 * (horizontally) split as 4 matrix of [6, 4]. The result of final matrix
802 803
 * will be 4 matrix of [3, 4], i.e. [3, 16].
 * Another example is A is [3, 8], B is [2, 16], head_number is 4. In this
T
tianshuo78520a 已提交
804
 * case, A will be split as [3, 2], B will be (vertically) split as
805
 * [2, 4]. The final result will be 4 matrix of 4 matrix of [3,4], i.e. [3, 16]
806 807 808
 */
template <typename DeviceContext>
template <typename T>
809 810 811 812 813 814 815
void Blas<DeviceContext>::MatMulWithHead(const framework::Tensor &mat_a,
                                         const MatDescriptor &dim_a,
                                         const framework::Tensor &mat_b,
                                         const MatDescriptor &dim_b, T alpha,
                                         int head_number,
                                         framework::Tensor *mat_out, T beta,
                                         bool mat_b_split_vertical) const {
816 817 818 819 820 821
  PADDLE_ENFORCE_EQ(dim_a.width_ % head_number, 0);
  PADDLE_ENFORCE_GE(head_number, 1);
  PADDLE_ENFORCE_LE(head_number, dim_a.width_);
  CBLAS_TRANSPOSE transA = !dim_a.trans_ ? CblasNoTrans : CblasTrans;
  CBLAS_TRANSPOSE transB = !dim_b.trans_ ? CblasNoTrans : CblasTrans;

822 823 824 825 826
  if (mat_b_split_vertical) {
    PADDLE_ENFORCE_EQ(dim_b.height_, dim_a.width_ / head_number);
    PADDLE_ENFORCE_EQ(dim_b.width_ % head_number, 0);
  }

827
  if (dim_a.batch_size_ == 0 && dim_b.batch_size_ == 0) {
828 829 830 831 832 833 834 835 836 837
    int lda = !dim_a.trans_ ? dim_a.width_ : dim_a.height_;
    int ldb = !dim_b.trans_ ? dim_b.width_ : dim_b.height_;
    int sub_matA_offset;
    int sub_matB_offset;
    int sub_matC_offset;
    int sub_mat_M = dim_a.height_;
    int sub_mat_N;
    int sub_mat_K;
    int ldc;

838
    for (int i = 0; i < head_number; i++) {
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
      sub_matA_offset = dim_a.trans_
                            ? i * (dim_a.width_ / head_number) * dim_a.height_
                            : i * (dim_a.width_ / head_number);
      if (mat_b_split_vertical) {
        sub_matB_offset = dim_b.trans_
                              ? i * (dim_b.width_ / head_number) * dim_b.height_
                              : i * (dim_b.width_ / head_number);
        sub_matC_offset = i * dim_b.width_ / head_number;

        sub_mat_N = dim_b.width_ / head_number;
        sub_mat_K = dim_b.height_;

        ldc = dim_b.width_;
      } else {
        sub_matB_offset =
            dim_b.trans_ ? i * (dim_b.height_ / head_number)
                         : i * (dim_b.height_ / head_number) * dim_b.width_;
        sub_matC_offset = i * dim_b.width_;

        sub_mat_N = dim_b.width_;
        sub_mat_K = dim_a.width_ / head_number;

        ldc = head_number * dim_b.width_;
      }

      this->template GEMM<T>(transA, transB, sub_mat_M, sub_mat_N, sub_mat_K,
                             alpha, mat_a.data<T>() + sub_matA_offset, lda,
866 867 868 869
                             mat_b.data<T>() + sub_matB_offset, ldb, beta,
                             mat_out->data<T>() + sub_matC_offset, ldc);
    }
  } else {
870 871 872
    PADDLE_ENFORCE_EQ((dim_a.batch_size_ == dim_b.batch_size_ ||
                       dim_a.batch_size_ == 0 || dim_b.batch_size_ == 0),
                      true);
873 874

    this->template BatchedGEMMWithHead<T>(
875 876 877
        transA, transB, dim_a.width_, dim_a.height_, dim_b.width_,
        dim_b.height_, alpha, mat_a.data<T>(), mat_b.data<T>(), beta,
        mat_out->data<T>(),
878
        dim_a.batch_size_ == 0 ? dim_b.batch_size_ : dim_a.batch_size_,
879
        dim_a.stride_, dim_b.stride_, head_number, mat_b_split_vertical);
880 881 882 883
  }
}
#endif

Y
Use mkl  
Yu Yang 已提交
884 885 886 887 888 889 890 891 892 893 894
template <typename DeviceContext>
template <typename T>
void Blas<DeviceContext>::VINV(int n, const T *a, T *y) const {
#ifdef PADDLE_WITH_MKLML
  CBlas<T>::VINV(n, a, y);
#else
  for (int i = 0; i < n; ++i) {
    y[i] = 1.0 / a[i];
  }
#endif
}
Y
Yu Yang 已提交
895

Y
Yihua Xu 已提交
896 897 898 899 900 901 902 903 904 905 906 907 908
template <>
template <typename T>
void Blas<platform::CPUDeviceContext>::VMERF(int n, const T *a, T *y,
                                             int64_t mode) const {
#ifdef PADDLE_WITH_MKLML
  CBlas<T>::VMERF(n, a, y, mode);
#else
  for (int i = 0; i < n; ++i) {
    y[i] = std::erf(a[i]);
  }
#endif
}

909 910 911 912 913 914 915 916 917 918 919 920 921
#ifdef PADDLE_WITH_MKLML
template <>
template <typename T>
void Blas<platform::CPUDeviceContext>::CSRMM(
    const char *transa, const int *m, const int *n, const int *k,
    const T *alpha, const char *matdescra, const T *val, const int *indx,
    const int *pntrb, const int *pntre, const T *b, const int *ldb,
    const T *beta, T *c, const int *ldc) const {
  CBlas<T>::CSRMM(transa, m, n, k, alpha, matdescra, val, indx, pntrb, pntre, b,
                  ldb, beta, c, ldc);
}
#endif

G
Guo Sheng 已提交
922 923 924 925 926 927 928 929 930 931 932
template <>
template <typename T>
void Blas<platform::CPUDeviceContext>::TRSM(CBLAS_SIDE side, CBLAS_UPLO uplo,
                                            CBLAS_TRANSPOSE transA,
                                            CBLAS_DIAG diag, int M, int N,
                                            T alpha, const T *A, int lda, T *B,
                                            int ldb) const {
  CBlas<T>::TRSM(CblasRowMajor, side, uplo, transA, diag, M, N, alpha, A, lda,
                 B, ldb);
}

Y
Yu Yang 已提交
933 934 935
}  // namespace math
}  // namespace operators
}  // namespace paddle