elementwise_op_function.h 55.5 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
2

L
Luo Tao 已提交
3 4 5
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
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
8

L
Luo Tao 已提交
9 10 11 12 13
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. */
14 15

#pragma once
16

17
#include <glog/logging.h>
18

19
#include <algorithm>
20
#include <functional>  // for multiplies
D
dzhwinter 已提交
21
#include <iterator>
22
#include <vector>
23

Y
Yi Wang 已提交
24 25 26
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/operator.h"
27
#include "paddle/fluid/framework/phi_utils.h"
28
#include "paddle/fluid/memory/malloc.h"
29
#include "paddle/fluid/operators/elementwise/elementwise_functor.h"
30
#include "paddle/fluid/platform/device/gpu/gpu_info.h"
Y
Yi Wang 已提交
31
#include "paddle/fluid/platform/transform.h"
32
#include "paddle/phi/kernels/cpu/elementwise.h"
33
#include "paddle/phi/kernels/cpu/elementwise_grad.h"
34

35
#if defined(__NVCC__) || defined(__HIPCC__)
C
chengduoZH 已提交
36
#ifdef __NVCC__
37
#include <cuda.h>
38 39 40
#elif defined(__HIPCC__)
#include <hip/hip_runtime.h>
#endif
C
chengduoZH 已提交
41
#include <thrust/iterator/iterator_adaptor.h>
42

43
#include "paddle/fluid/operators/elementwise/elementwise_op_broadcast.cu.h"
44
#include "paddle/fluid/operators/reduce_ops/reduce_op.cu.h"
45
#include "paddle/phi/backends/gpu/gpu_device_function.h"
46
#include "paddle/phi/backends/gpu/gpu_primitives.h"
47
#include "paddle/phi/kernels/gpu/elementwise_grad.h"
48

C
chengduoZH 已提交
49 50
#endif

Y
Yu Yang 已提交
51
#include "paddle/fluid/platform/for_range.h"
52
#include "paddle/phi/kernels/funcs/math_function.h"
53

54 55 56 57
#define DIVUP(x, y) (((x) + (y)-1) / (y))

#define ROUNDUP(x, y) (DIVUP((x), (y)) * (y))

58 59 60
namespace paddle {
namespace operators {

61
/*
62 63
 *  Pack input and output tensors into respective vectors with
 *  consideration of varible X`s class type.
64
 *  Input variable X is supported to be whether phi::DenseTensor or
65 66 67
 *  SelectedRows class type in this package function, once X
 *  was SelectedRows type, a valid pointer x_for_selectedrows
 *  is excepted to be passed in from op kernel for acquisition
68
 *  of the valid address of phi::DenseTensor created ahead in the function.
69
 */
70 71
template <typename OutT>
int PackTensorsIntoVector(const framework::ExecutionContext &ctx,
72 73 74
                          std::vector<const phi::DenseTensor *> *ins,
                          std::vector<phi::DenseTensor *> *outs,
                          phi::DenseTensor *x_for_selectedrows = nullptr) {
75
  int axis = -1;
76 77
  auto x_var = ctx.InputVar("X");
  PADDLE_ENFORCE_NOT_NULL(
78 79 80 81
      x_var,
      platform::errors::InvalidArgument(
          "Unable to get input Variable X, Variable name is %s.\n",
          ctx.InputName("X")));
82
  auto *y = ctx.Input<phi::DenseTensor>("Y");
83
  phi::DenseTensor *z;
84

85 86 87
  if (x_var->IsType<phi::DenseTensor>()) {
    auto *x = ctx.Input<phi::DenseTensor>("X");
    z = ctx.Output<phi::DenseTensor>("Out");
88
    ins->emplace_back(x);
89
  } else if (x_var->IsType<phi::SelectedRows>()) {
90 91
    PADDLE_ENFORCE_EQ(y->dims().size() == 1 && y->dims()[0] == 1,
                      true,
92 93 94 95 96 97 98 99 100 101
                      platform::errors::InvalidArgument(
                          "For elementwise_op, if X is Sparse, Y must be "
                          "scalar. But reveived the size of Y = %d.",
                          y->dims().size()));
    PADDLE_ENFORCE_NOT_NULL(
        x_for_selectedrows,
        platform::errors::InvalidArgument(
            "The parameter x_for_selectedrows is excepted to "
            "be valid, once input varible X`s class type is "
            "SelectedRows.\n"));
102 103
    auto &x_sele = x_var->Get<phi::SelectedRows>();
    auto out_sele = ctx.Output<phi::SelectedRows>("Out");
104 105 106 107 108 109
    *x_for_selectedrows = x_sele.value();
    out_sele->set_rows(x_sele.rows());
    out_sele->set_height(x_sele.height());
    out_sele->mutable_value()->Resize(x_sele.value().dims());
    out_sele->mutable_value()->mutable_data(ctx.GetPlace(),
                                            x_for_selectedrows->type());
110
    z = ctx.Output<phi::SelectedRows>("Out")->mutable_value();
111 112 113 114
    ins->emplace_back(x_for_selectedrows);
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "X's type[%s] is not supported by elementwise_op. X's type should be "
115
        "phi::DenseTensor or SelectedRows.",
116 117
        framework::ToTypeName(x_var->Type())));
  }
118
  z->mutable_data<OutT>(ctx.GetPlace());
119 120 121 122
  outs->emplace_back(z);

  if (y != nullptr) {
    ins->emplace_back(y);
123
    axis = ctx.HasAttr("axis") ? ctx.Attr<int>("axis") : -1;
124
  }
125
  return axis;
126 127
}

128 129
inline void GetBroadcastDimsArrays(const framework::DDim &x_dims,
                                   const framework::DDim &y_dims,
130 131 132 133
                                   int *x_dims_array,
                                   int *y_dims_array,
                                   int *out_dims_array,
                                   const int max_dim,
134
                                   const int axis) {
135 136 137 138 139 140 141
  phi::funcs::GetBroadcastDimsArrays(x_dims,
                                     y_dims,
                                     x_dims_array,
                                     y_dims_array,
                                     out_dims_array,
                                     max_dim,
                                     axis);
142
}
143

144
inline framework::DDim trim_trailing_singular_dims(
145
    const framework::DDim &dims) {
146
  return phi::funcs::TrimTrailingSingularDims(dims);
147 148
}

149 150 151 152
template <typename DeviceContext,
          typename T,
          typename DX_OP,
          typename DY_OP,
F
Feiyu Chan 已提交
153
          typename Tout = T>
154
void ElemwiseGradCompute(const framework::ExecutionContext &ctx,
155 156 157 158
                         const phi::DenseTensor &x,
                         const phi::DenseTensor &y,
                         const phi::DenseTensor &out,
                         const phi::DenseTensor &dout,
159
                         int axis,
160 161
                         phi::DenseTensor *dx,
                         phi::DenseTensor *dy,
162 163
                         DX_OP dx_op,
                         DY_OP dy_op) {
164
  const auto &dev_ctx = ctx.template device_context<DeviceContext>();
165 166
  phi::funcs::ElemwiseGradCompute<DeviceContext, T, DX_OP, DY_OP, Tout>(
      dev_ctx, x, y, out, dout, axis, dx, dy, dx_op, dy_op);
167 168
}

169 170 171 172
// It is a common implementation to compute binary calculation with the support
// of broadcast, supporting both CPU and GPU.
// - CPU implementation cannot support the case when x needs broadcast, thus
//   this function need to be called with XxxFunctor and XxxInverseFunctor,
173
//   like AddFunctor and InverseAddFunctor.
174 175 176 177
// - GPU implementation supports all the broadcast cases, thus there is no need
//   to define and call with XxxInverseFunctor.
// TODO(liuyiqun): optimize the CPU implementation to support all broadcast
// cases and avoid the need of XxxInverseFunctor.
178 179 180
template <typename Functor,
          typename DeviceContext,
          typename T,
181
          typename OutType = T>
