elementwise_grad_kernel_impl.h 32.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* 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. */

#pragma once

17 18
#include "glog/logging.h"

19
#include "paddle/phi/common/amp_type_traits.h"
20
#include "paddle/phi/common/complex.h"
21
#include "paddle/phi/common/float16.h"
22
#include "paddle/phi/core/dense_tensor.h"
23
#include "paddle/phi/core/tensor_utils.h"
24
#include "paddle/phi/kernels/full_kernel.h"
25
#include "paddle/phi/kernels/funcs/broadcast_function.h"
26
#include "paddle/phi/kernels/funcs/eigen/common.h"
27
#include "paddle/phi/kernels/funcs/elementwise_functor.h"
28

29
namespace phi {
30 31 32 33 34 35 36 37 38 39

template <typename T, typename Context, typename GradFunc>
void AddGradImpl(const Context& dev_ctx,
                 const DenseTensor& x,
                 const DenseTensor& y,
                 const DenseTensor& out_grad,
                 int axis,
                 DenseTensor* x_grad,
                 DenseTensor* y_grad,
                 GradFunc grad_func) {
40
  phi::funcs::ElementwiseGradPreProcess(out_grad, x_grad);
41 42 43 44 45 46
  auto* out = &out_grad;
  // Special case when y_grad is not needed and x_grad doesn't reduce
  if (x_grad != nullptr && y_grad == nullptr &&
      x_grad->dims() == out_grad.dims()) {
    VLOG(4) << "Special case when y_grad is not needed and x_grad doesn't "
               "reduce";
47
    phi::Copy(dev_ctx, out_grad, dev_ctx.GetPlace(), false, x_grad);
48 49 50 51
  } else if (x_grad == nullptr && y_grad != nullptr &&
             y_grad->dims() == out_grad.dims()) {
    VLOG(4) << "Special case when x_grad is not needed and y_grad doesn't "
               "reduce";
52
    phi::Copy(dev_ctx, out_grad, dev_ctx.GetPlace(), false, y_grad);
53 54 55 56 57
  } else {
    grad_func(dev_ctx, x, y, *out, out_grad, x_grad, y_grad, axis);
  }
}

58
template <typename T, typename Context>
59 60
void AddDoubleGradImpl(const Context& dev_ctx,
                       const DenseTensor& y,
61 62
                       const paddle::optional<DenseTensor>& ddx,
                       const paddle::optional<DenseTensor>& ddy,
63 64
                       const DenseTensor& dout,
                       int axis,
65
                       DenseTensor* ddout) {
66 67 68 69 70 71 72 73
  // ddOut = ddx + ddy
  if (ddout) {
    DenseTensor ddx_safe, ddy_safe;
    funcs::GetDoubleGradSafeTensor<Context, T>(
        dev_ctx, dout, ddx.get_ptr(), &ddx_safe);
    funcs::GetDoubleGradSafeTensor<Context, T>(
        dev_ctx, y, ddy.get_ptr(), &ddy_safe);

74
    dev_ctx.template Alloc<T>(ddout);
75 76 77
    auto ddx_dims = ddx_safe.dims();
    auto ddy_dims = ddy_safe.dims();
    if (ddx_dims.size() >= ddy_dims.size()) {
78
      funcs::ElementwiseCompute<funcs::AddFunctor<T>, T>(
79
          dev_ctx, ddx_safe, ddy_safe, funcs::AddFunctor<T>(), ddout, axis);
80
    } else {
81 82 83 84 85
      funcs::ElementwiseCompute<funcs::InverseAddFunctor<T>, T>(
          dev_ctx,
          ddx_safe,
          ddy_safe,
          funcs::InverseAddFunctor<T>(),
86 87
          ddout,
          axis);
88 89 90 91
    }
  }
}

92
template <typename T, typename Context>
93 94
void SubtractDoubleGradImpl(const Context& dev_ctx,
                            const DenseTensor& y,
95 96
                            const paddle::optional<DenseTensor>& ddx,
                            const paddle::optional<DenseTensor>& ddy,
97 98
                            const DenseTensor& dout,
                            int axis,
99
                            DenseTensor* ddout) {
100 101 102 103 104 105 106 107
  // DDOut = ddx - ddy
  if (ddout) {
    DenseTensor ddx_safe, ddy_safe;
    funcs::GetDoubleGradSafeTensor<Context, T>(
        dev_ctx, dout, ddx.get_ptr(), &ddx_safe);
    funcs::GetDoubleGradSafeTensor<Context, T>(
        dev_ctx, y, ddy.get_ptr(), &ddy_safe);

108
    dev_ctx.template Alloc<T>(ddout);
109
    funcs::ElementwiseCompute<funcs::SubtractFunctor<T>, T>(
110
        dev_ctx, ddx_safe, ddy_safe, funcs::SubtractFunctor<T>(), ddout, axis);
111 112 113
  }
}

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
/*
******************************
    Divide Grad
******************************
*/

template <typename T>
struct DivGradDX {
  HOSTDEVICE T operator()(T x, T y, T out, T dout) const { return dout / y; }
};

template <typename T>
struct DivGradDX<phi::dtype::complex<T>> {
  HOSTDEVICE phi::dtype::complex<T> operator()(
      phi::dtype::complex<T> x,
      phi::dtype::complex<T> y,
      phi::dtype::complex<T> out,
      phi::dtype::complex<T> dout) const {
    phi::dtype::complex<T> y_conj(y.real, -y.imag);
    return dout / y_conj;
  }
};

template <typename T>
struct DivGradDY {
  HOSTDEVICE T operator()(T x, T y, T out, T dout) const {
    return -dout * out / y;
  }
};

template <typename T>
145
struct DivGradDY<phi::dtype::complex<T>> {
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
  HOSTDEVICE phi::dtype::complex<T> operator()(
      phi::dtype::complex<T> x,
      phi::dtype::complex<T> y,
      phi::dtype::complex<T> out,
      phi::dtype::complex<T> dout) const {
    phi::dtype::complex<T> out_div_y_conj((out / y).real, -(out / y).imag);
    return -dout * out_div_y_conj;
  }
};

template <typename T>
struct DivDoubleDY {
  HOSTDEVICE T operator()(T x, T y, T out, T dout) const {
    return y * out * dout - x * dout;
  }
};

template <typename T, typename Context>
void DivideDoubleGradKernel(const Context& dev_ctx,
                            const DenseTensor& y,
                            const DenseTensor& out,
                            const DenseTensor& dx,
168 169
                            const paddle::optional<DenseTensor>& ddx,
                            const paddle::optional<DenseTensor>& ddy,
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
                            int axis,
                            DenseTensor* dy,
                            DenseTensor* dout,
                            DenseTensor* ddout) {
  if (dy) {
    dy->Resize(y.dims());
    dev_ctx.template Alloc<T>(dy);
  }
  if (dout) {
    dout->Resize(out.dims());
    dev_ctx.template Alloc<T>(dout);
  }
  if (ddout) {
    ddout->Resize(out.dims());
    dev_ctx.template Alloc<T>(ddout);
  }
  // ddX_safe == null ? 0 : ddX
  // ddY_safe == null ? 0 : ddY
  DenseTensor ddX_safe, ddY_safe;
  phi::funcs::GetDoubleGradSafeTensor<Context, T>(
      dev_ctx, dx, ddx.get_ptr(), &ddX_safe);
  phi::funcs::GetDoubleGradSafeTensor<Context, T>(
      dev_ctx, y, ddy.get_ptr(), &ddY_safe);

  // ddOut = ddX / Y - Out * ddY / Y = (ddX - Out * ddY) / Y
  // dY = Out * dX * ddY / Y - dX * ddX / Y
  // dOut = - dX * ddY
  // To save memory, (1) dout can be used as 'tmp' tensor, (2) ddout can
  // inplace ddx
  DenseTensor tmp;
  if (dout) {
    tmp = *dout;
  } else {
    tmp.Resize(out.dims());
    dev_ctx.template Alloc<T>(&tmp);
  }
  if (dy) {
    // dX_div_Y = dX / Y;
    DenseTensor dX_div_Y = tmp;
    funcs::DefaultElementwiseOperator<Context,
                                      T,
                                      funcs::DivideFunctor<T>,
                                      funcs::InverseDivideFunctor<T>>(
        dev_ctx, dx, y, &dX_div_Y, axis);

    // NOTE(dengkaipeng): in the following ElemwiseGradCompute, for the
    // first output tensor is nullptr, the branch to calculate first
    // output tensor will not be activated, DivGradDx function will not
    // be called and can be ignored, the first branch has little effect
    // on running speed.

    // dY = Out * dX * ddY / Y - dX * ddX / Y
    phi::funcs::ElemwiseGradCompute<Context, T, DivGradDX<T>, DivDoubleDY<T>>(
        dev_ctx,
        ddX_safe,
        ddY_safe,
        out,
        dX_div_Y,
        axis,
        nullptr,
        dy,
        DivGradDX<T>(),
        DivDoubleDY<T>());
  }

  if (ddout) {
    // ddOut = ddX / Y - Out * ddY / Y = (ddX - Out * ddY) / Y
    funcs::DefaultElementwiseOperator<Context,
                                      T,
                                      funcs::MultiplyFunctor<T>,
                                      funcs::InverseMultiplyFunctor<T>>(
        dev_ctx, out, ddY_safe, &tmp, axis);
    funcs::DefaultElementwiseOperator<Context,
                                      T,
                                      funcs::SubtractFunctor<T>,
                                      funcs::InverseSubtractFunctor<T>>(
        dev_ctx, ddX_safe, tmp, &tmp, axis);
    funcs::DefaultElementwiseOperator<Context,
                                      T,
                                      funcs::DivideFunctor<T>,
                                      funcs::InverseDivideFunctor<T>>(
        dev_ctx, tmp, y, ddout, axis);
  }

  if (dout) {
    // dOut = - dX * ddY
    funcs::DefaultElementwiseOperator<Context,
                                      T,
                                      funcs::MultiplyFunctor<T>,
                                      funcs::InverseMultiplyFunctor<T>>(
        dev_ctx, dx, ddY_safe, dout, axis);
    auto& place = *dev_ctx.eigen_device();
    auto dout_result = phi::EigenVector<T>::Flatten(*dout);
    dout_result.device(place) = static_cast<T>(-1) * dout_result;
  }
}
266 267 268 269 270 271 272 273 274 275 276 277
template <typename T, typename Context>
void ElementwiseFMaxGradKernel(const Context& dev_ctx,
                               const DenseTensor& x,
                               const DenseTensor& y,
                               const DenseTensor& out_grad,
                               DenseTensor* x_grad,
                               DenseTensor* y_grad) {
  funcs::ElementwiseGradPreProcess(out_grad, x_grad);

  auto out = out_grad;  // Fake out, not used
  auto x_dim = x.dims();
  auto y_dim = y.dims();
Z
zhangyuqin1998 已提交
278
  int axis = -1;
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
  if (x.dims() == y.dims()) {
    funcs::ElemwiseGradComputeNoBroadcast<Context,
                                          T,
                                          funcs::FMaxGradDx<T>,
                                          funcs::FMaxGradDy<T>>(
        dev_ctx,
        x_dim,
        y_dim,
        x,
        y,
        out,
        out_grad,
        axis,
        x_grad,
        y_grad,
        funcs::FMaxGradDx<T>(),
        funcs::FMaxGradDy<T>());
  } else {
    funcs::ElemwiseGradComputeWithBroadcast<T,
                                            funcs::FMaxGradDx<T>,
                                            funcs::FMaxGradDy<T>>(
        dev_ctx,
        x_dim,
        y_dim,
        x,
        y,
        out,
        out_grad,
        axis,
        x_grad,
        y_grad,
        funcs::FMaxGradDx<T>(),
        funcs::FMaxGradDy<T>());
  }
}

template <typename T, typename Context>
void ElementwiseFMinGradKernel(const Context& dev_ctx,
                               const DenseTensor& x,
                               const DenseTensor& y,
                               const DenseTensor& out_grad,
                               DenseTensor* x_grad,
                               DenseTensor* y_grad) {
  funcs::ElementwiseGradPreProcess(out_grad, x_grad);
  auto out = out_grad;  // Fake out, not used
  auto x_dim = x.dims();
  auto y_dim = y.dims();
Z
zyfncg 已提交
326
  int axis = -1;
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
  if (x.dims() == y.dims()) {
    funcs::ElemwiseGradComputeNoBroadcast<Context,
                                          T,
                                          funcs::FMinGradDx<T>,
                                          funcs::FMinGradDy<T>>(
        dev_ctx,
        x_dim,
        y_dim,
        x,
        y,
        out,
        out_grad,
        axis,
        x_grad,
        y_grad,
        funcs::FMinGradDx<T>(),
        funcs::FMinGradDy<T>());
  } else {
    funcs::ElemwiseGradComputeWithBroadcast<T,
                                            funcs::FMinGradDx<T>,
                                            funcs::FMinGradDy<T>>(
        dev_ctx,
        x_dim,
        y_dim,
        x,
        y,
        out,
        out_grad,
        axis,
        x_grad,
        y_grad,
        funcs::FMinGradDx<T>(),
        funcs::FMinGradDy<T>());
  }
}
362

Y
YuanRisheng 已提交
363 364 365 366 367
template <typename T>
struct MulGradDX {
  HOSTDEVICE T operator()(T x, T y, T out, T dout) const { return dout * y; }
};

368 369 370 371 372 373 374 375
// avoid [-Wint-in-bool-context] warning
template <>
struct MulGradDX<bool> {
  HOSTDEVICE bool operator()(bool x, bool y, bool out, bool dout) const {
    return dout && y;
  }
};

Y
YuanRisheng 已提交
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
template <typename T>
struct MulGradDX<phi::dtype::complex<T>> {
  HOSTDEVICE phi::dtype::complex<T> operator()(
      phi::dtype::complex<T> x,
      phi::dtype::complex<T> y,
      phi::dtype::complex<T> out,
      phi::dtype::complex<T> dout) const {
    phi::dtype::complex<T> y_conj(y.real, -y.imag);
    return dout * y_conj;
  }
};

/*
******************************
    Multiply Grad
******************************
*/

template <typename T>
struct MulGradDY {
  HOSTDEVICE T operator()(T x, T y, T out, T dout) const { return dout * x; }
};

399 400 401 402 403 404 405 406
// avoid [-Wint-in-bool-context] warning
template <>
struct MulGradDY<bool> {
  HOSTDEVICE bool operator()(bool x, bool y, bool out, bool dout) const {
    return dout && x;
  }
};

Y
YuanRisheng 已提交
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
template <typename T>
struct MulGradDY<phi::dtype::complex<T>> {
  HOSTDEVICE phi::dtype::complex<T> operator()(
      phi::dtype::complex<T> x,
      phi::dtype::complex<T> y,
      phi::dtype::complex<T> out,
      phi::dtype::complex<T> dout) const {
    phi::dtype::complex<T> x_conj(x.real, -x.imag);
    return dout * x_conj;
  }
};

template <typename T, typename Context>
void MultiplyDoubleGradKernel(const Context& dev_ctx,
                              const DenseTensor& x,
                              const DenseTensor& y,
                              const DenseTensor& dout,
424 425
                              const paddle::optional<DenseTensor>& ddx,
                              const paddle::optional<DenseTensor>& ddy,
Y
YuanRisheng 已提交
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
                              int axis,
                              DenseTensor* dx,
                              DenseTensor* dy,
                              DenseTensor* ddout) {
  if (ddout) dev_ctx.template Alloc<T>(ddout);

  DenseTensor ddx_safe, ddy_safe;
  funcs::GetDoubleGradSafeTensor<Context, T>(
      dev_ctx, x, ddx.get_ptr(), &ddx_safe);
  funcs::GetDoubleGradSafeTensor<Context, T>(
      dev_ctx, y, ddy.get_ptr(), &ddy_safe);

  // dx = dout * ddy
  // dy = dout * ddx
  // ddout = ddx * y + x * ddy
  // change computation sequence to save memory, so ddout can inplace ddx and
  // dx can be used as 'tmp' tensor
  // (1) dx = x * ddy
  // (2) dy = dout * ddx
  // (3) ddout = ddx * y
  // (4) ddout = ddout + dx
  // (5) dx = dout * ddy
  if (ddout) {
    auto& place = *dev_ctx.eigen_device();
450 451 452 453 454 455 456 457
    // size(ddout) > size(ddx) or we don't have ddx, ddout can't use memory of
    // ddx using inplace

    bool without_ddx = (ddx.get_ptr() == nullptr);
    if (!without_ddx) {
      without_ddx = (ddout->numel() > ddx.get_ptr()->numel());
    }
    if (without_ddx) {
Y
YuanRisheng 已提交
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
      phi::funcs::ElemwiseGradCompute<Context, T, MulGradDX<T>, MulGradDY<T>>(
          dev_ctx,
          ddx_safe,
          ddy_safe,
          dout,
          dout,
          axis,
          dx,
          dy,
          MulGradDX<T>(),
          MulGradDY<T>());

      DenseTensor ddout_tmp;
      ddout_tmp.Resize(ddout->dims());
      dev_ctx.template Alloc<T>(&ddout_tmp);

      funcs::DefaultElementwiseOperator<Context,
                                        T,
                                        funcs::MultiplyFunctor<T>,
                                        funcs::InverseMultiplyFunctor<T>>(
          dev_ctx, y, ddx_safe, ddout, axis);
479

Y
YuanRisheng 已提交
480 481 482 483 484 485 486 487 488 489 490
      funcs::DefaultElementwiseOperator<Context,
                                        T,
                                        funcs::MultiplyFunctor<T>,
                                        funcs::InverseMultiplyFunctor<T>>(
          dev_ctx, ddy_safe, x, &ddout_tmp, axis);

      auto ddout_t = phi::EigenVector<T>::Flatten(*ddout);
      auto ddout_tmp_t = phi::EigenVector<T>::Flatten(ddout_tmp);
      ddout_t.device(place) = ddout_t + ddout_tmp_t;
    } else {
      // use dx to save memory, other than alloc tmp tensor
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
      if (dx) {
        DenseTensor* ddout_tmp = dx;
        funcs::DefaultElementwiseOperator<Context,
                                          T,
                                          funcs::MultiplyFunctor<T>,
                                          funcs::InverseMultiplyFunctor<T>>(
            dev_ctx, x, ddy_safe, ddout_tmp, axis);

        // NOTE: in the following ElemwiseGradCompute, for the
        // first output tensor is nullptr, the branch to calculate first
        // output tensor will not be activated, DivGradDx function will not
        // be called and can be ignored, the first branch has little effect
        // on running speed.
        phi::funcs::ElemwiseGradCompute<Context, T, MulGradDX<T>, MulGradDY<T>>(
            dev_ctx,
            ddx_safe,
            ddy_safe,
            dout,
            dout,
            axis,
            nullptr,
            dy,
            MulGradDX<T>(),
            MulGradDY<T>());

        funcs::DefaultElementwiseOperator<Context,
                                          T,
                                          funcs::MultiplyFunctor<T>,
                                          funcs::InverseMultiplyFunctor<T>>(
            dev_ctx, ddx_safe, y, ddout, axis);
Y
YuanRisheng 已提交
521

522 523 524 525 526 527 528 529 530 531
        auto ddout_t = phi::EigenVector<T>::Flatten(*ddout);
        auto ddout_tmp_t = phi::EigenVector<T>::Flatten(*ddout_tmp);
        ddout_t.device(place) = ddout_t + ddout_tmp_t;

        funcs::DefaultElementwiseOperator<Context,
                                          T,
                                          funcs::MultiplyFunctor<T>,
                                          funcs::InverseMultiplyFunctor<T>>(
            dev_ctx, dout, ddy_safe, dx, axis);

532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
      } else if ((!dx) && dy) {
        DenseTensor tmp_a(ddout->dtype());
        tmp_a.Resize(ddout->dims());

        dev_ctx.template Alloc<T>(&tmp_a);
        funcs::DefaultElementwiseOperator<Context,
                                          T,
                                          funcs::MultiplyFunctor<T>,
                                          funcs::InverseMultiplyFunctor<T>>(
            dev_ctx, x, ddy_safe, &tmp_a, axis);

        auto ddout_t1 = phi::EigenVector<T>::Flatten(tmp_a);

        funcs::DefaultElementwiseOperator<Context,
                                          T,
                                          funcs::MultiplyFunctor<T>,
                                          funcs::InverseMultiplyFunctor<T>>(
            dev_ctx, ddx_safe, y, ddout, axis);

        auto ddout_t2 = phi::EigenVector<T>::Flatten(*ddout);
        ddout_t2.device(place) = ddout_t2 + ddout_t1;

        // NOTE: in the following ElemwiseGradCompute, for the
        // first output tensor is nullptr, the branch to calculate first
        // output tensor will not be activated, DivGradDx function will not
        // be called and can be ignored, the first branch has little effect
        // on running speed.
        phi::funcs::ElemwiseGradCompute<Context, T, MulGradDX<T>, MulGradDY<T>>(
            dev_ctx,
            ddx_safe,
            ddy_safe,
            dout,
            dout,
            axis,
            nullptr,
            dy,
            MulGradDX<T>(),
            MulGradDY<T>());
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
      } else {
        DenseTensor tmp_a(ddout->dtype());
        tmp_a.Resize(ddout->dims());

        dev_ctx.template Alloc<T>(&tmp_a);

        funcs::DefaultElementwiseOperator<Context,
                                          T,
                                          funcs::MultiplyFunctor<T>,
                                          funcs::InverseMultiplyFunctor<T>>(
            dev_ctx, x, ddy_safe, &tmp_a, axis);

        auto ddout_t1 = phi::EigenVector<T>::Flatten(tmp_a);

        funcs::DefaultElementwiseOperator<Context,
                                          T,
                                          funcs::MultiplyFunctor<T>,
                                          funcs::InverseMultiplyFunctor<T>>(
            dev_ctx, ddx_safe, y, ddout, axis);

        auto ddout_t2 = phi::EigenVector<T>::Flatten(*ddout);
        ddout_t2.device(place) = ddout_t2 + ddout_t1;
      }
Y
YuanRisheng 已提交
593
    }
594
  } else {
595 596 597 598 599 600 601 602 603 604 605 606
    VLOG(3) << "Calculating here with dx: " << dx << ", dy: " << dy;
    phi::funcs::ElemwiseGradCompute<Context, T, MulGradDX<T>, MulGradDY<T>>(
        dev_ctx,
        ddx_safe,
        ddy_safe,
        dout,
        dout,
        axis,
        dx,
        dy,
        MulGradDX<T>(),
        MulGradDY<T>());
Y
YuanRisheng 已提交
607 608 609 610 611 612 613 614
  }
}

template <typename T, typename Context>
void MultiplyTripleGradKernel(const Context& dev_ctx,
                              const DenseTensor& x,
                              const DenseTensor& y,
                              const DenseTensor& dout,
615 616
                              const paddle::optional<DenseTensor>& ddx,
                              const paddle::optional<DenseTensor>& ddy,
617 618
                              const paddle::optional<DenseTensor>& d_dx,
                              const paddle::optional<DenseTensor>& d_dy,
619
                              const paddle::optional<DenseTensor>& d_ddout,
Y
YuanRisheng 已提交
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
                              int axis,
                              DenseTensor* d_x,
                              DenseTensor* d_y,
                              DenseTensor* d_dout,
                              DenseTensor* d_ddx,
                              DenseTensor* d_ddy) {
  if (d_x) {
    d_x->Resize(x.dims());
    dev_ctx.template Alloc<T>(d_x);
  }
  if (d_y) {
    d_y->Resize(y.dims());
    dev_ctx.template Alloc<T>(d_y);
  }
  if (d_dout) {
    d_dout->Resize(dout.dims());
    dev_ctx.template Alloc<T>(d_dout);
  }
  if (d_ddx) {
    d_ddx->Resize(x.dims());
    dev_ctx.template Alloc<T>(d_ddx);
  }
  if (d_ddy) {
    d_ddy->Resize(y.dims());
    dev_ctx.template Alloc<T>(d_ddy);
  }

  auto& place = *dev_ctx.eigen_device();

  DenseTensor ddx_safe, ddy_safe;
  funcs::GetDoubleGradSafeTensor<Context, T>(
      dev_ctx, x, ddx.get_ptr(), &ddx_safe);
  funcs::GetDoubleGradSafeTensor<Context, T>(
      dev_ctx, y, ddy.get_ptr(), &ddy_safe);

  if (d_ddout.get_ptr()) {
    if (d_x) {
      // d_x = ddy * d_ddout
      funcs::DefaultElementwiseOperator<Context,
                                        T,
                                        funcs::MultiplyFunctor<T>,
                                        funcs::InverseMultiplyFunctor<T>>(
          dev_ctx, ddy_safe, *(d_ddout.get_ptr()), d_x, axis);
    }
    if (d_y) {
      // d_y = ddx * d_ddout
      funcs::DefaultElementwiseOperator<Context,
                                        T,
                                        funcs::MultiplyFunctor<T>,
                                        funcs::InverseMultiplyFunctor<T>>(
          dev_ctx, ddx_safe, *(d_ddout.get_ptr()), d_y, axis);
    }
672 673 674 675 676 677 678
  } else {
    if (d_x) {
      FullLikeKernel<T, Context>(dev_ctx, x, Scalar(0.0), x.dtype(), d_x);
    }
    if (d_y) {
      FullLikeKernel<T, Context>(dev_ctx, y, Scalar(0.0), y.dtype(), d_y);
    }
Y
YuanRisheng 已提交
679 680 681 682 683 684 685 686
  }

  if (d_dout) {
    // get d_dout
    // d_dout = ddy * d_dx + d_dy * ddx
    DenseTensor d_dout_tmp;
    d_dout_tmp.Resize(dout.dims());
    dev_ctx.template Alloc<T>(&d_dout_tmp);
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724

    if (d_dy && d_dx) {
      funcs::DefaultElementwiseOperator<Context,
                                        T,
                                        funcs::MultiplyFunctor<T>,
                                        funcs::InverseMultiplyFunctor<T>>(
          dev_ctx, d_dy.get(), ddx_safe, d_dout, axis);

      funcs::DefaultElementwiseOperator<Context,
                                        T,
                                        funcs::MultiplyFunctor<T>,
                                        funcs::InverseMultiplyFunctor<T>>(
          dev_ctx, ddy_safe, d_dx.get(), &d_dout_tmp, axis);

      auto d_dout_t = phi::EigenVector<T>::Flatten(*d_dout);
      auto d_dout_tmp_t = phi::EigenVector<T>::Flatten(d_dout_tmp);
      d_dout_t.device(place) = d_dout_t + d_dout_tmp_t;
    } else if (d_dy && !d_dx) {
      funcs::DefaultElementwiseOperator<Context,
                                        T,
                                        funcs::MultiplyFunctor<T>,
                                        funcs::InverseMultiplyFunctor<T>>(
          dev_ctx, d_dy.get(), ddx_safe, d_dout, axis);
      auto d_dout_t = phi::EigenVector<T>::Flatten(*d_dout);
      d_dout_t.device(place) = d_dout_t;
    } else if (!d_dy && d_dx) {
      funcs::DefaultElementwiseOperator<Context,
                                        T,
                                        funcs::MultiplyFunctor<T>,
                                        funcs::InverseMultiplyFunctor<T>>(
          dev_ctx, ddy_safe, d_dx.get(), d_dout, axis);

      auto d_dout_t = phi::EigenVector<T>::Flatten(*d_dout);
      d_dout_t.device(place) = d_dout_t;
    } else {
      FullLikeKernel<T, Context>(
          dev_ctx, dout, Scalar(0.0), dout.dtype(), d_dout);
    }
Y
YuanRisheng 已提交
725 726
  }

727
  if (d_ddx && ddx) {
Y
YuanRisheng 已提交
728 729 730 731 732
    // get d_ddx
    // d_ddx = dout * d_dy + y * d_ddout
    DenseTensor d_ddx_tmp;
    d_ddx_tmp.Resize(ddx->dims());
    dev_ctx.template Alloc<T>(&d_ddx_tmp);
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
    if (d_dy && d_ddout) {
      funcs::DefaultElementwiseOperator<Context,
                                        T,
                                        funcs::MultiplyFunctor<T>,
                                        funcs::InverseMultiplyFunctor<T>>(
          dev_ctx, dout, d_dy.get(), d_ddx, axis);

      funcs::DefaultElementwiseOperator<Context,
                                        T,
                                        funcs::MultiplyFunctor<T>,
                                        funcs::InverseMultiplyFunctor<T>>(
          dev_ctx, y, *(d_ddout.get_ptr()), &d_ddx_tmp, axis);

      auto d_ddx_t = phi::EigenVector<T>::Flatten(*d_ddx);
      auto d_ddx_tmp_t = phi::EigenVector<T>::Flatten(d_ddx_tmp);
      d_ddx_t.device(place) = d_ddx_t + d_ddx_tmp_t;
    } else if (d_dy && !d_ddout) {
      funcs::DefaultElementwiseOperator<Context,
                                        T,
                                        funcs::MultiplyFunctor<T>,
                                        funcs::InverseMultiplyFunctor<T>>(
          dev_ctx, dout, d_dy.get(), d_ddx, axis);

      auto d_ddx_t = phi::EigenVector<T>::Flatten(*d_ddx);
      d_ddx_t.device(place) = d_ddx_t;
    } else if (!d_dy && d_ddout) {
      funcs::DefaultElementwiseOperator<Context,
                                        T,
                                        funcs::MultiplyFunctor<T>,
                                        funcs::InverseMultiplyFunctor<T>>(
          dev_ctx, y, *(d_ddout.get_ptr()), d_ddx, axis);

      auto d_ddx_t = phi::EigenVector<T>::Flatten(*d_ddx);
      d_ddx_t.device(place) = d_ddx_t;
    } else {
      FullLikeKernel<T, Context>(dev_ctx, x, Scalar(0.0), x.dtype(), d_ddx);
    }
Y
YuanRisheng 已提交
770 771
  }

772
  if (d_ddy && ddy) {
Y
YuanRisheng 已提交
773 774 775 776 777
    // get d_ddy
    // d_ddy = dout * d_dx + x * d_ddout
    DenseTensor d_ddy_tmp;
    d_ddy_tmp.Resize(ddy->dims());
    dev_ctx.template Alloc<T>(&d_ddy_tmp);
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815

    if (d_dx && d_ddout) {
      funcs::DefaultElementwiseOperator<Context,
                                        T,
                                        funcs::MultiplyFunctor<T>,
                                        funcs::InverseMultiplyFunctor<T>>(
          dev_ctx, dout, d_dx.get(), d_ddy, axis);

      funcs::DefaultElementwiseOperator<Context,
                                        T,
                                        funcs::MultiplyFunctor<T>,
                                        funcs::InverseMultiplyFunctor<T>>(
          dev_ctx, x, *(d_ddout.get_ptr()), &d_ddy_tmp, axis);

      auto d_ddy_t = phi::EigenVector<T>::Flatten(*d_ddy);
      auto d_ddy_tmp_t = phi::EigenVector<T>::Flatten(d_ddy_tmp);
      d_ddy_t.device(place) = d_ddy_t + d_ddy_tmp_t;
    } else if (d_dx && !d_ddout) {
      funcs::DefaultElementwiseOperator<Context,
                                        T,
                                        funcs::MultiplyFunctor<T>,
                                        funcs::InverseMultiplyFunctor<T>>(
          dev_ctx, dout, d_dx.get(), d_ddy, axis);

      auto d_ddy_t = phi::EigenVector<T>::Flatten(*d_ddy);
      d_ddy_t.device(place) = d_ddy_t;
    } else if (!d_dx && d_ddout) {
      funcs::DefaultElementwiseOperator<Context,
                                        T,
                                        funcs::MultiplyFunctor<T>,
                                        funcs::InverseMultiplyFunctor<T>>(
          dev_ctx, x, *(d_ddout.get_ptr()), d_ddy, axis);

      auto d_ddy_t = phi::EigenVector<T>::Flatten(*d_ddy);
      d_ddy_t.device(place) = d_ddy_t;
    } else {
      FullLikeKernel<T, Context>(dev_ctx, y, Scalar(0.0), y.dtype(), d_ddy);
    }
Y
YuanRisheng 已提交
816 817 818
  }
}

819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
/*
******************************
    Maximum Grad
******************************
*/

template <typename T>
struct MaxGradDx {
  HOSTDEVICE T operator()(T x, T y, T out, T dout) const {
    return dout * static_cast<T>(x > y);
  }
};

template <typename T>
struct MaxGradDy {
  HOSTDEVICE T operator()(T x, T y, T out, T dout) const {
    return dout * static_cast<T>(x <= y);
  }
};

/*
******************************
    Minimum Grad
******************************
*/
template <typename T>
struct MinGradDx {
  HOSTDEVICE T operator()(T x, T y, T out, T dout) const {
    return dout * static_cast<T>(x < y);
  }
};

template <typename T>
struct MinGradDy {
  HOSTDEVICE T operator()(T x, T y, T out, T dout) const {
    return dout * static_cast<T>(x >= y);
  }
};
857

858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
template <typename T>
struct HeavisideGradDx {
  HOSTDEVICE T operator()(T x, T y, T out, T dout) const {
    return dout * static_cast<T>(0);
  }
};

template <typename T>
struct HeavisideGradDy {
  HOSTDEVICE T operator()(T x, T y, T out, T dout) const {
    return dout * static_cast<T>(x == static_cast<T>(0));
  }
};

template <typename T, typename Context>
873 874 875 876 877 878
void HeavisideGradKernel(const Context& dev_ctx,
                         const DenseTensor& x,
                         const DenseTensor& y,
                         const DenseTensor& dout,
                         DenseTensor* dx,
                         DenseTensor* dy) {
879 880 881 882 883 884 885 886
  funcs::ElementwiseGradPreProcess(dout, dx);
  phi::funcs::
      ElemwiseGradCompute<Context, T, HeavisideGradDx<T>, HeavisideGradDy<T>>(
          dev_ctx,
          x,
          y,
          dout,
          dout,
887
          -1,
888 889 890 891 892 893
          dx,
          dy,
          HeavisideGradDx<T>(),
          HeavisideGradDy<T>());
}

894
#if defined(__CUDA_ARCH__) || defined(__HIPCC__)
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
template <typename T, typename MPType>
HOSTDEVICE typename std::enable_if<std::is_integral<T>::value, T>::type
compute_pow_grad_dx(T x, T y, T out, T dout) {
  return dout * y *
         std::pow(static_cast<double>(x), static_cast<double>(y - 1));
}
template <typename T, typename MPType>
HOSTDEVICE typename std::enable_if<!std::is_integral<T>::value, T>::type
compute_pow_grad_dx(T x, T y, T out, T dout) {
  MPType x_val = static_cast<MPType>(x);
  MPType y_val = static_cast<MPType>(y);
  return static_cast<T>(static_cast<MPType>(dout) * y_val *
                        std::pow(x_val, y_val - 1));
}
template <typename T, typename MPType>
HOSTDEVICE typename std::enable_if<std::is_integral<T>::value, T>::type
compute_pow_grad_dy(T x, T y, T out, T dout) {
  return dout * std::log(static_cast<double>(x)) *
         std::pow(static_cast<double>(x), static_cast<double>(y));
}
template <typename T, typename MPType>
HOSTDEVICE typename std::enable_if<!std::is_integral<T>::value, T>::type
compute_pow_grad_dy(T x, T y, T out, T dout) {
  MPType x_val = static_cast<MPType>(x);
  MPType y_val = static_cast<MPType>(y);
  return static_cast<T>(static_cast<MPType>(dout) * std::log(x_val) *
                        std::pow(x_val, y_val));
}
#else
template <typename T, typename MPType>
HOSTDEVICE T compute_pow_grad_dx(T x, T y, T out, T dout) {
  MPType x_val = static_cast<MPType>(x);
  MPType y_val = static_cast<MPType>(y);
  return static_cast<T>(static_cast<MPType>(dout) * y_val *
                        std::pow(x_val, y_val - 1));
}
template <typename T, typename MPType>
HOSTDEVICE T compute_pow_grad_dy(T x, T y, T out, T dout) {
  MPType x_val = static_cast<MPType>(x);
  MPType y_val = static_cast<MPType>(y);
  return static_cast<T>(static_cast<MPType>(dout) * std::log(x_val) *
                        std::pow(x_val, y_val));
}
938 939
#endif

940 941 942 943 944
template <typename T>
struct PowGradDX {
  using MPType = typename phi::dtype::MPTypeTrait<T>::Type;
  HOSTDEVICE T operator()(T x, T y, T out, T dout) const {
    return compute_pow_grad_dx<T, MPType>(x, y, out, dout);
945 946 947
  }
};

948 949
template <typename T, typename Enable = void>
struct PowGradDY {
950
  using MPType = typename phi::dtype::MPTypeTrait<T>::Type;
951
  HOSTDEVICE T operator()(T x, T y, T out, T dout) const {
952
    return compute_pow_grad_dy<T, MPType>(x, y, out, dout);
953 954 955
  }
};

956 957 958 959 960 961 962 963
template <typename T, typename Context>
void ElementwisePowGradKernel(const Context& dev_ctx,
                              const DenseTensor& x,
                              const DenseTensor& y,
                              const DenseTensor& dout,
                              DenseTensor* dx,
                              DenseTensor* dy) {
  funcs::ElementwiseGradPreProcess(dout, dx);
964
  int axis = -1;
965 966 967 968
  phi::funcs::ElemwiseGradCompute<Context, T, PowGradDX<T>, PowGradDY<T>>(
      dev_ctx, x, y, dout, dout, axis, dx, dy, PowGradDX<T>(), PowGradDY<T>());
}

969
}  // namespace phi