// 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. // 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 "paddle/phi/kernels/swiglu_grad_kernel.h" #include "paddle/phi/backends/xpu/enforce_xpu.h" #include "paddle/phi/core/kernel_registry.h" #include "paddle/phi/kernels/full_kernel.h" namespace phi { template void SwiGluGradKernel(const Context& dev_ctx, const DenseTensor& x, const optional& y, const DenseTensor& dz, DenseTensor* dx, DenseTensor* dy) { if (dx && dx->numel() == 0) { dev_ctx.template Alloc(dx); if (dy) { Full(dev_ctx, dy->dims(), 0, dy); } return; } if (dy && dy->numel() == 0) { dev_ctx.template Alloc(dy); if (dx) { Full(dev_ctx, dx->dims(), 0, dx); } return; } using XPUType = typename XPUTypeTrait::Type; const auto* x_data = x.data(); const auto* dz_data = dz.data(); auto* dx_data = dev_ctx.template Alloc(dx); const auto& dims = x.dims(); int64_t axis = dims.size() - 1; auto dims_vec = vectorize(dims); const XPUType* y_ptr = nullptr; XPUType* dy_ptr = nullptr; if (y) { const auto& y_tensor = y.get(); const auto& y_dims = y_tensor.dims(); const auto* y_data = y_tensor.data(); auto* dy_data = dev_ctx.template Alloc(dy); y_ptr = reinterpret_cast(y_data); dy_ptr = reinterpret_cast(dy_data); PADDLE_ENFORCE_EQ(y_dims, dims, common::errors::InvalidArgument( "The shape of Input(Y):[%s] must be equal " "to the shape of Input(X):[%s].", y_dims, dims)); } int ret = xpu::swiglu_grad(dev_ctx.x_context(), reinterpret_cast(x_data), y_ptr, reinterpret_cast(dz_data), reinterpret_cast(dx_data), dy_ptr, dims_vec, axis, true); PADDLE_ENFORCE_XDNN_SUCCESS(ret, "swiglu_grad"); } } // namespace phi PD_REGISTER_KERNEL(swiglu_grad, XPU, ALL_LAYOUT, phi::SwiGluGradKernel, float, phi::float16, phi::bfloat16){};