182
void ElementwiseComputeEx(const framework::ExecutionContext &ctx,
183 184
                          const phi::DenseTensor *x,
                          const phi::DenseTensor *y,
185 186
                          int axis,
                          Functor func,
187
                          phi::DenseTensor *z) {
188
  z->mutable_data<OutType>(ctx.GetPlace());
189
  const auto &dev_ctx = ctx.template device_context<DeviceContext>();
190 191
  phi::funcs::ElementwiseCompute<Functor, T, OutType>(
      dev_ctx, *x, *y, axis, func, z);
F
fengjiayi 已提交
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
// FusedElemwiseAndAct
// --- forward
template <typename T, typename CompoundFunctor, bool KeepIntermediateOut>
struct FusedElemwiseAndActNoBroadcast {
  HOSTDEVICE void operator()(size_t i) {
    T y_val = y_[i];
    T x_val = x_[i];
    if (KeepIntermediateOut) {
      T intermeidiate_out = compound_functor_.GetIntermediateOut(x_val, y_val);
      intermediate_out_[i] = intermeidiate_out;
      out_[i] =
          compound_functor_.GetOutUseIntermediateOut(x_val, intermeidiate_out);
    } else {
      out_[i] = compound_functor_.GetOut(x_val, y_val);
    }
  }

  const T *x_;
  const T *y_;
  CompoundFunctor compound_functor_;
  T *out_;
  T *intermediate_out_;
};

// FusedElemwiseAndActBroadcast1:
// In this case, X and Y can be reshaped to a matrix.
// For example shape(X) = (2, 3, 4, 5), shape(Y) = (4, 5) and axis = -1 or 2,
// X can be reshaped to (6, 20) and Y can be reshaped to (1, 20)
222 223 224 225 226 227 228
template <typename T,
          typename CompoundFunctor,
          bool BcastY,
          bool KeepIntermediateOut,
          bool SameShapeOfIntermediateOutAndOut>
static void FusedElemwiseAndActBroadcast1CPU(const T *x,
                                             const T *y,
229
                                             CompoundFunctor compound_functor,
230 231 232
                                             int h,
                                             int w,
                                             T *out,
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 266 267
                                             T *intermediate_out) {
  for (int i = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j) {
      int offset = i * w + j;

      T y_val = BcastY ? y[j] : y[offset];
      T x_val = BcastY ? x[offset] : x[j];
      int64_t intermediate_out_offset;
      if (KeepIntermediateOut) {
        T intermeidiate_out = compound_functor.GetIntermediateOut(x_val, y_val);

        if (SameShapeOfIntermediateOutAndOut) {
          // for the case of f1(f2(x, y))
          intermediate_out_offset = offset;
        } else if (BcastY) {
          intermediate_out_offset = j;
        } else {
          intermediate_out_offset = offset;
        }

        intermediate_out[intermediate_out_offset] = intermeidiate_out;
        out[offset] =
            compound_functor.GetOutUseIntermediateOut(x_val, intermeidiate_out);
      } else {
        out[offset] = compound_functor.GetOut(x_val, y_val);
      }
    }
  }
}

// FusedElemwiseAndActBroadcast2
// In this case, X and Y can be reshaped to a matrix.
// For example shape(X) = (2, 3, 4, 5), shape(Y) = (3, 4) and axis = 1,
// X can be reshaped to (2, 12, 5) and Y can be reshaped to (1, 12, 1)
// pre = 2, n = 12, post = 5
268 269 270 271 272 273 274 275 276 277
template <typename T,
          typename CompoundFunctor,
          bool BcastY,
          bool KeepIntermediateOut,
          bool SameShapeOfIntermediateOutAndOut>
static void FusedElemwiseAndActBroadcast2CPU(const T *x,
                                             const T *y,
                                             int pre,
                                             int n,
                                             int post,
278
                                             CompoundFunctor compound_functor,
279 280
                                             T *out,
                                             T *intermediate_out) {
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
  for (int i = 0; i < pre; ++i) {
    for (int j = 0; j < n; ++j) {
      for (int k = 0; k < post; ++k) {
        int offset = i * n * post + j * post + k;

        T y_val = BcastY ? y[j] : y[offset];
        T x_val = BcastY ? x[offset] : x[j];
        int64_t intermediate_out_offset;

        if (KeepIntermediateOut) {
          T intermeidiate_out =
              compound_functor.GetIntermediateOut(x_val, y_val);

          if (SameShapeOfIntermediateOutAndOut) {
            // for the case of f1(f2(x, y))
            intermediate_out_offset = offset;
          } else if (BcastY) {
            intermediate_out_offset = j;
          } else {
            intermediate_out_offset = offset;
          }

          intermediate_out[intermediate_out_offset] = intermeidiate_out;
          out[offset] = compound_functor.GetOutUseIntermediateOut(
              x_val, intermeidiate_out);
        } else {
          out[offset] = compound_functor.GetOut(x_val, y_val);
        }
      }
    }
  }
}

314
#if defined(__NVCC__) || defined(__HIPCC__)
315 316 317 318 319
template <typename T,
          typename CompoundFunctor,
          bool BcastY,
          bool KeepIntermediateOut,
          bool SameShapeOfIntermediateOutAndOut>
320
static __global__ void FusedElemwiseAndActBroadcast1CUDAKernel(
321 322 323 324 325 326 327
    const T *x,
    const T *y,
    int h,
    int w,
    CompoundFunctor compound_functor,
    T *out,
    T *intermediate_out) {
328 329
  int i = blockIdx.x;
  int j = threadIdx.x;
330

331
  while (j < w) {
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
    int offset = i * w + j;

    T y_val = BcastY ? y[j] : y[offset];
    T x_val = BcastY ? x[offset] : x[j];
    int64_t intermediate_out_offset;

    if (KeepIntermediateOut) {
      T intermeidiate_out = compound_functor.GetIntermediateOut(x_val, y_val);

      if (SameShapeOfIntermediateOutAndOut) {
        // for the case of f1(f2(x, y))
        intermediate_out_offset = offset;
      } else if (BcastY) {
        intermediate_out_offset = j;
      } else {
        intermediate_out_offset = offset;
      }

      intermediate_out[intermediate_out_offset] = intermeidiate_out;
      out[offset] =
          compound_functor.GetOutUseIntermediateOut(x_val, intermeidiate_out);
    } else {
      out[offset] = compound_functor.GetOut(x_val, y_val);
    }

357
    j += ELEMWISE_MAX_BLOCK_DIM;
358 359 360
  }
}

361 362 363 364 365 366 367
template <typename T,
          typename CompoundFunctor,
          bool BcastY,
          bool KeepIntermediateOut,
          bool SameShapeOfIntermediateOutAndOut>
static void FusedElemwiseAndActBroadcast1CUDA(gpuStream_t stream,
                                              const T *x,
368 369
                                              const T *y,
                                              CompoundFunctor compound_functor,
370 371 372
                                              int h,
                                              int w,
                                              T *out,
373
                                              T *intermediate_out) {
374 375
  int block_size = std::min(ELEMWISE_MAX_BLOCK_DIM, w);
  int gird_size = h;
376 377 378
  FusedElemwiseAndActBroadcast1CUDAKernel<T,
                                          CompoundFunctor,
                                          BcastY,
379 380
                                          KeepIntermediateOut,
                                          SameShapeOfIntermediateOutAndOut>
381 382
      <<<gird_size, block_size, 0, stream>>>(
          x, y, h, w, compound_functor, out, intermediate_out);
383 384
}

385 386 387 388 389
template <typename T,
          typename CompoundFunctor,
          bool BcastY,
          bool KeepIntermediateOut,
          bool SameShapeOfIntermediateOutAndOut>
