reduce_op.h 32.4 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
G
guosheng 已提交
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
G
guosheng 已提交
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
G
guosheng 已提交
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. */
G
guosheng 已提交
14 15 16

#pragma once

17
#include <algorithm>
18
#include <set>
19
#include <string>
W
whs 已提交
20
#include <vector>
21

22
#include "paddle/fluid/framework/data_type_transform.h"
23
#include "paddle/fluid/framework/tensor_util.h"
W
Wu Yi 已提交
24
#include "paddle/fluid/operators/reduce_ops/reduce_op_function.h"
25 26
#include "paddle/phi/kernels/funcs/math_function.h"
// only can include the headers in paddle/phi/api dirs
27
#include "paddle/fluid/framework/convert_utils.h"
28
#include "paddle/fluid/framework/phi_utils.h"
29
#include "paddle/phi/kernels/cpu/reduce.h"
30

31
#if defined(__HIPCC__) || defined(__NVCC__) || defined(__xpu__)
32 33
#include "paddle/phi/kernels/gpu/reduce.h"
#include "paddle/phi/kernels/gpu/reduce_grad.h"
34
#endif
G
guosheng 已提交
35 36 37 38

namespace paddle {
namespace operators {

39 40 41 42 43 44 45 46 47
#define HANDLE_DIM(NDIM, RDIM)                                   \
  if (ndim == NDIM && rdim == RDIM) {                            \
    paddle::operators::                                          \
        ReduceFunctor<DeviceContext, OutT, NDIM, RDIM, Functor>( \
            context.template device_context<DeviceContext>(),    \
            *input,                                              \
            output,                                              \
            dims,                                                \
            keep_dim);                                           \
W
whs 已提交
48 49
  }

50 51
using DDim = framework::DDim;

52 53
inline void GetShuffledDim(const DDim& src_dims,
                           DDim* dst_dims,
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
                           const std::vector<int>& reduced_dims,
                           std::vector<int>* perm_axis) {
  // check if it's a reduced dim
  std::vector<bool> src_dims_check(src_dims.size(), false);
  size_t src_size = src_dims.size();
  size_t reduce_size = reduced_dims.size();
  for (size_t i = 0; i < reduce_size; ++i) {
    dst_dims->at(src_size - reduce_size + i) = src_dims[reduced_dims[i]];
    (*perm_axis)[src_size - reduce_size + i] = reduced_dims[i];
    src_dims_check[reduced_dims[i]] = true;
  }

  size_t offset = 0;
  for (size_t i = 0; i < src_dims_check.size(); ++i) {
    bool is_reduced = src_dims_check[i];
    if (!is_reduced) {
      (*perm_axis)[offset] = i;
      dst_dims->at(offset++) = src_dims[i];
    }
  }
}

76
static inline std::vector<int> GetReduceDim(const std::vector<int>& dims,
77 78
                                            int dim_size,
                                            bool reduce_all) {
79 80 81 82 83 84 85 86 87
  std::vector<int> reduce_dims;
  if (reduce_all) {
    reduce_dims.resize(dim_size);
    int reduce_size = reduce_dims.size();
    for (int i = 0; i < reduce_size; ++i) {
      reduce_dims[i] = i;
    }
  } else {
    for (auto e : dims) {
88 89
      PADDLE_ENFORCE_LT(e,
                        dim_size,
90
                        paddle::platform::errors::InvalidArgument(
91
                            "ReduceBaseOp: invalid axis, when x_dims is %d, "
92
                            "axis[i] should less than x_dims, but got %d.",
93 94
                            dim_size,
                            e));
95 96 97 98 99
      reduce_dims.push_back(e >= 0 ? e : e + dim_size);
    }
  }
  return reduce_dims;
}
100 101
template <typename DeviceContext, typename OutT>
void GetShuffledInput(const framework::ExecutionContext& context,
102 103
                      const phi::DenseTensor* input,
                      phi::DenseTensor* shuffled_input,
104 105 106 107 108 109 110 111
                      const std::vector<int>& dims) {
  DDim shuffled_dims(input->dims());
  std::vector<int> perm_axis(input->dims().size());
  GetShuffledDim(input->dims(), &shuffled_dims, dims, &perm_axis);

  shuffled_input->Resize(shuffled_dims);
  shuffled_input->mutable_data<OutT>(context.GetPlace());

112
  phi::funcs::TransposeNormal<DeviceContext, OutT> trans;
113 114 115 116
  trans(context.template device_context<DeviceContext>(),
        *input,
        shuffled_input,
        perm_axis);
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
}

inline void GetOriginDimFromShuffled(const DDim& src_dim,
                                     const std::vector<int>& dims,
                                     std::vector<int>* origin_dim) {
  DDim shuffled_dims(src_dim);
  size_t n = src_dim.size();
  std::vector<int> perm_axis(n);
  GetShuffledDim(src_dim, &shuffled_dims, dims, &perm_axis);
  for (size_t i = 0; i < n; ++i) {
    (*origin_dim)[perm_axis[i]] = i;
  }
}

template <typename DeviceContext, typename OutT, typename Functor>
void HandleLargeDim(const framework::ExecutionContext& context,
133 134
                    const phi::DenseTensor* input,
                    phi::DenseTensor* output,
135 136
                    const std::vector<int>& dims,
                    bool keep_dim) {
137
  //  shuffle the reduced dim to the end
138
  phi::DenseTensor shuffled_input;
139 140 141 142
  GetShuffledInput<DeviceContext, OutT>(context, input, &shuffled_input, dims);

  // transpose to 2D tensor whose shape is {unreduced, reduced}.
  const int64_t unreduced = output->numel();
143 144 145 146 147 148 149 150 151 152 153 154 155 156
  const int64_t input_numel = shuffled_input.numel();
  // assume: 0 / 0 == 0, which allow process 0 dim tensor
  const int64_t reduced = (unreduced != 0) ? (input_numel / unreduced) : 0;

  PADDLE_ENFORCE_EQ(
      unreduced * reduced,
      input_numel,
      phi::errors::InvalidArgument(
          "Reducing failed in HandleLargeDim, when try to transpose (%d) "
          "operands into 2D tensor with shape (%d, %d).",
          input_numel,
          unreduced,
          reduced));

157
  shuffled_input.Resize({unreduced, reduced});
158

159 160
  DDim output_dim = output->dims();
  output->Resize({unreduced});
161
  paddle::operators::ReduceFunctor<DeviceContext, OutT, 2, 1, Functor>(
162 163 164 165 166
      context.template device_context<DeviceContext>(),
      shuffled_input,
      output,
      {1},
      keep_dim);
167 168 169 170 171
  output->Resize(output_dim);
}

template <typename DeviceContext, typename T, typename Functor>
void HandleLargeDimGrad(const framework::ExecutionContext& context,
172 173 174 175
                        const phi::DenseTensor* x,
                        const phi::DenseTensor* out,
                        const phi::DenseTensor* dout,
                        phi::DenseTensor* dx,
176 177
                        Functor functor,
                        const std::vector<int>& dims) {
178
  const int64_t unreduced = out->numel();
179 180 181 182 183 184 185 186 187 188 189 190 191 192
  const int64_t x_numel = x->numel();
  // assume: 0 / 0 == 0, which allow process 0 dim tensor
  const int64_t reduced = (unreduced != 0) ? (x_numel / unreduced) : 0;

  PADDLE_ENFORCE_EQ(
      unreduced * reduced,
      x_numel,
      phi::errors::InvalidArgument(
          "Reducing failed in HandleLargeDimGrad, when try to transpose (%d) "
          "operands into 2D tensor with shape (%d, %d).",
          x_numel,
          unreduced,
          reduced));

193 194 195
  DDim out_dim(out->dims());
  DDim x_dim(x->dims());
  // transpose and reshape X
196
  phi::DenseTensor shuffled_x;
197 198 199 200 201 202
  GetShuffledInput<DeviceContext, T>(context, x, &shuffled_x, dims);
  DDim shuffled_dim = shuffled_x.dims();
  shuffled_x.Resize({unreduced, reduced});
  // reshape dX {unreduced, reduced}
  dx->Resize({unreduced, reduced});
  ReduceGradFunctor<DeviceContext, T, 2, Functor>(
203 204 205 206 207 208 209
      context.template device_context<DeviceContext>(),
      shuffled_x,
      *out,
      *dout,
      dx,
      functor,
      {1});
210 211 212
  // transpose dX
  std::vector<int> origin_axis(x_dim.size());
  GetOriginDimFromShuffled(x_dim, dims, &origin_axis);
213
  phi::DenseTensor dx_tmp;
214 215 216
  framework::TensorCopy(*dx, context.GetPlace(), &dx_tmp);
  dx_tmp.Resize(shuffled_dim);
  dx->Resize(x_dim);
217
  phi::funcs::TransposeNormal<DeviceContext, T> trans;
218 219 220
  trans(context.template device_context<DeviceContext>(),
        dx_tmp,
        dx,
221 222
        origin_axis);
}
223 224 225

template <typename DeviceContext, typename T, typename Functor>
struct ReduceKernelFunctor {
226 227
  const phi::DenseTensor* input;
  phi::DenseTensor* output;
228 229 230 231
  std::vector<int> dims;
  bool keep_dim;
  bool reduce_all;
  const framework::ExecutionContext& context;
232 233
  ReduceKernelFunctor(const phi::DenseTensor* input,
                      phi::DenseTensor* output,
234 235
                      const std::vector<int>& dims,
                      bool keep_dim,
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
                      bool reduce_all,
                      const framework::ExecutionContext& context)
      : input(input),
        output(output),
        dims(dims),
        keep_dim(keep_dim),
        reduce_all(reduce_all),
        context(context) {}

