Add abs functions

This commit is contained in:
zhoushunjie
2022-11-24 04:02:00 +00:00
parent a14c55069f
commit 12af6b4464
4 changed files with 34 additions and 0 deletions

View File

@@ -39,6 +39,7 @@ DEFINE_ACTIVATION_KERNEL(Sqrt, SqrtFunctor)
DEFINE_ACTIVATION_KERNEL(Log, LogFunctor)
DEFINE_ACTIVATION_KERNEL(Round, RoundFunctor)
DEFINE_ACTIVATION_KERNEL(Exp, ExpFunctor)
DEFINE_ACTIVATION_KERNEL(Abs, AbsFunctor)
void Sqrt(const FDTensor& x, FDTensor* out) {
FD_VISIT_FLOAT_TYPES(x.dtype, "SqrtKernel",
@@ -60,5 +61,10 @@ void Exp(const FDTensor& x, FDTensor* out) {
([&] { ExpKernel<data_t>(x, out); }));
}
void Abs(const FDTensor& x, FDTensor* out) {
FD_VISIT_FLOAT_TYPES(x.dtype, "AbsKernel",
([&] { AbsKernel<data_t>(x, out); }));
}
} // namespace function
} // namespace fastdeploy

View File

@@ -43,5 +43,11 @@ FASTDEPLOY_DECL void Round(const FDTensor& x, FDTensor* out);
*/
FASTDEPLOY_DECL void Exp(const FDTensor& x, FDTensor* out);
/** This operator is used to perform elementwise abs for input X. Only for float type FDTensor
@param x The input tensor.
@param out The output tensor which stores the result.
*/
FASTDEPLOY_DECL void Abs(const FDTensor& x, FDTensor* out);
} // namespace function
} // namespace fastdeploy

View File

@@ -52,5 +52,14 @@ template <typename T> struct SqrtFunctor {
}
};
// abs(x) = x if x > 0 else -x
template <typename T> struct AbsFunctor {
template <typename Device, typename X, typename Out>
void operator()(Device d, X x, Out out) const {
out.device(d) =
x.unaryExpr([](T v) { return v > static_cast<T>(0) ? v : -v; });
}
};
} // namespace function
} // namespace fastdeploy

View File

@@ -83,5 +83,18 @@ TEST(fastdeploy, exp_sqrt_round_log) {
log_result.size());
}
TEST(fastdeploy, abs) {
CheckShape check_shape;
CheckData check_data;
FDTensor x, y;
std::vector<float> test_data = {-1, 2, 3, -5, -4, -6};
x.SetExternalData({2, 3}, FDDataType::FP32, test_data.data());
std::vector<float> result = {1, 2, 3, 5, 4, 6};
Abs(x, &y);
check_shape(y.shape, {2, 3});
check_data(reinterpret_cast<const float*>(y.Data()), result.data(),
result.size());
}
} // namespace function
} // namespace fastdeploy