390
static __global__ void FusedElemwiseAndActBroadcast2CUDAKernel(
391 392 393 394 395 396 397 398
    const T *x,
    const T *y,
    CompoundFunctor compound_functor,
    int pre,
    int n,
    int post,
    T *out,
    T *intermediate_out) {
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
  int tid = threadIdx.x;
  int j = blockIdx.x;

  while (true) {
    int i = tid / post;
    int k = tid % post;
    if (i >= pre) break;

    int offset = i * n * post + j * post + k;

    T y_val = BcastY ? y[j] : y[offset];
    T x_val = BcastY ? x[offset] : x[j];
    int64_t intermediate_out_offset;

    if (KeepIntermediateOut) {
      T intermeidiate_out = compound_functor.GetIntermediateOut(x_val, y_val);

      if (SameShapeOfIntermediateOutAndOut) {
        // for the case of f1(f2(x, y))
        intermediate_out_offset = offset;
      } else if (BcastY) {
        intermediate_out_offset = j;
      } else {
        intermediate_out_offset = offset;
      }

      intermediate_out[intermediate_out_offset] = intermeidiate_out;
      out[offset] =
          compound_functor.GetOutUseIntermediateOut(x_val, intermeidiate_out);
    } else {
      out[offset] = compound_functor.GetOut(x_val, y_val);
    }

    tid += ELEMWISE_MAX_BLOCK_DIM;
  }
}

436 437 438 439 440 441 442 443 444 445
template <typename T,
          typename CompoundFunctor,
          bool BcastY,
          bool KeepIntermediateOut,
          bool SameShapeOfIntermediateOutAndOut>
static void FusedElemwiseAndActBroadcast2CUDA(gpuStream_t stream,
                                              const T *x,
                                              const T *y,
                                              int pre,
                                              int n,
446 447
                                              int post,
                                              CompoundFunctor compound_functor,
448 449
                                              T *out,
                                              T *intermediate_out) {
450 451 452
  int block_size = std::min(ELEMWISE_MAX_BLOCK_DIM, pre * post);
  int gird_size = n;

453 454 455
  FusedElemwiseAndActBroadcast2CUDAKernel<T,
                                          CompoundFunctor,
                                          BcastY,
456 457
                                          KeepIntermediateOut,
                                          SameShapeOfIntermediateOutAndOut>
458 459
      <<<gird_size, block_size, 0, stream>>>(
          x, y, compound_functor, pre, n, post, out, intermediate_out);
460 461 462 463
}

#endif

464 465 466
template <typename DeviceContext,
          typename T,
          typename CompoundFunctor,
467 468
          bool KeepIntermediateOut>
void FusedElemwiseAndActComputeNoBroadcast(
469 470
    const framework::ExecutionContext &ctx,
    const framework::DDim &x_dim,
471 472
    const phi::DenseTensor &x,
    const phi::DenseTensor &y,
473
    CompoundFunctor compound_functor,
474 475
    phi::DenseTensor *out,
    phi::DenseTensor *intermediate_out) {
476
  size_t N = static_cast<size_t>(phi::product(x_dim));
477 478 479 480 481 482

  platform::ForRange<DeviceContext> for_range(
      ctx.template device_context<DeviceContext>(), N);

  for_range(
      FusedElemwiseAndActNoBroadcast<T, CompoundFunctor, KeepIntermediateOut>{
483 484 485
          x.data<T>(),
          y.data<T>(),
          compound_functor,
486 487 488 489 490 491
          out->mutable_data<T>(ctx.GetPlace()),
          intermediate_out == nullptr
              ? nullptr
              : intermediate_out->mutable_data<T>(ctx.GetPlace())});
}

492 493 494 495 496
template <typename DeviceContext,
          typename T,
          typename CompoundFunctor,
          bool BcastY,
          bool KeepIntermediateOut,
497 498
          bool SameShapeOfIntermediateOutAndOut>
void FusedElemwiseAndActComputeWithBroadcast(
499 500 501
    const framework::ExecutionContext &ctx,
    const framework::DDim &x_dim,
    const framework::DDim &y_dim_untrimed,
502 503
    const phi::DenseTensor &x,
    const phi::DenseTensor &y,
504 505
    CompoundFunctor compound_functor,
    int axis,
506 507
    phi::DenseTensor *out,
    phi::DenseTensor *intermediate_out) {
508 509 510 511
  axis = (axis == -1 ? x_dim.size() - y_dim_untrimed.size() : axis);
  auto y_dim = trim_trailing_singular_dims(y_dim_untrimed);
  axis = (y_dim.size() == 0) ? x_dim.size() : axis;

512
  int pre, n, post, is_run_common_broadcast;
513 514
  phi::funcs::GetMidDims(
      x_dim, y_dim, axis, &pre, &n, &post, &is_run_common_broadcast);
515 516 517 518
  if (post == 1) {
    int h = pre;
    int w = n;
    if (platform::is_gpu_place(ctx.GetPlace())) {
519
#if defined(__NVCC__) || defined(__HIPCC__)
520 521 522
      FusedElemwiseAndActBroadcast1CUDA<T,
                                        CompoundFunctor,
                                        BcastY,
523 524
                                        KeepIntermediateOut,
                                        SameShapeOfIntermediateOutAndOut>(
525 526 527 528 529 530
          ctx.template device_context<DeviceContext>().stream(),
          x.data<T>(),
          y.data<T>(),
          compound_functor,
          h,
          w,
531 532 533 534 535 536
          out->mutable_data<T>(ctx.GetPlace()),
          intermediate_out == nullptr
              ? nullptr
              : intermediate_out->mutable_data<T>(ctx.GetPlace()));
#endif
    } else {
537 538 539
      FusedElemwiseAndActBroadcast1CPU<T,
                                       CompoundFunctor,
                                       BcastY,
540 541
                                       KeepIntermediateOut,
                                       SameShapeOfIntermediateOutAndOut>(
542 543 544 545 546
          x.data<T>(),
          y.data<T>(),
          compound_functor,
          h,
          w,
547 548 549 550 551 552 553
          out->mutable_data<T>(ctx.GetPlace()),
          intermediate_out == nullptr
              ? nullptr
              : intermediate_out->mutable_data<T>(ctx.GetPlace()));
    }
  } else {
    if (platform::is_gpu_place(ctx.GetPlace())) {
554
#if defined(__NVCC__) || defined(__HIPCC__)
555 556 557
      FusedElemwiseAndActBroadcast2CUDA<T,
                                        CompoundFunctor,
                                        BcastY,
558 559
                                        KeepIntermediateOut,
                                        SameShapeOfIntermediateOutAndOut>(
560 561 562 563 564 565 566
          ctx.template device_context<DeviceContext>().stream(),
          x.data<T>(),
          y.data<T>(),
          pre,
          n,
          post,
          compound_functor,
567 568 569 570 571 572
          out->mutable_data<T>(ctx.GetPlace()),
          intermediate_out == nullptr
              ? nullptr
              : intermediate_out->mutable_data<T>(ctx.GetPlace()));
#endif
    } else {
573 574 575
      FusedElemwiseAndActBroadcast2CPU<T,
                                       CompoundFunctor,
                                       BcastY,
576 577
                                       KeepIntermediateOut,
                                       SameShapeOfIntermediateOutAndOut>(
578 579 580 581 582 583
          x.data<T>(),
          y.data<T>(),
          pre,
          n,
          post,
          compound_functor,
584 585 586 587 588 589 590 591 592
          out->mutable_data<T>(ctx.GetPlace()),
          intermediate_out == nullptr
              ? nullptr
              : intermediate_out->mutable_data<T>(ctx.GetPlace()));
    }
  }
}

// --- backward
593 594 595 596
template <typename T,
          typename DX_OP,
          typename DY_OP,
          typename DIntermediate_OP,
C
chengduo 已提交
597
          bool UseIntermediateOut>