  template <typename OutT>
  void apply() const {
    output->mutable_data<OutT>(context.GetPlace());
    if (reduce_all) {
      // Flatten and reduce 1-D tensor
      auto x = EigenVector<OutT>::Flatten(*input);
      auto out = EigenScalar<OutT>::From(*output);
      auto& place =
          *context.template device_context<DeviceContext>().eigen_device();
      auto reduce_dim = Eigen::array<int, 1>({{0}});
      Functor functor;
      functor(place, &x, &out, reduce_dim);
    } else {
      int ndim = input->dims().size();
      int rdim = dims.size();
260
      if (ndim > 6) {
261 262
        HandleLargeDim<DeviceContext, OutT, Functor>(
            context, input, output, dims, keep_dim);
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
      } else {
        HANDLE_DIM(6, 5);
        HANDLE_DIM(6, 4);
        HANDLE_DIM(6, 3);
        HANDLE_DIM(6, 2);
        HANDLE_DIM(6, 1);
        HANDLE_DIM(5, 4);
        HANDLE_DIM(5, 3);
        HANDLE_DIM(5, 2);
        HANDLE_DIM(5, 1);
        HANDLE_DIM(4, 3);
        HANDLE_DIM(4, 2);
        HANDLE_DIM(4, 1);
        HANDLE_DIM(3, 2);
        HANDLE_DIM(3, 1);
        HANDLE_DIM(2, 1);
        HANDLE_DIM(1, 1);
      }
281 282 283
    }
  }
};
Q
QI JUN 已提交
284
template <typename DeviceContext, typename T, typename Functor>
Y
Yu Yang 已提交
285
class ReduceKernel : public framework::OpKernel<T> {
286 287 288
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    bool reduce_all = context.Attr<bool>("reduce_all");
289
    auto* output = context.Output<phi::DenseTensor>("Out");
290 291 292 293
    auto dims = context.Attr<std::vector<int>>("dim");
    bool keep_dim = context.Attr<bool>("keep_dim");
    int out_dtype = context.Attr<int>("out_dtype");
    framework::proto::VarType::Type cast_out_dtype;
294
    auto* input = context.Input<phi::DenseTensor>("X");
295

296
    if (out_dtype < 0) {
297 298
      cast_out_dtype = static_cast<framework::proto::VarType::Type>(
          framework::TransToProtoVarType(input->dtype()));
299 300 301
    } else {
      cast_out_dtype = static_cast<framework::proto::VarType::Type>(out_dtype);
    }
302 303 304 305 306 307 308 309 310

