1 /* Copyright 2016 The TensorFlow Authors. All Rights Reserved. 2 3 Licensed under the Apache License, Version 2.0 (the "License"); 4 you may not use this file except in compliance with the License. 5 You may obtain a copy of the License at 6 7 http://www.apache.org/licenses/LICENSE-2.0 8 9 Unless required by applicable law or agreed to in writing, software 10 distributed under the License is distributed on an "AS IS" BASIS, 11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 See the License for the specific language governing permissions and 13 limitations under the License. 14 ==============================================================================*/ 15 16 #ifndef TENSORFLOW_CONTRIB_RNN_KERNELS_BLAS_GEMM_H_ 17 #define TENSORFLOW_CONTRIB_RNN_KERNELS_BLAS_GEMM_H_ 18 19 #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" 20 #include "tensorflow/core/framework/tensor_types.h" 21 #include "tensorflow/core/kernels/eigen_activations.h" 22 #include "tensorflow/core/platform/types.h" 23 24 namespace tensorflow { 25 class OpKernelContext; 26 namespace functor { 27 28 template <typename T> 29 struct TensorCuBlasGemm { 30 void operator()(OpKernelContext* ctx, bool transa, bool transb, uint64 m, 31 uint64 n, uint64 k, T alpha, const T* a, int lda, const T* b, 32 int ldb, T beta, T* c, int ldc); 33 }; 34 35 template <typename Device, typename T, bool USE_CUBLAS> 36 struct TensorBlasGemm; 37 38 template <typename Device, typename T> 39 struct TensorBlasGemm<Device, T, true /* USE_CUBLAS */> { 40 static void compute(OpKernelContext* ctx, const Device& d, bool transa, 41 bool transb, T alpha, typename TTypes<T>::ConstMatrix a, 42 typename TTypes<T>::ConstMatrix b, T beta, 43 typename TTypes<T>::Matrix c) { 44 int64 m = c.dimensions()[0]; 45 int64 n = c.dimensions()[1]; 46 int64 k = transa ? a.dimensions()[0] : a.dimensions()[1]; 47 48 TensorCuBlasGemm<T>()(ctx, transb, transa, n, m, k, alpha, b.data(), 49 transb ? k : n, a.data(), transa ? m : k, beta, 50 c.data(), n); 51 } 52 }; 53 54 template <typename Device, typename T> 55 struct TensorBlasGemm<Device, T, false /* USE_CUBLAS */> { 56 static void compute(OpKernelContext* ctx, const Device& d, bool transa, 57 bool transb, T alpha, typename TTypes<T>::ConstMatrix a, 58 typename TTypes<T>::ConstMatrix b, T beta, 59 typename TTypes<T>::Matrix c) { 60 Eigen::array<Eigen::IndexPair<Eigen::DenseIndex>, 1> contract_pairs; 61 contract_pairs[0] = 62 Eigen::IndexPair<Eigen::DenseIndex>(transa == false, transb == true); 63 if (alpha == T(1) && beta == T(0)) { 64 c.device(d) = a.contract(b, contract_pairs); 65 } else if (alpha == T(1) && beta == T(1)) { 66 c.device(d) += a.contract(b, contract_pairs); 67 } else { 68 c.device(d) = c.constant(alpha) * a.contract(b, contract_pairs) + 69 c.constant(beta) * c; 70 } 71 } 72 }; 73 74 } // namespace functor 75 } // namespace tensorflow 76 77 #endif // TENSORFLOW_CONTRIB_RNN_KERNELS_BLAS_GEMM_H_ 78