598 599
struct FusedElemwiseAndActGradNoBroadcast {
  HOSTDEVICE void operator()(size_t i) {
600 601 602
    T zero = static_cast<T>(0);
    T x_val = (x_ == nullptr) ? zero : x_[i];
    T y_val = (y_ == nullptr) ? zero : y_[i];
603 604 605 606 607
    T out_val = out_[i];
    T dout_val = dout_[i];
    T intermediate_out_val = UseIntermediateOut
                                 ? intermediate_out_[i]
                                 : dx_op_.GetIntermediateOut(x_val, y_val);
608
    if (dx_ != nullptr) {
609 610
      dx_[i] = dx_op_.UseIntermediateOut(
          x_val, y_val, intermediate_out_val, out_val, dout_val);
611 612
    }
    if (dy_ != nullptr) {
613 614
      dy_[i] = dy_op_.UseIntermediateOut(
          x_val, y_val, intermediate_out_val, out_val, dout_val);
C
chengduo 已提交
615 616
    }
    if (dintermediate_ != nullptr) {
617 618
      dintermediate_[i] = dintermediate_op_.UseIntermediateOut(
          x_val, intermediate_out_val, out_val, dout_val);
619 620 621 622 623 624 625 626 627 628
    }
  }

  const T *x_;
  const T *y_;
  const T *intermediate_out_;
  const T *out_;
  const T *dout_;
  DX_OP dx_op_;
  DY_OP dy_op_;
C
chengduo 已提交
629
  DIntermediate_OP dintermediate_op_;
630 631
  T *dx_;
  T *dy_;
C
chengduo 已提交
632
  T *dintermediate_;
633 634
};

635 636 637 638 639 640
template <typename DeviceContext,
          typename T,
          typename DX_OP,
          typename DY_OP,
          typename DIntermediate_OP,
          bool UseIntermediateOut>
641
void FusedElemwiseAndActGradComputeNoBroadcast(
642 643 644
    const framework::ExecutionContext &ctx,
    const framework::DDim &x_dim,
    const framework::DDim &y_dim,
645 646 647 648 649
    const phi::DenseTensor *x,
    const phi::DenseTensor *y,
    const phi::DenseTensor *intermediate_out,
    const phi::DenseTensor *out,
    const phi::DenseTensor *dout,
650
    int axis,
651 652 653
    phi::DenseTensor *dx,
    phi::DenseTensor *dy,
    phi::DenseTensor *dintermediate,
654 655
    DX_OP dx_op,
    DY_OP dy_op,
C
chengduo 已提交
656
    DIntermediate_OP dintermediate_op) {
657
  size_t N = static_cast<size_t>(phi::product(x_dim));
658 659
  platform::ForRange<DeviceContext> for_range(
      ctx.template device_context<DeviceContext>(), N);
660 661 662 663 664
  const T *x_data = nullptr;
  const T *y_data = nullptr;
  if (x->IsInitialized()) x_data = x->data<T>();
  if (y->IsInitialized()) y_data = y->data<T>();

665 666 667 668 669 670 671 672 673 674 675 676 677
  for_range(FusedElemwiseAndActGradNoBroadcast<T,
                                               DX_OP,
                                               DY_OP,
                                               DIntermediate_OP,
                                               UseIntermediateOut>{
      x_data,
      y_data,
      intermediate_out ? intermediate_out->data<T>() : nullptr,
      out->data<T>(),
      dout->data<T>(),
      dx_op,
      dy_op,
      dintermediate_op,
678 679
      dx == nullptr ? nullptr : dx->mutable_data<T>(ctx.GetPlace()),
      dy == nullptr ? nullptr : dy->mutable_data<T>(ctx.GetPlace()),
680 681 682
      dintermediate == nullptr
          ? nullptr
          : dintermediate->mutable_data<T>(ctx.GetPlace())});
683 684
}

685 686 687 688 689 690
template <typename T,
          typename DX_OP,
          typename DY_OP,
          typename DIntermediate_OP,
          bool UseIntermediateOut,
          bool BcastY,
C
chengduo 已提交
691 692
          bool SameShapeOfIntermediateOutAndOut>
static void FusedElemwiseAndActGradBroadcast1CPU(
693 694 695 696 697 698 699 700 701 702 703 704 705
    const T *x,
    const T *y,
    const T *intermediate_out,
    const T *out,
    const T *dout,
    int h,
    int w,
    DX_OP dx_op,
    DY_OP dy_op,
    DIntermediate_OP dintermediate_op,
    T *dx,
    T *dy,
    T *d_intermediate) {
706
  int64_t tmp_out_idx, x_idx, y_idx;
707
  T zero = static_cast<T>(0);
708 709 710 711 712 713 714
  for (int i = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j) {
      int offset = i * w + j;

      tmp_out_idx = BcastY ? j : offset;
      y_idx = BcastY ? j : offset;
      x_idx = BcastY ? offset : j;
715 716
      T x_val = (x == nullptr) ? zero : x[x_idx];
      T y_val = (y == nullptr) ? zero : y[y_idx];
717 718 719 720 721 722 723

      if (SameShapeOfIntermediateOutAndOut) {
        tmp_out_idx = offset;
      }

      if (dx != nullptr) {
        T tmp = UseIntermediateOut
724 725
                    ? dx_op.UseIntermediateOut(x_val,
                                               y_val,
C
chengduo 已提交
726
                                               intermediate_out[tmp_out_idx],
727 728
                                               out[offset],
                                               dout[offset])
729
                    : dx_op.Recompute(x_val, y_val, out[offset], dout[offset]);
730 731 732 733 734 735 736 737 738 739 740 741 742

        if (BcastY) {
          dx[x_idx] = tmp;
        } else {
          if (i == 0) {
            dx[x_idx] = tmp;
          } else {
            dx[x_idx] += tmp;
          }
        }
      }
      if (dy != nullptr) {
        T tmp = UseIntermediateOut
743 744
                    ? dy_op.UseIntermediateOut(x_val,
                                               y_val,
C
chengduo 已提交
745
                                               intermediate_out[tmp_out_idx],
746 747
                                               out[offset],
                                               dout[offset])
748
                    : dy_op.Recompute(x_val, y_val, out[offset], dout[offset]);
749 750 751 752 753 754 755 756 757 758
        if (BcastY) {
          if (i == 0) {
            dy[y_idx] = tmp;
          } else {
            dy[y_idx] += tmp;
          }
        } else {
          dy[y_idx] = tmp;
        }
      }
C
chengduo 已提交
759
      if (d_intermediate != nullptr) {
760
        T tmp = UseIntermediateOut ? dintermediate_op.UseIntermediateOut(
761 762 763 764
                                         x_val,
                                         intermediate_out[tmp_out_idx],
                                         out[offset],
                                         dout[offset])
765 766
                                   : dintermediate_op.Recompute(
                                         x_val, y_val, out[offset], dout[i]);
C
chengduo 已提交
767 768 769 770 771 772 773 774 775 776
        if (SameShapeOfIntermediateOutAndOut) {
          d_intermediate[tmp_out_idx] = tmp;
        } else {
          if (i == 0) {
            d_intermediate[tmp_out_idx] = tmp;
          } else {
            d_intermediate[tmp_out_idx] += tmp;
          }
        }
      }
777 778 779 780
    }
  }
}

781 782 783 784 785 786
template <typename T,
          typename DX_OP,
          typename DY_OP,
          typename DIntermediate_OP,
          bool UseIntermediateOut,
          bool BcastY,
C
chengduo 已提交
787 788
          bool SameShapeOfIntermediateOutAndOut>