    auto& dev_ctx = context.device_context<DeviceContext>();
    output->mutable_data(
        dev_ctx.GetPlace(),
        static_cast<framework::proto::VarType::Type>(cast_out_dtype));

    std::vector<int64_t> tmp_dims(dims.begin(), dims.end());

    // call new kernel
311 312
    phi::Reduce<typename framework::ConvertToPhiContext<DeviceContext>::TYPE,
                T,
313 314
                Functor>(
        static_cast<const typename framework::ConvertToPhiContext<
W
Wilber 已提交
315
            DeviceContext>::TYPE&>(dev_ctx),
316 317 318 319 320 321
        *input,
        reduce_all,
        tmp_dims,
        keep_dim,
        framework::TransToPhiDataType(cast_out_dtype),
        output);
322 323
  }
};
324

325 326
template <typename DeviceContext, typename T, typename Functor>
void LaunchReduceGradKernel(const framework::ExecutionContext& context,
327 328 329 330
                            const phi::DenseTensor* input0,
                            const phi::DenseTensor* input1,
                            const phi::DenseTensor* input2,
                            phi::DenseTensor* output,
331
                            Functor functor,
332 333 334 335 336 337 338 339 340 341 342
                            const std::vector<int>& dims,
                            bool reduce_all = false) {
  if (reduce_all) {
    auto x = EigenVector<T>::Flatten(*input0);
    auto x_reduce = EigenVector<T>::Flatten(*input1);
    auto x_reduce_grad = EigenVector<T>::Flatten(*input2);
    auto x_grad = EigenVector<T>::Flatten(*output);
    auto& place =
        *context.template device_context<DeviceContext>().eigen_device();
    auto broadcast_dim =
        Eigen::array<int, 1>({{static_cast<int>(input0->numel())}});
343 344 345 346 347 348
    functor(place,
            &x,
            &x_reduce,
            &x_grad,
            &x_reduce_grad,
            broadcast_dim,
349 350 351 352 353 354
            broadcast_dim[0]);
  } else {
    int rank = input0->dims().size();
    switch (rank) {
      case 1:
        ReduceGradFunctor<DeviceContext, T, 1, Functor>(
355 356 357 358 359 360 361
            context.template device_context<DeviceContext>(),
            *input0,
            *input1,
            *input2,
            output,
            functor,
            dims);
362 363 364
        break;
      case 2:
        ReduceGradFunctor<DeviceContext, T, 2, Functor>(
365 366 367 368 369 370 371
            context.template device_context<DeviceContext>(),
            *input0,
            *input1,
            *input2,
            output,
            functor,
            dims);
372 373 374
        break;
      case 3:
        ReduceGradFunctor<DeviceContext, T, 3, Functor>(
375 376 377 378 379 380 381
            context.template device_context<DeviceContext>(),
            *input0,
            *input1,
            *input2,
            output,
            functor,
            dims);
382 383 384
        break;
      case 4:
        ReduceGradFunctor<DeviceContext, T, 4, Functor>(
385 386 387 388 389 390 391
            context.template device_context<DeviceContext>(),
            *input0,
            *input1,
            *input2,
            output,
            functor,
            dims);
392 393 394
        break;
      case 5:
        ReduceGradFunctor<DeviceContext, T, 5, Functor>(
395 396 397 398 399 400 401
            context.template device_context<DeviceContext>(),
            *input0,
            *input1,
            *input2,
            output,
            functor,
            dims);
402 403 404
        break;
      case 6:
        ReduceGradFunctor<DeviceContext, T, 6, Functor>(
405 406 407 408 409 410 411
            context.template device_context<DeviceContext>(),
            *input0,
            *input1,
            *input2,
            output,
            functor,
            dims);
412 413
        break;
      default:
414 415
        HandleLargeDimGrad<DeviceContext, T, Functor>(
            context, input0, input1, input2, output, functor, dims);
416 417 418 419 420
        break;
    }
  }
}

421 422 423 424 425
template <typename DeviceContext,
          typename T,
          typename Functor,
          bool kNoNeedBufferX = false,
          bool kNoNeedBufferY = false>
Y
Yu Yang 已提交
426
class ReduceGradKernel : public framework::OpKernel<T> {
G
guosheng 已提交
427
 public:
428
  void ComputeFromInput(const phi::DenseTensor* input2,
429
                        const framework::ExecutionContext& context) const {
430
    bool reduce_all = context.Attr<bool>("reduce_all");
431
    auto dims = context.Attr<std::vector<int>>("dim");
432 433
    auto* input0 = context.Input<phi::DenseTensor>("X");
    auto* input1 = context.Input<phi::DenseTensor>("Out");
434

435 436
    auto* output =
        context.Output<phi::DenseTensor>(framework::GradVarName("X"));
437 438
    output->mutable_data<T>(context.GetPlace());

439
    // The dims has full dim, set the reduce_all is True
440 441
    const auto& input_dim_size =
        context.Input<phi::DenseTensor>("X")->dims().size();
442 443 444 445 446 447 448 449 450
    std::set<int> dims_set(dims.begin(), dims.end());
    bool full_dim = true;
    for (auto i = 0; i < input_dim_size; i++) {
      if (dims_set.find(i) == dims_set.end()) {
        full_dim = false;
        break;
      }
    }
    reduce_all = (reduce_all || full_dim);
451 452 453 454 455 456 457 458 459 460 461
    // NOTE: EigenTensor::From() uses tensor->data()
    // if op has NoNeedBufferVarsInferer, the corresponding kNoNeedBufferX or
    // kNoNeedBufferY should set true
    // and use fake var that has same dims.
    if (kNoNeedBufferX) {
      input0 = output;
    }
    if (kNoNeedBufferY) {
      input1 = input2;
    }

462 463
    const std::vector<int> const_dims = dims;

L
lvmengsi 已提交
464 465 466
    // NOTE(dengkaipeng): Out is unnecessary in some reduce kernel and
    // not be set as Input in grad Maker, use Out_grad to replace here
    if (!input1) input1 = input2;
467
    Functor functor;
468 469 470 471 472 473 474 475
    LaunchReduceGradKernel<DeviceContext, T, Functor>(context,
                                                      input0,
                                                      input1,
                                                      input2,
                                                      output,
                                                      functor,
                                                      const_dims,
                                                      reduce_all);
G
guosheng 已提交
476
  }
477 478 479 480

