Files
2026-07-13 12:40:42 +08:00

66 lines
2.2 KiB
C++

// Copyright (c) 2022 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 "paddle/phi/kernels/scatter_nd_add_grad_kernel.h"
#include "paddle/phi/backends/cpu/cpu_context.h"
#include "paddle/phi/core/kernel_registry.h"
#include "paddle/phi/core/tensor_utils.h"
#include "paddle/phi/kernels/full_kernel.h"
#include "paddle/phi/kernels/funcs/gather.h"
namespace phi {
template <typename T, typename Context>
void ScatterNdAddGradKernel(const Context &dev_ctx,
const DenseTensor &index,
const DenseTensor &updates UNUSED,
const DenseTensor &out_grad,
DenseTensor *x_grad,
DenseTensor *updates_grad) {
if (out_grad.numel() == 0) {
if (x_grad) {
dev_ctx.template Alloc<T>(x_grad);
}
if (updates_grad) {
Full<T, Context>(dev_ctx, updates_grad->dims(), 0, updates_grad);
}
return;
}
if (x_grad) {
Copy(dev_ctx, out_grad, dev_ctx.GetPlace(), false, x_grad);
}
if (updates_grad) {
dev_ctx.template Alloc<T>(updates_grad);
// Gradient by Gather: dUpdates = dO[Ids]
const auto &index_type = index.dtype();
if (index_type == DataType::INT32) {
funcs::CPUGatherNd<T, int32_t>(dev_ctx, out_grad, index, updates_grad);
} else {
funcs::CPUGatherNd<T, int64_t>(dev_ctx, out_grad, index, updates_grad);
}
}
}
} // namespace phi
PD_REGISTER_KERNEL(scatter_nd_add_grad,
CPU,
ALL_LAYOUT,
phi::ScatterNdAddGradKernel,
float,
double,
int64_t,
int,
uint8_t) {}