static void FusedElemwiseAndActGradBroadcast2CPU(
789 790 791 792 793 794 795 796 797 798 799 800 801 802
    const T *x,
    const T *y,
    const T *intermediate_out,
    const T *out,
    const T *dout,
    int pre,
    int n,
    int post,
    DX_OP dx_op,
    DY_OP dy_op,
    DIntermediate_OP dintermediate_op,
    T *dx,
    T *dy,
    T *d_intermediate) {
803
  int64_t tmp_out_idx, x_idx, y_idx;
804
  T zero = static_cast<T>(0);
805 806 807 808 809 810 811 812 813
  for (int i = 0; i < pre; ++i) {
    for (int j = 0; j < n; ++j) {
      for (int k = 0; k < post; ++k) {
        int offset = i * n * post + j * post + k;

        tmp_out_idx = BcastY ? j : offset;
        y_idx = BcastY ? j : offset;
        x_idx = BcastY ? offset : j;

814 815 816
        T x_val = (x == nullptr) ? zero : x[x_idx];
        T y_val = (y == nullptr) ? zero : y[y_idx];

817 818 819 820 821
        if (SameShapeOfIntermediateOutAndOut) {
          tmp_out_idx = offset;
        }

        if (dx != nullptr) {
822 823
          T tmp =
              UseIntermediateOut
824 825
                  ? dx_op.UseIntermediateOut(x_val,
                                             y_val,
826
                                             intermediate_out[tmp_out_idx],
827 828
                                             out[offset],
                                             dout[offset])
829
                  : dx_op.Recompute(x_val, y_val, out[offset], dout[offset]);
830 831 832 833 834 835 836 837 838 839 840 841

          if (BcastY) {
            dx[x_idx] = tmp;
          } else {
            if (i == 0 && k == 0) {
              dx[x_idx] = tmp;
            } else {
              dx[x_idx] += tmp;
            }
          }
        }
        if (dy != nullptr) {
842 843
          T tmp =
              UseIntermediateOut
844 845
                  ? dy_op.UseIntermediateOut(x_val,
                                             y_val,
846
                                             intermediate_out[tmp_out_idx],
847 848
                                             out[offset],
                                             dout[offset])
849
                  : dy_op.Recompute(x_val, y_val, out[offset], dout[offset]);
850 851 852 853 854 855 856 857 858 859
          if (BcastY) {
            if (i == 0 && k == 0) {
              dy[y_idx] = tmp;
            } else {
              dy[y_idx] += tmp;
            }
          } else {
            dy[y_idx] = tmp;
          }
        }
C
chengduo 已提交
860
        if (d_intermediate != nullptr) {
861
          T tmp = UseIntermediateOut ? dintermediate_op.UseIntermediateOut(
862 863 864 865
                                           x_val,
                                           intermediate_out[tmp_out_idx],
                                           out[offset],
                                           dout[offset])
866 867
                                     : dintermediate_op.Recompute(
                                           x_val, y_val, out[offset], dout[i]);
C
chengduo 已提交
868 869 870 871 872 873 874 875 876 877
          if (SameShapeOfIntermediateOutAndOut) {
            d_intermediate[tmp_out_idx] = tmp;
          } else {
            if (i == 0) {
              d_intermediate[tmp_out_idx] = tmp;
            } else {
              d_intermediate[tmp_out_idx] += tmp;
            }
          }
        }
878 879 880 881 882
      }
    }
  }
}

883
#if defined(__NVCC__) || defined(__HIPCC__)
884 885 886 887 888 889
template <typename T,
          typename DX_OP,
          typename DY_OP,
          typename DIntermediate_OP,
          bool UseIntermediateOut,
          bool BcastY,
C
chengduo 已提交
890
          bool SameShapeOfIntermediateOutAndOut>
891
static __global__ void FusedElemwiseAndActGradBroadcast1CUDAKernel(
892 893 894 895 896 897 898 899 900 901 902 903 904
    const T *x,
    const T *y,
    const T *intermediate_out,
    const T *out,
    const T *dout,
    int h,
    int w,
    DX_OP dx_op,
    DY_OP dy_op,
    DIntermediate_OP dintermediate_op,
    T *dx,
    T *dy,
    T *d_intermediate) {
905 906 907 908 909 910
  __shared__ T sdata[BLOCK_Y][BLOCK_X];
  size_t idx = threadIdx.x + BLOCK_X * blockIdx.x;
  size_t width_stride = gridDim.x * BLOCK_X;

  size_t full_w = ROUNDUP(w, BLOCK_X);

911
  T zero = static_cast<T>(0);
912

913 914 915 916 917
  for (size_t j = idx; j < full_w; j += width_stride) {
    T val(0), inter_val(0);
    if (j < w) {
      for (size_t i = threadIdx.y; i < h; i += BLOCK_Y) {
        size_t offset = i * w + j;
918

919 920 921 922 923
        size_t tmp_out_idx = BcastY ? j : offset;
        size_t y_idx = BcastY ? j : offset;
        size_t x_idx = BcastY ? offset : j;
        T x_val = (x == nullptr) ? zero : x[x_idx];
        T y_val = (y == nullptr) ? zero : y[y_idx];
924

925 926 927
        if (SameShapeOfIntermediateOutAndOut) {
          tmp_out_idx = offset;
        }
928

929 930 931
        if (dx != nullptr) {
          T tmp =
              UseIntermediateOut
932 933
                  ? dx_op.UseIntermediateOut(x_val,
                                             y_val,
934
                                             intermediate_out[tmp_out_idx],
935 936
                                             out[offset],
                                             dout[offset])
937
                  : dx_op.Recompute(x_val, y_val, out[offset], dout[offset]);
938

939 940 941 942 943 944 945 946 947
          if (BcastY) {
            dx[x_idx] = tmp;
          } else {
            val += tmp;
          }
        }
        if (dy != nullptr) {
          T tmp =
              UseIntermediateOut
948 949
                  ? dy_op.UseIntermediateOut(x_val,
                                             y_val,
950
                                             intermediate_out[tmp_out_idx],
951 952
                                             out[offset],
                                             dout[offset])
953
                  : dy_op.Recompute(x_val, y_val, out[offset], dout[offset]);
954 955 956 957 958 959 960 961 962
          if (BcastY) {
            val += tmp;
          } else {
            dy[y_idx] = tmp;
          }
        }
        if (d_intermediate != nullptr) {
          T tmp = UseIntermediateOut
                      ? dintermediate_op.UseIntermediateOut(
963 964 965 966 967 968
                            y[y_idx],
                            intermediate_out[tmp_out_idx],
                            out[offset],
                            dout[offset])
                      : dintermediate_op.Recompute(
                            x_val, y_val, out[offset], dout[offset]);
969 970 971 972 973 974
          if (SameShapeOfIntermediateOutAndOut) {
            d_intermediate[tmp_out_idx] = tmp;
          } else {
            inter_val += tmp;
          }
        }
C
chengduo 已提交
975 976
      }
    }
977

978 979 980 981 982 983 984
    // transpose, for ReduceSum with wrap
    sdata[threadIdx.y][threadIdx.x] = val;
    __syncthreads();
    val = sdata[threadIdx.x][threadIdx.y];
#pragma unroll
    for (int i = BLOCK_X >> 1; i > 0; i >>= 1) {
      // reduce sum with wrap
985
      val += phi::backends::gpu::CudaShuffleXorSync(0xFFFFFFFF, val, i);
986
    }
987

988 989 990 991
    size_t idx_j = j + threadIdx.y;
    if (BcastY) {
      if (dy) {
        if (threadIdx.x == 0 && (idx_j < w)) dy[idx_j] = val;
992
      }
993 994 995
    } else {
      if (dx) {
        if (threadIdx.x == 0 && (idx_j < w)) dx[idx_j] = val;
996 997
      }
    }
998 999 1000 1001 1002 1003 1004 1005 1006

    if (!SameShapeOfIntermediateOutAndOut) {
      if (d_intermediate) {
        sdata[threadIdx.y][threadIdx.x] = inter_val;
        __syncthreads();
        inter_val = sdata[threadIdx.x][threadIdx.y];
#pragma unroll
        for (int i = BLOCK_X >> 1; i > 0; i >>= 1) {
          // reduce sum with wrap
1007 1008
          inter_val +=
              phi::backends::gpu::CudaShuffleXorSync(0xFFFFFFFF, inter_val, i);
1009 1010
        }
        if (threadIdx.x == 0 && (idx_j < w)) d_intermediate[idx_j] = inter_val;
C
chengduo 已提交
1011 1012
      }
    }
1013
  }  // end for
1014 1015
}