  void Compute(const framework::ExecutionContext& context) const override {
    int in_dtype = context.Attr<int>("in_dtype");
    if (in_dtype >= 0) {
481
      phi::DenseTensor tmp_tensor;
482 483
      auto* pre_input =
          context.Input<phi::DenseTensor>(framework::GradVarName("Out"));
484 485 486 487 488 489
      auto in_kernel_type =
          phi::KernelKey(framework::TransToProtoVarType(pre_input->dtype()),
                         context.GetPlace());
      auto out_kernel_type =
          phi::KernelKey(static_cast<framework::proto::VarType::Type>(in_dtype),
                         context.GetPlace());
490 491
      framework::TransDataType(
          in_kernel_type, out_kernel_type, *pre_input, &tmp_tensor);
492 493 494
      ComputeFromInput(&tmp_tensor, context);

    } else {
495 496
      auto* input2 =
          context.Input<phi::DenseTensor>(framework::GradVarName("Out"));
497 498 499
      ComputeFromInput(input2, context);
    }
  }
500
};
G
guosheng 已提交
501

502
class ReduceBaseOp : public framework::OperatorWithKernel {
503 504
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
G
guosheng 已提交
505

506
  void InferShape(framework::InferShapeContext* ctx) const override {
507 508
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "ReduceBaseOp");
    OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "ReduceBaseOp");
509 510 511
    auto x_dims = ctx->GetInputDim("X");
    auto x_rank = x_dims.size();
    auto dims = ctx->Attrs().Get<std::vector<int>>("dim");
512 513
    PADDLE_ENFORCE_GT(dims.size(),
                      0,
514
                      platform::errors::InvalidArgument(
515
                          "The input dim dimensions of ReduceBaseOp "
516 517 518
                          "should be greater than 0. But received the dim "
                          "dimesions of Reduce = %d.",
                          dims.size()));
519

520
    for (size_t i = 0; i < dims.size(); ++i) {
521 522
      PADDLE_ENFORCE_LT(dims[i],
                        x_rank,
523 524 525 526
                        platform::errors::InvalidArgument(
                            "The reduce dim index %d should be in the "
                            "range [-dimension(X), dimension(X)] "
                            "which dimesion = %d. But received dim index = %d.",
527 528 529 530 531
                            i,
                            x_rank,
                            dims[i]));
      PADDLE_ENFORCE_GE(dims[i],
                        -x_rank,
532 533 534 535
                        platform::errors::InvalidArgument(
                            "The reduce dim index %d should be in the "
                            "range [-dimension(X), dimension(X)] "
                            "which dimesion = %d. But received dim index = %d.",
536 537 538
                            i,
                            x_rank,
                            dims[i]));
539 540 541 542 543 544 545
      if (dims[i] < 0) dims[i] = x_rank + dims[i];
    }
    sort(dims.begin(), dims.end());
    bool reduce_all = ctx->Attrs().Get<bool>("reduce_all");
    bool keep_dim = ctx->Attrs().Get<bool>("keep_dim");
    if (reduce_all) {
      if (keep_dim)
546
        ctx->SetOutputDim("Out",
547
                          phi::make_ddim(std::vector<int64_t>(x_rank, 1)));
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
      else
        ctx->SetOutputDim("Out", {1});
    } else {
      auto dims_vector = vectorize(x_dims);
      if (keep_dim) {
        for (size_t i = 0; i < dims.size(); ++i) {
          dims_vector[dims[i]] = 1;
        }
      } else {
        const int kDelFlag = -2;
        for (size_t i = 0; i < dims.size(); ++i) {
          dims_vector[dims[i]] = kDelFlag;
        }
        dims_vector.erase(
            remove(dims_vector.begin(), dims_vector.end(), kDelFlag),
            dims_vector.end());
      }
565 566 567
      if (!keep_dim && dims_vector.size() == 0) {
        dims_vector.push_back(1);
      }
568
      auto out_dims = phi::make_ddim(dims_vector);
569
      ctx->SetOutputDim("Out", out_dims);
570
      if (dims.size() > 0 && dims[0] != 0) {
571 572 573 574 575
        // Only pass LoD when not reducing on the first dim.
        ctx->ShareLoD("X", /*->*/ "Out");
      }
    }
  }
