From b458b41d6844d9ffcbc318f8ffb97458997cb5fc Mon Sep 17 00:00:00 2001 From: Kai Li Date: Tue, 25 Feb 2014 20:06:05 +0800 Subject: [PATCH] Use macro to simplify element wise cpu math functions --- include/caffe/util/math_functions.hpp | 33 ++++++++++++++++++++++----------- src/caffe/util/math_functions.cpp | 13 ++----------- 2 files changed, 24 insertions(+), 22 deletions(-) diff --git a/include/caffe/util/math_functions.hpp b/include/caffe/util/math_functions.hpp index 4878cf2..ec297bf 100644 --- a/include/caffe/util/math_functions.hpp +++ b/include/caffe/util/math_functions.hpp @@ -126,22 +126,33 @@ inline char caffe_sign(Dtype val) { return (Dtype(0) < val) - (val < Dtype(0)); } -template -void caffe_cpu_sign(const int n, const Dtype* x, Dtype* y) { - for (int i = 0; i < n; ++i) { - y[i] = caffe_sign(x[i]); +// The following two macros are modifications of DEFINE_VSL_UNARY_FUNC +// in include/caffe/util/mkl_alternate.hpp authored by @Rowland Depp. +// Please refer to commit 7e8ef25c7 of the boost-eigen branch. +// Git cherry picking that commit caused a conflict hard to resolve and +// copying that file in convenient for code reviewing. +// So they have to be pasted here temporarily. +#define DEFINE_CAFFE_CPU_UNARY_FUNC(name, operation) \ + template \ + void caffe_cpu_##name(const int n, const Dtype* x, Dtype* y) { \ + CHECK_GT(n, 0); CHECK(x); CHECK(y); \ + for (int i = 0; i < n; ++i) { \ + operation; \ + } \ } -} + +#define INSTANTIATE_CAFFE_CPU_UNARY_FUNC(name) \ + template <> \ + void caffe_cpu_##name(const int n, const float* x, float* y); \ + template <> \ + void caffe_cpu_##name(const int n, const double* x, double* y) + +DEFINE_CAFFE_CPU_UNARY_FUNC(sign, y[i] = caffe_sign(x[i])); template void caffe_gpu_sign(const int n, const Dtype* x, Dtype* y); -template -void caffe_cpu_fabs(const int n, const Dtype* x, Dtype* y) { - for (int i = 0; i < n; ++i) { - y[i] = std::fabs(x[i]); - } -} +DEFINE_CAFFE_CPU_UNARY_FUNC(fabs, y[i] = std::fabs(x[i])); template void caffe_gpu_fabs(const int n, const Dtype* x, Dtype* y); diff --git a/src/caffe/util/math_functions.cpp b/src/caffe/util/math_functions.cpp index a24f287..47be94a 100644 --- a/src/caffe/util/math_functions.cpp +++ b/src/caffe/util/math_functions.cpp @@ -410,16 +410,7 @@ void caffe_gpu_asum(const int n, const double* x, double* y) { CUBLAS_CHECK(cublasDasum(Caffe::cublas_handle(), n, x, 1, y)); } -template <> -void caffe_cpu_sign(const int n, const float* x, float* y); - -template <> -void caffe_cpu_sign(const int n, const double* x, double* y); - -template <> -void caffe_cpu_fabs(const int n, const float* x, float* y); - -template <> -void caffe_cpu_fabs(const int n, const double* x, double* y); +INSTANTIATE_CAFFE_CPU_UNARY_FUNC(sign); +INSTANTIATE_CAFFE_CPU_UNARY_FUNC(fabs); } // namespace caffe -- 2.7.4