1016 1017 1018 1019 1020 1021
template <typename T,
          typename DX_OP,
          typename DY_OP,
          typename DIntermediate_OP,
          bool UseIntermediateOut,
          bool BcastY,
C
chengduo 已提交
1022 1023
          bool SameShapeOfIntermediateOutAndOut>
static void FusedElemwiseAndActGradBroadcast1CUDA(
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
    const framework::ExecutionContext &ctx,
    const T *x,
    const T *y,
    const T *intermediate_out,
    const T *out,
    const T *dout,
    int h,
    int w,
    DX_OP dx_op,
    DY_OP dy_op,
    DIntermediate_OP dintermediate_op,
    T *dx,
    T *dy,
1037 1038 1039 1040 1041 1042 1043 1044 1045
    T *d_intermediate) {
  gpuStream_t stream = ctx.cuda_device_context().stream();

  dim3 blocks(BLOCK_X, BLOCK_Y);
  int max_gpu_threads = ctx.cuda_device_context().GetMaxPhysicalThreadCount();
  int max_blocks = std::max(max_gpu_threads / (BLOCK_X * BLOCK_Y), 1);
  int theory_block = (w + BLOCK_X - 1) / BLOCK_X;
  dim3 grids(std::min(theory_block, max_blocks));

1046 1047 1048 1049 1050 1051
  FusedElemwiseAndActGradBroadcast1CUDAKernel<T,
                                              DX_OP,
                                              DY_OP,
                                              DIntermediate_OP,
                                              UseIntermediateOut,
                                              BcastY,
1052
                                              SameShapeOfIntermediateOutAndOut>
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
      <<<grids, blocks, 0, stream>>>(x,
                                     y,
                                     intermediate_out,
                                     out,
                                     dout,
                                     h,
                                     w,
                                     dx_op,
                                     dy_op,
                                     dintermediate_op,
                                     dx,
                                     dy,
1065
                                     d_intermediate);
1066 1067
}

1068 1069 1070 1071 1072 1073
template <typename T,
          typename DX_OP,
          typename DY_OP,
          typename DIntermediate_OP,
          bool UseIntermediateOut,
          bool BcastY,
C
chengduo 已提交
1074
          bool SameShapeOfIntermediateOutAndOut>
1075
static __global__ void FusedElemwiseAndActGradBroadcast2CUDAKernel(
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
    const T *x,
    const T *y,
    const T *intermediate_out,
    const T *out,
    const T *dout,
    int pre,
    int n,
    int post,
    DX_OP dx_op,
    DY_OP dy_op,
    DIntermediate_OP dintermediate_op,
    T *dx,
    T *dy,
    T *d_intermediate) {
1090 1091 1092
  int tid = threadIdx.x;
  int j = blockIdx.x;

C
chengduo 已提交
1093
  T val(0), inter_val(0);
1094 1095
  int ttid = tid;
  int64_t tmp_out_idx, x_idx, y_idx;
1096
  T zero = static_cast<T>(0);
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
  while (true) {
    int i = ttid / post;
    int k = ttid % post;
    if (i >= pre) break;

    int offset = i * n * post + j * post + k;

    tmp_out_idx = BcastY ? j : offset;
    y_idx = BcastY ? j : offset;
    x_idx = BcastY ? offset : j;
1107 1108
    T x_val = (x == nullptr) ? zero : x[x_idx];
    T y_val = (y == nullptr) ? zero : y[y_idx];
1109 1110 1111 1112 1113 1114

    if (SameShapeOfIntermediateOutAndOut) {
      tmp_out_idx = offset;
    }

    if (dx != nullptr) {
1115
      T tmp = UseIntermediateOut
1116 1117
                  ? dx_op.UseIntermediateOut(x_val,
                                             y_val,
1118
                                             intermediate_out[tmp_out_idx],
1119 1120
                                             out[offset],
                                             dout[offset])
1121
                  : dx_op.Recompute(x_val, y_val, out[offset], dout[offset]);
1122 1123 1124 1125 1126 1127 1128 1129

      if (BcastY) {
        dx[x_idx] = tmp;
      } else {
        val += tmp;
      }
    }
    if (dy != nullptr) {
1130
      T tmp = UseIntermediateOut
1131 1132
                  ? dy_op.UseIntermediateOut(x_val,
                                             y_val,
1133
                                             intermediate_out[tmp_out_idx],
1134 1135
                                             out[offset],
                                             dout[offset])
1136
                  : dy_op.Recompute(x_val, y_val, out[offset], dout[offset]);
1137 1138 1139 1140 1141 1142
      if (BcastY) {
        val += tmp;
      } else {
        dy[y_idx] = tmp;
      }
    }
C
chengduo 已提交
1143
    if (d_intermediate != nullptr) {
1144
      T tmp = UseIntermediateOut ? dintermediate_op.UseIntermediateOut(
1145 1146 1147 1148
                                       y_val,
                                       intermediate_out[tmp_out_idx],
                                       out[offset],
                                       dout[offset])
1149 1150
                                 : dintermediate_op.Recompute(
                                       x_val, y_val, out[offset], dout[offset]);
C
chengduo 已提交
1151 1152 1153 1154 1155 1156
      if (SameShapeOfIntermediateOutAndOut) {
        d_intermediate[tmp_out_idx] = tmp;
      } else {
        inter_val += tmp;
      }
    }
1157 1158 1159
    ttid += ELEMWISE_MAX_BLOCK_DIM;
  }

C
chengduo 已提交
1160 1161
  int h = pre * post;
  h = h > ELEMWISE_MAX_BLOCK_DIM ? ELEMWISE_MAX_BLOCK_DIM : h;
1162 1163
  if (BcastY) {
    if (dy) {
1164
      val = phi::backends::gpu::reduceSum(val, tid, h);
1165 1166 1167 1168 1169 1170
      if (threadIdx.x == 0) {
        dy[j] = val;
      }
    }
  } else {
    if (dx) {
1171
      val = phi::backends::gpu::reduceSum(val, tid, h);
1172 1173 1174 1175 1176
      if (threadIdx.x == 0) {
        dx[j] = val;
      }
    }
  }
C
chengduo 已提交
1177 1178
  if (!SameShapeOfIntermediateOutAndOut) {
    if (d_intermediate) {
1179
      inter_val = phi::backends::gpu::reduceSum(inter_val, tid, h);
C
chengduo 已提交
1180 1181 1182 1183 1184
      if (threadIdx.x == 0) {
        d_intermediate[j] = inter_val;
      }
    }
  }
1185 1186
}

1187 1188 1189 1190 1191 1192
template <typename T,
          typename DX_OP,
          typename DY_OP,
          typename DIntermediate_OP,
          bool UseIntermediateOut,
          bool BcastY,
C
chengduo 已提交
1193
          bool SameShapeOfIntermediateOutAndOut>
1194
static void FusedElemwiseAndActGradBroadcast2CUDA(
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
    gpuStream_t stream,
    const T *x,
    const T *y,
    const T *intermediate_out,
    const T *out,
    const T *dout,
    int pre,
    int n,
    int post,
    DX_OP dx_op,
    DY_OP dy_op,
    DIntermediate_OP dintermediate_op,
    T *dx,
    T *dy,
C
chengduo 已提交
1209
    T *dintermediate) {
1210 1211
  int block_size = std::min(ELEMWISE_MAX_BLOCK_DIM, pre * post);
  int gird_size = n;
1212 1213 1214 1215 1216 1217
  FusedElemwiseAndActGradBroadcast2CUDAKernel<T,
                                              DX_OP,
                                              DY_OP,
                                              DIntermediate_OP,
                                              UseIntermediateOut,
                                              BcastY,
1218
                                              SameShapeOfIntermediateOutAndOut>
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
      <<<gird_size, block_size, 0, stream>>>(x,
                                             y,
                                             intermediate_out,
                                             out,
                                             dout,
                                             pre,
                                             n,
                                             post,
                                             dx_op,
                                             dy_op,
                                             dintermediate_op,
                                             dx,
                                             dy,
                                             dintermediate);
1233 1234 1235
}
#endif