576

577 578 579 580 581 582
  // oneDNN's reduction kernel is optimized only for reducing throughout the
  // most outer dims, so in case of another type of reduction, it would be
  // better to fallback to native implementation
  static bool HasOptimizedOneDNNKernel(const framework::ExecutionContext& ctx) {
    // native reduce kernels don't support bf16
    // so oneDNN kernel is enforced in that case
583
    if (ctx.Input<phi::DenseTensor>("X")->dtype() == phi::DataType::BFLOAT16)
584 585
      return true;

586 587 588 589
    if (!ctx.HasAttr("dim") || !ctx.HasAttr("reduce_all")) {
      return false;
    }

590 591
    auto reduce_dims = ctx.Attr<std::vector<int>>("dim");
    const bool reduce_all = ctx.Attr<bool>("reduce_all");
592
    int ndims = ctx.Input<phi::DenseTensor>("X")->dims().size();
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611

    if (reduce_all) {
      return true;
    }

    for (size_t i = 0; i < reduce_dims.size(); ++i) {
      if (reduce_dims[i] < 0) reduce_dims[i] = ndims + reduce_dims[i];
    }
    sort(reduce_dims.begin(), reduce_dims.end());
    for (size_t i = 0; i < reduce_dims.size(); ++i) {
      if (reduce_dims[reduce_dims.size() - i - 1] !=
          static_cast<int>(ndims - i - 1)) {
        return false;
      }
    }

    return true;
  }

