reduce_op.h 18.1 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 18
#include <algorithm>
#include <string>
W
whs 已提交
19
#include <vector>
20

21 22
#include "paddle/fluid/framework/data_type_transform.h"
#include "paddle/fluid/operators/cast_op.h"
W
Wu Yi 已提交
23
#include "paddle/fluid/operators/reduce_ops/reduce_op_function.h"
G
guosheng 已提交
24 25 26 27

namespace paddle {
namespace operators {

28 29
#define HANDLE_DIM(NDIM, RDIM)                                            \
  if (ndim == NDIM && rdim == RDIM) {                                     \
30
    ReduceFunctor<DeviceContext, OutT, NDIM, RDIM, Functor>(              \
31 32
        context.template device_context<DeviceContext>(), *input, output, \
        dims, keep_dim);                                                  \
W
whs 已提交
33 34
  }

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
using Tensor = framework::Tensor;

template <typename DeviceContext, typename T, typename Functor>
struct ReduceKernelFunctor {
  const Tensor* input;
  Tensor* output;
  std::vector<int> dims;
  bool keep_dim;
  bool reduce_all;
  const framework::ExecutionContext& context;
  ReduceKernelFunctor(const Tensor* input, Tensor* output,
                      const std::vector<int>& dims, bool keep_dim,
                      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();
71 72 73 74 75 76 77 78 79
      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);
80 81 82 83 84 85 86 87 88 89
      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);
    }
  }
};
Q
QI JUN 已提交
90
template <typename DeviceContext, typename T, typename Functor>
Y
Yu Yang 已提交
91
class ReduceKernel : public framework::OpKernel<T> {
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    bool reduce_all = context.Attr<bool>("reduce_all");
    auto* output = context.Output<Tensor>("Out");
    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;

    if (out_dtype < 0) {
      auto* cast_input = context.Input<Tensor>("X");
      cast_out_dtype =
          static_cast<framework::proto::VarType::Type>(cast_input->type());
      framework::VisitDataType(
          cast_out_dtype,
          ReduceKernelFunctor<DeviceContext, T, Functor>(
              cast_input, output, dims, keep_dim, reduce_all, context));
    } else {
      Tensor tmp_tensor;
      cast_out_dtype = static_cast<framework::proto::VarType::Type>(out_dtype);
      auto* input = context.Input<Tensor>("X");

      tmp_tensor.Resize(input->dims());
      framework::VisitDataType(
          cast_out_dtype,
          CastOpFunctor<DeviceContext, T>(
              input, &tmp_tensor,
              context.template device_context<DeviceContext>()));
      framework::VisitDataType(
          cast_out_dtype,
          ReduceKernelFunctor<DeviceContext, T, Functor>(
              &tmp_tensor, output, dims, keep_dim, reduce_all, context));
    }
  }
};

template <typename DeviceContext, typename OutT, typename Functor>
class BoolReduceKernel : public framework::OpKernel<OutT> {
G
guosheng 已提交
130 131
 public:
  void Compute(const framework::ExecutionContext& context) const override {
132
    bool reduce_all = context.Attr<bool>("reduce_all");
133 134
    auto* input = context.Input<Tensor>("X");
    auto* output = context.Output<Tensor>("Out");
135
    output->mutable_data<OutT>(context.GetPlace());
136 137 138 139

    auto dims = context.Attr<std::vector<int>>("dim");
    bool keep_dim = context.Attr<bool>("keep_dim");

140 141
    if (reduce_all) {
      // Flatten and reduce 1-D tensor
142 143
      auto x = EigenVector<OutT>::Flatten(*input);
      auto out = EigenScalar<OutT>::From(*output);
144 145 146 147
      auto& place =
          *context.template device_context<DeviceContext>().eigen_device();
      auto reduce_dim = Eigen::array<int, 1>({{0}});
      Functor functor;
148
      functor(place, &x, &out, reduce_dim);
149
    } else {
150 151
      int ndim = input->dims().size();
      int rdim = dims.size();
152 153 154 155 156 157 158 159 160 161
      // comments for accelerating compiling temporarily.
      //      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);
W
whs 已提交
162 163 164 165 166 167 168
      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);
G
guosheng 已提交
169 170 171
    }
  }
};
172 173
template <typename DeviceContext, typename T, typename Functor,
          bool kNoNeedBufferX = false, bool kNoNeedBufferY = false>