1236 1237 1238 1239 1240 1241 1242
template <typename DeviceContext,
          typename T,
          typename DX_OP,
          typename DY_OP,
          typename DIntermediate_OP,
          bool UseIntermediateOut,
          bool BcastY,
1243 1244
          bool SameShapeOfIntermediateOutAndOut>
void FusedElemwiseAndActGradComputeWithBroadcast(
1245 1246 1247
    const framework::ExecutionContext &ctx,
    const framework::DDim &x_dim,
    const framework::DDim &y_dim_untrimed,
1248 1249 1250 1251 1252
    const phi::DenseTensor *x,
    const phi::DenseTensor *y,
    const phi::DenseTensor *intermediate_out,
    const phi::DenseTensor *out,
    const phi::DenseTensor *dout,
1253
    int axis,
1254 1255 1256
    phi::DenseTensor *dx,
    phi::DenseTensor *dy,
    phi::DenseTensor *dintermediate,
1257 1258
    DX_OP dx_op,
    DY_OP dy_op,
C
chengduo 已提交
1259
    DIntermediate_OP dintermediate_op) {
1260 1261 1262 1263
  axis = (axis == -1 ? x_dim.size() - y_dim_untrimed.size() : axis);
  auto y_dim = trim_trailing_singular_dims(y_dim_untrimed);
  axis = (y_dim.size() == 0) ? x_dim.size() : axis;

1264
  int pre, n, post, is_run_common_broadcast;
1265 1266
  phi::funcs::GetMidDims(
      x_dim, y_dim, axis, &pre, &n, &post, &is_run_common_broadcast);
1267 1268 1269 1270
  const T *x_data = nullptr;
  const T *y_data = nullptr;
  if (x->IsInitialized()) x_data = x->data<T>();
  if (y->IsInitialized()) y_data = y->data<T>();
1271 1272 1273
  if (post == 1) {
    int h = pre;
    int w = n;
1274

1275
    if (platform::is_gpu_place(ctx.GetPlace())) {
1276
#if defined(__NVCC__) || defined(__HIPCC__)
1277 1278 1279 1280 1281 1282
      FusedElemwiseAndActGradBroadcast1CUDA<T,
                                            DX_OP,
                                            DY_OP,
                                            DIntermediate_OP,
                                            UseIntermediateOut,
                                            BcastY,
1283
                                            SameShapeOfIntermediateOutAndOut>(
1284 1285 1286
          ctx,
          x_data,
          y_data,
1287
          intermediate_out == nullptr ? nullptr : intermediate_out->data<T>(),
1288 1289 1290 1291 1292 1293 1294
          out->data<T>(),
          dout->data<T>(),
          h,
          w,
          dx_op,
          dy_op,
          dintermediate_op,
1295
          dx == nullptr ? nullptr : dx->mutable_data<T>(ctx.GetPlace()),
C
chengduo 已提交
1296
          dy == nullptr ? nullptr : dy->mutable_data<T>(ctx.GetPlace()),
1297 1298 1299
          dintermediate == nullptr
              ? nullptr
              : dintermediate->mutable_data<T>(ctx.GetPlace()));
1300 1301
#endif
    } else {
1302 1303 1304 1305 1306 1307
      FusedElemwiseAndActGradBroadcast1CPU<T,
                                           DX_OP,
                                           DY_OP,
                                           DIntermediate_OP,
                                           UseIntermediateOut,
                                           BcastY,
1308
                                           SameShapeOfIntermediateOutAndOut>(
1309 1310
          x_data,
          y_data,
1311
          intermediate_out == nullptr ? nullptr : intermediate_out->data<T>(),
1312 1313 1314 1315 1316 1317 1318
          out->data<T>(),
          dout->data<T>(),
          h,
          w,
          dx_op,
          dy_op,
          dintermediate_op,
1319
          dx == nullptr ? nullptr : dx->mutable_data<T>(ctx.GetPlace()),
C
chengduo 已提交
1320
          dy == nullptr ? nullptr : dy->mutable_data<T>(ctx.GetPlace()),
1321 1322 1323
          dintermediate == nullptr
              ? nullptr
              : dintermediate->mutable_data<T>(ctx.GetPlace()));
1324 1325 1326
    }
  } else {
    if (platform::is_gpu_place(ctx.GetPlace())) {
1327
#if defined(__NVCC__) || defined(__HIPCC__)
1328 1329 1330 1331 1332 1333
      FusedElemwiseAndActGradBroadcast2CUDA<T,
                                            DX_OP,
                                            DY_OP,
                                            DIntermediate_OP,
                                            UseIntermediateOut,
                                            BcastY,
1334
                                            SameShapeOfIntermediateOutAndOut>(
1335 1336 1337
          ctx.template device_context<DeviceContext>().stream(),
          x_data,
          y_data,
1338
          intermediate_out == nullptr ? nullptr : intermediate_out->data<T>(),
1339 1340 1341 1342 1343 1344 1345
          out->data<T>(),
          dout->data<T>(),
          pre,
          n,
          post,
          dx_op,
          dy_op,
C
chengduo 已提交
1346
          dintermediate_op,
1347
          dx == nullptr ? nullptr : dx->mutable_data<T>(ctx.GetPlace()),
C
chengduo 已提交
1348
          dy == nullptr ? nullptr : dy->mutable_data<T>(ctx.GetPlace()),
1349 1350 1351
          dintermediate == nullptr
              ? nullptr
              : dintermediate->mutable_data<T>(ctx.GetPlace()));
1352 1353
#endif
    } else {
1354 1355 1356 1357 1358 1359
      FusedElemwiseAndActGradBroadcast2CPU<T,
                                           DX_OP,
                                           DY_OP,
                                           DIntermediate_OP,
                                           UseIntermediateOut,
                                           BcastY,
1360
                                           SameShapeOfIntermediateOutAndOut>(
1361 1362
          x_data,
          y_data,
1363
          intermediate_out == nullptr ? nullptr : intermediate_out->data<T>(),
1364 1365 1366 1367 1368 1369 1370
          out->data<T>(),
          dout->data<T>(),
          pre,
          n,
          post,
          dx_op,
          dy_op,
C
chengduo 已提交
1371
          dintermediate_op,
1372
          dx == nullptr ? nullptr : dx->mutable_data<T>(ctx.GetPlace()),
C
chengduo 已提交
1373
          dy == nullptr ? nullptr : dy->mutable_data<T>(ctx.GetPlace()),
1374 1375 1376
          dintermediate == nullptr
              ? nullptr
              : dintermediate->mutable_data<T>(ctx.GetPlace()));
1377 1378 1379 1380
    }
  }
}

1381 1382 1383 1384 1385 1386
template <typename DeviceContext,
          typename T,
          typename DX_OP,
          typename DY_OP,
          typename DIntermediate_OP,
          bool UseIntermediateOut,
C
chengduo 已提交
1387
          bool SameShapeOfIntermediateOutAndOut>