612
  phi::KernelKey GetExpectedKernelType(
613 614 615 616
      const framework::ExecutionContext& ctx) const override {
    // choose cudnn kernel if the runtime supported.
    auto input_data_type = OperatorWithKernel::IndicateVarDataType(ctx, "X");

617 618 619 620
    // NOTE(jiahongyu): Below codes originally enclosed by PADDLE_WITH_MKLDNN
    if (ctx.Input<phi::DenseTensor>("X")->dims().size() > 5 ||
        !HasOptimizedOneDNNKernel(ctx)) {
      this->SetDnnFallback(true);
621
    }
622
    // NOTE(jiahongyu): Above codes originally enclosed by PADDLE_WITH_MKLDNN
623 624

    if (input_data_type == framework::proto::VarType::FP16) {
625 626
      PADDLE_ENFORCE_EQ(
          platform::is_gpu_place(ctx.GetPlace()) ||
Y
ykkk2333 已提交
627
              platform::is_xpu_place(ctx.GetPlace()) ||
628
              platform::is_custom_place(ctx.GetPlace()),
629 630
          true,
          platform::errors::InvalidArgument(
张春乔 已提交
631
              "float16 can only be used on GPU or NPU or XPU place"));
632
    }
633
    return phi::KernelKey(input_data_type, ctx.GetPlace());
634
  }
635 636
};

637
class ReduceOpUseInputPlace : public ReduceBaseOp {
G
Guo Sheng 已提交
638
 public:
639
  using ReduceBaseOp::ReduceBaseOp;
G
Guo Sheng 已提交
640 641

 protected:
642
  phi::KernelKey GetExpectedKernelType(
G
Guo Sheng 已提交
643
      const framework::ExecutionContext& ctx) const override {
644 645 646
    phi::KernelKey kt = OperatorWithKernel::GetExpectedKernelType(ctx);
    kt.set_backend(
        phi::TransToPhiBackend(ctx.Input<phi::DenseTensor>("X")->place()));
G
Guo Sheng 已提交
647 648 649 650
    return kt;
  }
};

651 652 653
class ReduceGradOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
W
whs 已提交
654

655
  void InferShape(framework::InferShapeContext* ctx) const override {
656
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "ReduceBaseOp");
657 658 659
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")),
                   "Input",
                   "Out@GRAD",
660
                   "ReduceBaseOp");
661 662
    auto x_dims = ctx->GetInputDim("X");
    auto x_rank = x_dims.size();
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
    // TODO(dev): We should delete Infershape and migrate it into
    // UnchangeInferMeta.In case of 'dim' is Variable, it will
    // not exist in Attrs but in Inputs.
    if (ctx->HasAttr("dim")) {
      auto dims = ctx->Attrs().Get<std::vector<int>>("dim");
      for (size_t i = 0; i < dims.size(); ++i) {
        PADDLE_ENFORCE_LT(
            dims[i],
            x_rank,
            platform::errors::InvalidArgument(
                "The reduce dim index %d should be in the "
                "range [-dimension(X), dimension(X)], "
                "which dimesion = %d. But received dim index = %d.",
                i,
                x_rank,
                dims[i]));
        if (dims[i] < 0) dims[i] = x_rank + dims[i];
      }
681
    }
682

683 684 685 686
    auto x_grad_name = framework::GradVarName("X");
    if (ctx->HasOutput(x_grad_name)) {
      ctx->SetOutputDim(x_grad_name, x_dims);
      ctx->ShareLoD("X", /*->*/ x_grad_name);
W
whs 已提交
687
    }
688
  }
689 690

 protected:
