// Copyright (c) 2024 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. #include #include #include #include #include #include #include #include #ifndef _USE_MATH_DEFINES #define _USE_MATH_DEFINES #endif #include #include "paddle/phi/core/kernel_registry.h" #include "paddle/phi/core/tensor_utils.h" #include "paddle/phi/kernels/funcs/activation_functor.h" #include "paddle/phi/kernels/funcs/blas/blas.h" #include "paddle/phi/kernels/funcs/eigen/common.h" #include "paddle/phi/kernels/soft_relu_grad_kernel.h" namespace phi { template struct SoftReluGradFunctor { float threshold; void SetAttrs(float threshold_) { threshold = threshold_; } template void operator()(Device d, X x UNUSED, Out out, dOut dout, dX dx) { auto tmp = static_cast(threshold); auto temp = ((out > -tmp) * (out < tmp)).template cast(); dx.device(d) = dout * (static_cast(1) - (-out).exp()) * temp; } }; template void SoftmaxGradKernel(const Context& dev_ctx, const DenseTensor& x_in, const DenseTensor& out_in, const DenseTensor& out_grad, float threshold, DenseTensor* x_grad) { dev_ctx.template Alloc(x_grad); auto dout = EigenVector::Flatten(out_grad); auto out = EigenVector::Flatten(out_in); auto dx = EigenVector::Flatten(*x_grad); auto x = EigenVector::Flatten(x_in); auto* eigen_dev = dev_ctx.eigen_device(); SoftReluGradFunctor functor; functor.SetAttrs(threshold); functor(*eigen_dev, x, out, dout, dx); } } // namespace phi PD_REGISTER_KERNEL( soft_relu_grad, CPU, ALL_LAYOUT, phi::SoftmaxGradKernel, float, double) {}