/* Copyright (c) 2021 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 "paddle/fluid/operators/gelu_op.h" namespace paddle { namespace operators { using Tensor = framework::Tensor; template class GeluXPUKernel : public framework::OpKernel { using XPUType = typename XPUTypeTrait::Type; public: void Compute(const framework::ExecutionContext& ctx) const override { auto* x = ctx.Input("X"); auto* out = ctx.Output("Out"); auto place = ctx.GetPlace(); const XPUType* x_data = reinterpret_cast(x->data()); XPUType* y_data = reinterpret_cast(out->mutable_data(place)); auto& dev_ctx = ctx.template device_context(); int r = xpu::gelu(dev_ctx.x_context(), x_data, y_data, x->numel()); PADDLE_ENFORCE_EQ( r, XPU_SUCCESS, platform::errors::External("XPU gelu kernel return wrong value[%d %s]", r, XPUAPIErrorMsg[r])); } }; template class GeluGradXPUKernel : public framework::OpKernel { using XPUType = typename XPUTypeTrait::Type; public: void Compute(const framework::ExecutionContext& ctx) const override { auto* x = ctx.Input("X"); auto* dout = ctx.Input(framework::GradVarName("Out")); auto* dx = ctx.Output(framework::GradVarName("X")); auto place = ctx.GetPlace(); const XPUType* x_data = reinterpret_cast(x->data()); const XPUType* dout_data = reinterpret_cast(dout->data()); XPUType* dx_data = reinterpret_cast(dx->mutable_data(place)); auto& dev_ctx = ctx.template device_context(); int r = xpu::gelu_grad(dev_ctx.x_context(), x_data, nullptr, dout_data, dx_data, dout->numel()); PADDLE_ENFORCE_EQ(r, XPU_SUCCESS, platform::errors::External( "XPU gelu_grad kernel return wrong value[%d %s]", r, XPUAPIErrorMsg[r])); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_XPU_KERNEL( gelu, ops::GeluXPUKernel, ops::GeluXPUKernel); REGISTER_OP_XPU_KERNEL( gelu_grad, ops::GeluGradXPUKernel, ops::GeluGradXPUKernel);