691
  phi::KernelKey GetExpectedKernelType(
692
      const framework::ExecutionContext& ctx) const override {
693
    int out_dtype = ctx.Attr<int>("out_dtype");
J
jakpiase 已提交
694
    auto input_data_type =
695 696 697 698
        (out_dtype >= 0)
            ? static_cast<framework::proto::VarType::Type>(out_dtype)
            : OperatorWithKernel::IndicateVarDataType(
                  ctx, framework::GradVarName("Out"));
699

700 701 702 703
    // NOTE(jiahongyu): Below codes originally enclosed by PADDLE_WITH_MKLDNN
    // max 5D tensor is supported
    if (ctx.Input<phi::DenseTensor>("X")->dims().size() > 5) {
      dnn_fallback_ = true;
704
    }
705
    // NOTE(jiahongyu): Above codes originally enclosed by PADDLE_WITH_MKLDNN
706

707
    return phi::KernelKey(input_data_type, ctx.GetPlace());
708
  }
709 710
};

711
class ReduceBaseOpMaker : public framework::OpProtoAndCheckerMaker {
712 713 714 715 716 717 718 719 720 721 722 723
 public:
  void Make() final {
    AddInput("X",
             "(Tensor) The input tensor. Tensors with rank at most 6 are "
             "supported.");
    AddOutput("Out", "(Tensor) The result tensor.");
    AddAttr<std::vector<int>>(
        "dim",
        "(list<int>, default {0}) The dimensions to reduce. "
        "Must be in the range [-rank(input), rank(input)). "
        "If `dim[i] < 0`, the dims[i] to reduce is `rank + dims[i]`. "
        "Note that reducing on the first dim will make the LoD info lost.")
724 725
        .SetDefault({0})
        .SupportTensor();
726 727 728 729 730 731 732 733
    AddAttr<bool>("keep_dim",
                  "(bool, default false) "
                  "If true, retain the reduced dimension with length 1.")
        .SetDefault(false);
    AddAttr<bool>("reduce_all",
                  "(bool, default false) "
                  "If true, output a scalar reduced along all dimensions.")
        .SetDefault(false);
734 735 736 737 738 739 740 741 742 743
    AddAttr<int>("in_dtype",
                 "(int, default -1)"
                 "The dtype of input, default value is -1, the user could not "
                 "set this value.")
        .SetDefault(-1);
    AddAttr<int>(
        "out_dtype",
        "(int, default -1)"
        "The dtype of output, default value is -1, the dtype is same as intput")
        .SetDefault(-1);
744 745
    AddComment(string::Sprintf(R"DOC(
%s Operator.
W
whs 已提交
746

747 748 749
This operator computes the %s of input tensor along the given dimension.
The result tensor has 1 fewer dimension than the input unless keep_dim is true.
If reduce_all is true, just reduce along all dimensions and output a scalar.
W
whs 已提交
750

751
)DOC",
752 753
                               GetOpType(),
                               GetName()));
G
guosheng 已提交
754
  }
755 756 757 758

 protected:
  virtual std::string GetName() const = 0;
  virtual std::string GetOpType() const = 0;
G
guosheng 已提交
759 760
};

761
#if defined(__HIPCC__) || defined(__NVCC__) || defined(__xpu__)
762 763
template <typename T,
          template <typename>
764
          class ReduceBaseOp,
765 766
          template <typename, typename>
          class TransformOp>
767 768 769 770
class ReduceCudaKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    bool reduce_all = context.Attr<bool>("reduce_all");
771 772
    const phi::DenseTensor* input = context.Input<phi::DenseTensor>("X");
    phi::DenseTensor* output = context.Output<phi::DenseTensor>("Out");
773
    auto out_dtype = context.Attr<int>("out_dtype");
774
    auto pt_out_dtype = paddle::framework::TransToPhiDataType(
775
        static_cast<framework::proto::VarType::Type>(out_dtype));
776
    std::vector<int> dims = context.Attr<std::vector<int>>("dim");
777 778 779 780
#ifdef PADDLE_WITH_XPU_KP
    auto& dev_ctx =
        context.template device_context<paddle::platform::XPUDeviceContext>();
#else
781
    auto& dev_ctx = context.cuda_device_context();
782
#endif
783
    if (out_dtype >= 0) {
784
      output->mutable_data(dev_ctx.GetPlace(), pt_out_dtype);
785
    } else {
786
      output->mutable_data(dev_ctx.GetPlace(), input->dtype());
787
    }
788 789 790

    std::vector<int64_t> dims_int64{dims.begin(), dims.end()};

791
    phi::Reduce<T, ReduceBaseOp, TransformOp>(
792
        dev_ctx, *input, reduce_all, dims_int64, false, pt_out_dtype, output);
793 794
  }
};
795