Y
Yu Yang 已提交
174
class ReduceGradKernel : public framework::OpKernel<T> {
G
guosheng 已提交
175
 public:
176 177
  void ComputeFromInput(const Tensor* input2,
                        const framework::ExecutionContext& context) const {
178
    bool reduce_all = context.Attr<bool>("reduce_all");
179 180 181
    auto dims = context.Attr<std::vector<int>>("dim");
    auto* input0 = context.Input<Tensor>("X");
    auto* input1 = context.Input<Tensor>("Out");
182

183 184 185
    auto* output = context.Output<Tensor>(framework::GradVarName("X"));
    output->mutable_data<T>(context.GetPlace());

186 187 188 189 190 191 192 193 194 195 196
    // 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;
    }

L
lvmengsi 已提交
197 198 199 200
    // 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;

201 202 203 204 205 206 207 208 209 210
    if (reduce_all) {
      auto x = EigenVector<T>::Flatten(*input0);
      auto x_reduce = EigenVector<T>::From(*input1);
      auto x_reduce_grad = EigenVector<T>::From(*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())}});
      Functor functor;
211
      functor(place, &x, &x_reduce, &x_grad, &x_reduce_grad, broadcast_dim,
212 213
              broadcast_dim[0]);
    } else {
214
      int rank = input0->dims().size();
215 216
      switch (rank) {
        case 1:
217 218 219
          ReduceGradFunctor<DeviceContext, T, 1, Functor>(
              context.template device_context<DeviceContext>(), *input0,
              *input1, *input2, output, dims);
220 221
          break;
        case 2:
222 223 224
          ReduceGradFunctor<DeviceContext, T, 2, Functor>(
              context.template device_context<DeviceContext>(), *input0,
              *input1, *input2, output, dims);
225 226
          break;
        case 3:
227 228 229
          ReduceGradFunctor<DeviceContext, T, 3, Functor>(
              context.template device_context<DeviceContext>(), *input0,
              *input1, *input2, output, dims);
230 231
          break;
        case 4:
232 233 234
          ReduceGradFunctor<DeviceContext, T, 4, Functor>(
              context.template device_context<DeviceContext>(), *input0,
              *input1, *input2, output, dims);
235 236
          break;
        case 5:
237 238 239
          ReduceGradFunctor<DeviceContext, T, 5, Functor>(
              context.template device_context<DeviceContext>(), *input0,
              *input1, *input2, output, dims);
240 241
          break;
        case 6:
242 243 244
          ReduceGradFunctor<DeviceContext, T, 6, Functor>(
              context.template device_context<DeviceContext>(), *input0,
              *input1, *input2, output, dims);
245 246
          break;
      }
G
guosheng 已提交
247 248
    }
  }
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268

  void Compute(const framework::ExecutionContext& context) const override {
    int in_dtype = context.Attr<int>("in_dtype");
    if (in_dtype >= 0) {
      Tensor tmp_tensor;
      auto* pre_input = context.Input<Tensor>(framework::GradVarName("Out"));
      auto in_kernel_type =
          framework::OpKernelType(pre_input->type(), context.GetPlace());
      auto out_kernel_type = framework::OpKernelType(
          static_cast<framework::proto::VarType::Type>(in_dtype),
          context.GetPlace());
      framework::TransDataType(in_kernel_type, out_kernel_type, *pre_input,
                               &tmp_tensor);
      ComputeFromInput(&tmp_tensor, context);

    } else {
      auto* input2 = context.Input<Tensor>(framework::GradVarName("Out"));
      ComputeFromInput(input2, context);
    }
  }
269
};
G
guosheng 已提交
270

271 272 273
class ReduceOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
G
guosheng 已提交
274

275
  void InferShape(framework::InferShapeContext* ctx) const override {
276 277
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "ReduceOp");
    OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "ReduceOp");
278 279
    auto x_dims = ctx->GetInputDim("X");
    auto x_rank = x_dims.size();
280
    PADDLE_ENFORCE_LE(x_rank, 6,
281 282 283 284 285
                      platform::errors::InvalidArgument(
                          "The input tensor X's dimensions of ReduceOp "
                          "should be less equal than 6. But received X's "
                          "dimensions = %d, X's shape = [%s].",
                          x_rank, x_dims));
286
    auto dims = ctx->Attrs().Get<std::vector<int>>("dim");
287 288 289 290 291 292
    PADDLE_ENFORCE_GT(dims.size(), 0,
                      platform::errors::InvalidArgument(
                          "The input dim dimensions of ReduceOp "
                          "should be greater than 0. But received the dim "
                          "dimesions of Reduce = %d.",
                          dims.size()));
293

