/* 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/framework/op_registry.h" #include "paddle/fluid/platform/device/npu/npu_op_runner.h" #include "paddle/phi/kernels/funcs/axis_utils.h" namespace paddle { namespace operators { template class SoftmaxNPUKernel : public framework::OpKernel { public: void Compute(const framework::ExecutionContext& ctx) const override { auto* in = ctx.Input("X"); auto axis = ctx.Attr("axis"); std::vector axes; axes.push_back(axis); framework::NPUAttributeMap attr_input = {{"axes", axes}}; auto* out = ctx.Output("Out"); out->mutable_data(ctx.GetPlace()); const auto& runner = NpuOpRunner("SoftmaxV2", {*in}, {*out}, attr_input); auto stream = ctx.template device_context() .stream(); runner.Run(stream); } }; template class SoftmaxGradNPUKernel : public framework::OpKernel { public: void Compute(const framework::ExecutionContext& ctx) const override { auto* out = ctx.Input("Out"); auto* dOut = ctx.Input(framework::GradVarName("Out")); auto* dX = ctx.Output(framework::GradVarName("X")); auto dims = dX->dims(); const int rank = dims.size(); const int axis = phi::funcs::CanonicalAxis(ctx.Attr("axis"), rank); int64_t first_dim = 1; int64_t sec_dim = 1; for (int i = 0; i < axis; i++) { first_dim *= dims[i]; } for (int i = axis; i < rank; i++) { sec_dim *= dims[i]; } Tensor tmp_out; tmp_out.ShareDataWith(*out).Resize({first_dim, sec_dim}); Tensor tmp_dOut; tmp_dOut.ShareDataWith(*dOut).Resize({first_dim, sec_dim}); dX->Resize(phi::make_ddim({first_dim, sec_dim})); dX->mutable_data(ctx.GetPlace()); framework::NPUAttributeMap attr_input = {}; const auto& runner = NpuOpRunner(std::string("SoftmaxGrad"), {tmp_out, tmp_dOut}, {*dX}, attr_input); auto stream = ctx.template device_context() .stream(); runner.Run(stream); dX->Resize(dims); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; namespace plat = paddle::platform; REGISTER_OP_NPU_KERNEL( softmax, ops::SoftmaxNPUKernel, ops::SoftmaxNPUKernel, ops::SoftmaxNPUKernel); REGISTER_OP_NPU_KERNEL( softmax_grad, ops::SoftmaxGradNPUKernel, ops::SoftmaxGradNPUKernel, ops::SoftmaxGradNPUKernel);