796
#ifndef PADDLE_WITH_XPU_KP
797 798 799 800 801 802
template <typename T, template <typename, typename> class TransformOp>
class ReduceCudaGradKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    bool reduce_all = context.Attr<bool>("reduce_all");
    std::vector<int> dims = context.Attr<std::vector<int>>("dim");
803
    auto* in_x = context.Input<phi::DenseTensor>("X");
804

805
    auto* d_out =
806 807
        context.Input<phi::DenseTensor>(framework::GradVarName("Out"));
    auto* d_x = context.Output<phi::DenseTensor>(framework::GradVarName("X"));
808
    auto out_dtype = context.Attr<int>("in_dtype");
809
    auto pt_out_dtype = framework::TransToPhiDataType(
810
        static_cast<framework::proto::VarType::Type>(out_dtype));
811 812 813 814 815 816 817 818 819 820
    // get reduce_dim and reduce_num for reduce_mean_grad
    int dim_size = in_x->dims().size();
    std::vector<int> reduce_dims = GetReduceDim(dims, dim_size, reduce_all);
    auto update_dims = vectorize(d_x->dims());
    int reduce_num = 1;
    for (auto i : reduce_dims) {
      reduce_num *= (in_x->dims())[i];
      update_dims[i] = 1;
    }
    // make new tensor
821
    phi::DenseTensor new_d_out(d_out->type());
822
    new_d_out.ShareDataWith(*d_out);
823
    new_d_out.Resize(phi::make_ddim(update_dims));
824 825
    auto& dev_ctx = context.cuda_device_context();
    if (out_dtype > 0) {
826
      d_x->mutable_data(dev_ctx.GetPlace(), pt_out_dtype);
827
    } else {
828
      d_x->mutable_data(dev_ctx.GetPlace(), d_out->dtype());
829
    }
H
Huang Jiyi 已提交
830 831
    auto pt_d_out = std::make_unique<phi::DenseTensor>(new_d_out);
    auto pt_d_x = std::make_unique<phi::DenseTensor>(*d_x);
832
    if (out_dtype <= 0) {
833
      pt_out_dtype = d_out->dtype();
834
    }
835

836
    using MPType = typename kps::details::MPTypeTrait<T>::Type;
837 838 839 840 841
    phi::ReduceGrad<TransformOp<T, MPType>>(dev_ctx,
                                            pt_d_out.get(),
                                            pt_d_x.get(),
                                            pt_out_dtype,
                                            TransformOp<T, MPType>(reduce_num));
842 843
  }
};
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859

template <typename T>
struct EqualFunctor {
  inline T initial() { return static_cast<T>(0.0f); }

  inline HOSTDEVICE T operator()(const T a, const T b) const {
    return static_cast<T>(a == b);
  }
};

template <typename T, typename Enable = void>
struct DivideFunctor {
  inline T initial() { return static_cast<T>(1.0f); }

  inline HOSTDEVICE T operator()(const T a, const T b) const { return a / b; }
};
860
#endif
861
#endif
862

G
guosheng 已提交
863 864
}  // namespace operators
}  // namespace paddle
865

866 867
namespace ops = paddle::operators;

H
hong 已提交
868
#define REGISTER_REDUCE_OP(op_name)                                           \
869
  class __##op_name##Maker__ : public ops::ReduceBaseOpMaker {                \
H
hong 已提交
870 871 872 873 874
   protected:                                                                 \
    virtual std::string GetName() const { return #op_name; }                  \
    virtual std::string GetOpType() const { return "Reduce " #op_name; }      \
  };                                                                          \
  REGISTER_OPERATOR(                                                          \
875
      op_name,                                                                \
876
      ops::ReduceBaseOp,                                                      \
877
      __##op_name##Maker__,                                                   \
H
hong 已提交
878 879 880 881 882 883
      paddle::framework::DefaultGradOpMaker<paddle::framework::OpDesc, true>, \
      paddle::framework::DefaultGradOpMaker<paddle::imperative::OpBase,       \
                                            true>);                           \
  REGISTER_OPERATOR(op_name##_grad, ops::ReduceGradOp)

#define REGISTER_REDUCE_OP_WITHOUT_GRAD(op_name, ...)                    \
884
  class __##op_name##Maker__ : public ops::ReduceBaseOpMaker {           \
885 886 887 888
   protected:                                                            \
    virtual std::string GetName() const { return #op_name; }             \
    virtual std::string GetOpType() const { return "Reduce " #op_name; } \
  };                                                                     \
H
hong 已提交
889
  REGISTER_OPERATOR(                                                     \
890
      op_name,                                                           \
891
      ops::ReduceBaseOp##__VA_ARGS__,                                    \
892
      __##op_name##Maker__,                                              \
H
hong 已提交
893 894
      paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,    \
      paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>);