294
    for (size_t i = 0; i < dims.size(); ++i) {
295
      PADDLE_ENFORCE_LT(dims[i], x_rank,
296 297 298 299 300
                        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]));
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
      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)
        ctx->SetOutputDim(
            "Out", framework::make_ddim(std::vector<int64_t>(x_rank, 1)));
      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());
      }
327 328 329
      if (!keep_dim && dims_vector.size() == 0) {
        dims_vector.push_back(1);
      }
330 331
      auto out_dims = framework::make_ddim(dims_vector);
      ctx->SetOutputDim("Out", out_dims);
332
      if (dims.size() > 0 && dims[0] != 0) {
333 334 335 336 337 338 339
        // Only pass LoD when not reducing on the first dim.
        ctx->ShareLoD("X", /*->*/ "Out");
      }
    }
  }
};

G
Guo Sheng 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352
class ReduceOpUseInputPlace : public ReduceOp {
 public:
  using ReduceOp::ReduceOp;

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    framework::OpKernelType kt = OperatorWithKernel::GetExpectedKernelType(ctx);
    kt.place_ = ctx.Input<framework::LoDTensor>("X")->place();
    return kt;
  }
};

353 354 355
class ReduceGradOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
W
whs 已提交
356

357
  void InferShape(framework::InferShapeContext* ctx) const override {
358 359 360
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "ReduceOp");
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")), "Input",
                   "Out@GRAD", "ReduceOp");
361 362
    auto x_dims = ctx->GetInputDim("X");
    auto x_rank = x_dims.size();
363 364 365 366 367
    PADDLE_ENFORCE_LE(x_rank, 6,
                      platform::errors::InvalidArgument(
                          "Tensors with rank at most 6 are supported by "
                          "ReduceOp. Received tensor with rank %d.",
                          x_rank));
368
    auto dims = ctx->Attrs().Get<std::vector<int>>("dim");
W
whs 已提交
369
    for (size_t i = 0; i < dims.size(); ++i) {
370
      PADDLE_ENFORCE_LT(dims[i], x_rank,
371 372 373 374 375
                        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]));
W
whs 已提交
376
      if (dims[i] < 0) dims[i] = x_rank + dims[i];
377 378 379 380 381 382
    }
    sort(dims.begin(), dims.end());
    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 已提交
383
    }
384
  }
385 386 387 388

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
389 390 391 392 393 394
    int in_dtype = ctx.Attr<int>("in_dtype");
    if (in_dtype >= 0) {
      return framework::OpKernelType(
          static_cast<framework::proto::VarType::Type>(in_dtype),
          ctx.GetPlace());
    }
395 396 397
    return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
                                       ctx, framework::GradVarName("Out")),
                                   ctx.GetPlace());
398
  }
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
};

class ReduceOpMaker : public framework::OpProtoAndCheckerMaker {
 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.")
        .SetDefault({0});
    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);
423 424 425 426 427 428 429 430 431 432
    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);
433 434
    AddComment(string::Sprintf(R"DOC(
%s Operator.
W
whs 已提交
435

436 437 438
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 已提交
439

440 441
)DOC",
                               GetOpType(), GetName()));
G
guosheng 已提交
442
  }
443 444 445 446

 protected:
  virtual std::string GetName() const = 0;
  virtual std::string GetOpType() const = 0;
G
guosheng 已提交
447 448 449 450
};

}  // namespace operators
}  // namespace paddle
451

452 453
namespace ops = paddle::operators;

H
hong 已提交
454 455 456 457 458 459 460 461 462 463 464 465 466 467
#define REGISTER_REDUCE_OP(op_name)                                           \
  class __##op_name##Maker__ : public ops::ReduceOpMaker {                    \
   protected:                                                                 \
    virtual std::string GetName() const { return #op_name; }                  \
    virtual std::string GetOpType() const { return "Reduce " #op_name; }      \
  };                                                                          \
  REGISTER_OPERATOR(                                                          \
      op_name, ops::ReduceOp, __##op_name##Maker__,                           \
      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, ...)                    \
468 469 470 471 472
  class __##op_name##Maker__ : public ops::ReduceOpMaker {               \
   protected:                                                            \
    virtual std::string GetName() const { return #op_name; }             \
    virtual std::string GetOpType() const { return "Reduce " #op_name; } \
  };                                                                     \
H
hong 已提交
473 474 475 476
  REGISTER_OPERATOR(                                                     \
      op_name, ops::ReduceOp##__VA_ARGS__, __##op_name##Maker__,         \
      paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,    \
      paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>);