EigenGemm.cpp 2.5 KB
Newer Older
H
hedaoyuan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
/* 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 <glog/logging.h>
#include "unsupported/Eigen/CXX11/Tensor"

namespace paddle {

template <class T>
struct EigenBlasGemm {
  typedef Eigen::TensorMap<Eigen::Tensor<T, 2, Eigen::RowMajor, int>,
                           Eigen::Aligned>
      Matrix;

  static void compute(const bool transA,
                      const bool transB,
                      const int M,
                      const int N,
                      const int K,
                      const T alpha,
                      const T* A,
                      const int lda,
                      const T* B,
                      const int ldb,
                      const T beta,
                      T* C,
                      const int ldc) {
    Eigen::array<int, 2> sizeA;
    if (transA) {
      sizeA[0] = K;
      sizeA[1] = M;
      CHECK_EQ(M, lda);
    } else {
      sizeA[0] = M;
      sizeA[1] = K;
      CHECK_EQ(K, lda);
    }
    Eigen::array<int, 2> sizeB;
    if (transB) {
      sizeB[0] = N;
      sizeB[1] = K;
      CHECK_EQ(K, ldb);
    } else {
      sizeB[0] = K;
      sizeB[1] = N;
      CHECK_EQ(N, ldb);
    }
    Eigen::array<int, 2> sizeC;
    sizeC[0] = M;
    sizeC[1] = N;
    CHECK_EQ(N, ldc);

    const Matrix a(const_cast<T*>(A), sizeA);
    const Matrix b(const_cast<T*>(B), sizeB);
    Matrix c(C, sizeC);

    typedef typename Eigen::Tensor<T, 2>::DimensionPair DimPair;
    Eigen::array<DimPair, 1> dims;
    dims[0] = DimPair(1, 0);
    dims[0].first = transA ? 0 : 1;
    dims[0].second = transB ? 1 : 0;

    Eigen::DefaultDevice device;
    if (alpha == T(1) && beta == T(0)) {
      c.device(device) = a.contract(b, dims);
    } else if (alpha == T(1) && beta == T(1)) {
      c.device(device) += a.contract(b, dims);
    } else {
H
hedaoyuan 已提交
80
      c.device(device) = alpha * a.contract(b, dims) + beta * c;
H
hedaoyuan 已提交
81 82 83 84 85 86 87 88 89 90 91
    }
  }
};

#ifdef PADDLE_TYPE_DOUBLE
template class EigenBlasGemm<double>;
#else
template class EigenBlasGemm<float>;
#endif

}  // namespace paddle