1388
void FusedElemwiseAndActGradComputeEx(const framework::ExecutionContext &ctx,
1389 1390 1391 1392 1393
                                      const phi::DenseTensor *x,
                                      const phi::DenseTensor *y,
                                      const phi::DenseTensor *out,
                                      const phi::DenseTensor *intermediate_out,
                                      const phi::DenseTensor *dout,
1394
                                      int axis,
1395 1396 1397
                                      phi::DenseTensor *dx,
                                      phi::DenseTensor *dy,
                                      phi::DenseTensor *dintermediate,
1398 1399 1400
                                      DX_OP dx_op,
                                      DY_OP dy_op,
                                      DIntermediate_OP dintermediate_op) {
1401 1402 1403
  const framework::DDim &x_dim = x->dims();
  const framework::DDim &y_dim = y->dims();
  if (UseIntermediateOut) {
1404 1405 1406
    PADDLE_ENFORCE_NOT_NULL(
        intermediate_out,
        platform::errors::InvalidArgument("Intermediate out is null pointer."));
1407 1408
  }
  if (x_dim == y_dim) {
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
    FusedElemwiseAndActGradComputeNoBroadcast<DeviceContext,
                                              T,
                                              DX_OP,
                                              DY_OP,
                                              DIntermediate_OP,
                                              UseIntermediateOut>(
        ctx,
        x_dim,
        y_dim,
        x,
        y,
        intermediate_out,
        out,
        dout,
        axis,
        dx,
        dy,
        dintermediate,
        dx_op,
        dy_op,
        dintermediate_op);
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
  } else {  // Y is a scalar
    bool bcast_y = x_dim.size() >= y_dim.size();
    if (x_dim.size() == y_dim.size()) {
      for (int i = 0; i < x_dim.size(); ++i) {
        if (x_dim[i] < y_dim[i]) {
          bcast_y = false;
          break;
        }
      }
    }

    // z = f1(x, f2(y))
    // z = f1(f2(x, y))
    if (bcast_y) {  // Y should be broadcast.
      FusedElemwiseAndActGradComputeWithBroadcast<
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
          DeviceContext,
          T,
          DX_OP,
          DY_OP,
          DIntermediate_OP,
          UseIntermediateOut,
          true /*BcastY*/,
          SameShapeOfIntermediateOutAndOut>(ctx,
                                            x_dim,
                                            y_dim,
                                            x,
                                            y,
                                            intermediate_out,
                                            out,
                                            dout,
                                            axis,
                                            dx,
                                            dy,
                                            dintermediate,
                                            dx_op,
                                            dy_op,
                                            dintermediate_op);
1467 1468
    } else {
      FusedElemwiseAndActGradComputeWithBroadcast<
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
          DeviceContext,
          T,
          DX_OP,
          DY_OP,
          DIntermediate_OP,
          UseIntermediateOut,
          false /*BcastY*/,
          SameShapeOfIntermediateOutAndOut>(ctx,
                                            y_dim,
                                            x_dim,
                                            x,
                                            y,
                                            intermediate_out,
                                            out,
                                            dout,
                                            axis,
                                            dx,
                                            dy,
                                            dintermediate,
                                            dx_op,
                                            dy_op,
                                            dintermediate_op);
1491 1492 1493 1494
    }
  }
}

1495 1496 1497 1498 1499
template <typename DeviceContext,
          typename T,
          typename CompoundFunctor,
          bool KeepIntermediateOut,
          bool SameShapeOfIntermediateOutAndOut>
1500
void FusedElemwiseAndActComputeEx(const framework::ExecutionContext &ctx,
1501 1502
                                  const phi::DenseTensor &x,
                                  const phi::DenseTensor &y,
1503
                                  int axis,
1504
                                  CompoundFunctor compound_functor,
1505 1506
                                  phi::DenseTensor *out,
                                  phi::DenseTensor *intermediate_out) {
1507
  if (KeepIntermediateOut) {
1508 1509 1510 1511 1512
    PADDLE_ENFORCE_NOT_NULL(
        intermediate_out,
        platform::errors::InvalidArgument(
            "The save_intermediate_out is opened, intermediate "
            "out is null pointer."));
1513 1514 1515 1516 1517
  }

  const framework::DDim &x_dim = x.dims();
  const framework::DDim &y_dim = y.dims();
  if (x.dims() == y.dims()) {
1518 1519 1520
    FusedElemwiseAndActComputeNoBroadcast<DeviceContext,
                                          T,
                                          CompoundFunctor,
1521 1522 1523 1524 1525
                                          KeepIntermediateOut>(
        ctx, x_dim, x, y, compound_functor, out, intermediate_out);
  } else {
    // Whether the shape of Y is a continuous subsequence of X,
    // For more information please refer to the op's introduction.
1526
    bool bcast_y = x.numel() >= y.numel();
1527 1528 1529 1530
    // z = f1(x, f2(y))
    // z = f1(f2(x, y))
    if (bcast_y) {  // Y should be broadcast.
      // In this case,
1531 1532
      // for 'f2(y)', the shape of intermediate_out should be equal to the
      // shape
1533 1534 1535 1536
      // of Y.
      // for 'f2(x, y)', the shape of intermediate_out should be equal to the
      // shape of Out.
      // the shape of Out should be equal to the shape of X.
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
      FusedElemwiseAndActComputeWithBroadcast<DeviceContext,
                                              T,
                                              CompoundFunctor,
                                              true /*BcastY*/,
                                              KeepIntermediateOut,
                                              SameShapeOfIntermediateOutAndOut>(
          ctx,
          x_dim /*OutShape*/,
          y_dim,
          x,
          y,
          compound_functor,
          axis,
          out,
1551 1552 1553
          intermediate_out);
    } else {
      // In this case,
1554 1555
      // for 'f2(y)', the shape of intermediate_out should be equal to the
      // shape
1556 1557 1558 1559
      // of Out.
      // for 'f2(x, y)', the shape of intermediate_out should be equal to the
      // shape of Out.
      // the shape of Out should be equal to the shape of Y.
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
      FusedElemwiseAndActComputeWithBroadcast<DeviceContext,
                                              T,
                                              CompoundFunctor,
                                              false /*BcastY*/,
                                              KeepIntermediateOut,
                                              SameShapeOfIntermediateOutAndOut>(
          ctx,
          y_dim /*OutShape*/,
          x_dim,
          x,
          y,
          compound_functor,
          axis,
          out,
1574 1575 1576 1577
          intermediate_out);
    }
  }
}
1578 1579 1580

template <typename DeviceContext, typename T>
static inline void GetDoubleGradSafeTensor(
1581
    const framework::ExecutionContext &ctx,
1582 1583 1584
    const phi::DenseTensor *x,
    const phi::DenseTensor *ddx,
    phi::DenseTensor *ddx_safe) {
1585
  const auto &dev_ctx = ctx.template device_context<DeviceContext>();
1586 1587
  phi::funcs::GetDoubleGradSafeTensor<DeviceContext, T>(
      dev_ctx, *x, ddx, ddx_safe);
1588 1589
}

1590 1591 1592 1593
// for broadcast backwards
static inline std::vector<int> GetReduceDim(const framework::DDim &in,
                                            const framework::DDim &out,
                                            int axis) {
1594
  return phi::funcs::GetReduceDim(in, out, axis);
1595
}
1596 1597 1598 1599

#if defined(__NVCC__) || defined(__HIPCC__)

template <ElementwiseType ET, typename T, typename Functor>
L
Leo Chen 已提交
1600
void GetGradXAndYOut(const phi::GPUContext &dev_ctx,
1601 1602
                     const platform::Place &place,
                     int axis,
1603 1604 1605 1606
                     std::vector<const phi::DenseTensor *> ins,
                     const phi::DenseTensor *dout,
                     phi::DenseTensor *dx,
                     phi::DenseTensor *dy,
1607 1608 1609
                     Functor func) {
  phi::GetGradXAndYOut<ET, T, Functor>(
      dev_ctx, place, axis, ins, *dout, dx, dy, func);
1610 1611 1612
}

template <ElementwiseType ET, typename T, typename Functor>
L
Leo Chen 已提交
1613
void GetGradXOrYOut(const phi::GPUContext &dev_ctx,
1614 1615
                    const platform::Place &place,
                    int axis,
1616 1617 1618
                    std::vector<const phi::DenseTensor *> ins,
                    const phi::DenseTensor *dout,
                    phi::DenseTensor *dxy,
1619
                    Functor func) {
1620 1621
  phi::GetGradXOrYOut<ET, T, Functor>(
      dev_ctx, place, axis, ins, *dout, dxy, func);
1622 1623 1624 1625
}

#endif

1626 1627
}  // namespace operators
}  // namespace paddle