reduce_op.cc 7.0 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

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/reduce_op.h"
G
guosheng 已提交
16

Y
Yang Yang 已提交
17 18 19
#include <string>
#include <vector>

G
guosheng 已提交
20 21 22 23 24 25 26 27 28
namespace paddle {
namespace operators {

using framework::Tensor;

class ReduceOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

29
  void InferShape(framework::InferShapeContext *ctx) const override {
30 31 32 33 34
    PADDLE_ENFORCE(ctx->HasInput("X"),
                   "Input(X) of ReduceOp should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput("Out"),
                   "Output(Out) of ReduceOp should not be null.");
    auto x_dims = ctx->GetInputDim("X");
G
guosheng 已提交
35
    auto x_rank = x_dims.size();
G
guosheng 已提交
36
    PADDLE_ENFORCE_LE(x_rank, 6, "Tensors with rank at most 6 are supported.");
37
    int dim = ctx->Attrs().Get<int>("dim");
G
guosheng 已提交
38 39 40
    if (dim < 0) dim = x_rank + dim;
    PADDLE_ENFORCE_LT(
        dim, x_rank,
G
guosheng 已提交
41
        "The dim should be in the range [-rank(input), rank(input)).");
42
    bool reduce_all = ctx->Attrs().Get<bool>("reduce_all");
43
    bool keep_dim = ctx->Attrs().Get<bool>("keep_dim");
44
    if (reduce_all) {
45 46 47 48 49
      if (keep_dim)
        ctx->SetOutputDim(
            "Out", framework::make_ddim(std::vector<int64_t>(x_rank, 1)));
      else
        ctx->SetOutputDim("Out", {1});
G
guosheng 已提交
50
    } else {
51 52 53 54 55 56 57 58 59 60 61 62
      auto dims_vector = vectorize(x_dims);
      if (keep_dim || x_rank == 1) {
        dims_vector[dim] = 1;
      } else {
        dims_vector.erase(dims_vector.begin() + dim);
      }
      auto out_dims = framework::make_ddim(dims_vector);
      ctx->SetOutputDim("Out", out_dims);
      if (dim != 0) {
        // Only pass LoD when not reducing on the first dim.
        ctx->ShareLoD("X", /*->*/ "Out");
      }
63
    }
G
guosheng 已提交
64 65 66 67 68 69 70
  }
};

class ReduceGradOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

71
  void InferShape(framework::InferShapeContext *ctx) const override {
72 73 74 75
    PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should not be null.");
    PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
                   "Input(Out@GRAD) should not be null.");
    auto x_dims = ctx->GetInputDim("X");
G
guosheng 已提交
76
    auto x_rank = x_dims.size();
G
guosheng 已提交
77
    PADDLE_ENFORCE_LE(x_rank, 6, "Tensors with rank at most 6 are supported.");
78
    int dim = ctx->Attrs().Get<int>("dim");
G
guosheng 已提交
79 80 81
    if (dim < 0) dim = x_rank + dim;
    PADDLE_ENFORCE_LT(
        dim, x_rank,
G
guosheng 已提交
82
        "The dim should be in the range [-rank(input), rank(input)).");
83 84 85
    auto x_grad_name = framework::GradVarName("X");
    if (ctx->HasOutput(x_grad_name)) {
      ctx->SetOutputDim(x_grad_name, x_dims);
86
      ctx->ShareLoD("X", /*->*/ x_grad_name);
87
    }
G
guosheng 已提交
88 89 90
  }
};

G
guosheng 已提交
91
class ReduceOpMaker : public framework::OpProtoAndCheckerMaker {
G
guosheng 已提交
92
 public:
Y
Yu Yang 已提交
93
  void Make() final {
K
kexinzhao 已提交
94 95 96
    AddInput("X",
             "(Tensor) The input tensor. Tensors with rank at most 6 are "
             "supported.");
G
guosheng 已提交
97
    AddOutput("Out", "(Tensor) The result tensor.");
98 99
    AddAttr<int>(
        "dim",
K
kexinzhao 已提交
100
        "(int, default 0) The dimension to reduce. "
101 102
        "Must be in the range [-rank(input), rank(input)). "
        "If `dim < 0`, the dim to reduce is `rank + dim`. "
K
kexinzhao 已提交
103
        "Note that reducing on the first dim will make the LoD info lost.")
104
        .SetDefault(0);
G
guosheng 已提交
105 106 107 108
    AddAttr<bool>("keep_dim",
                  "(bool, default false) "
                  "If true, retain the reduced dimension with length 1.")
        .SetDefault(false);
109 110 111 112
    AddAttr<bool>("reduce_all",
                  "(bool, default false) "
                  "If true, output a scalar reduced along all dimensions.")
        .SetDefault(false);
Y
Yu Yang 已提交
113 114
    AddComment(string::Sprintf(R"DOC(
%s Operator.
K
kexinzhao 已提交
115

Y
Yu Yang 已提交
116
This operator computes the %s of input tensor along the given dimension.
K
kexinzhao 已提交
117
The result tensor has 1 fewer dimension than the input unless keep_dim is true.
118
If reduce_all is true, just reduce along all dimensions and output a scalar.
K
kexinzhao 已提交
119

Y
Yu Yang 已提交
120 121
)DOC",
                               GetOpType(), GetName()));
G
guosheng 已提交
122 123 124
  }

 protected:
Y
Yu Yang 已提交
125 126
  virtual std::string GetName() const = 0;
  virtual std::string GetOpType() const = 0;
127 128
};

G
guosheng 已提交
129 130 131 132 133
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

Y
Yu Yang 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
#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(reduce_##op_name, ops::ReduceOp, __##op_name##Maker__, \
                    paddle::framework::DefaultGradOpDescMaker<true>);      \
  REGISTER_OPERATOR(reduce_##op_name##_grad, ops::ReduceGradOp)

REGISTER_REDUCE_OP(sum);
REGISTER_REDUCE_OP(mean);
REGISTER_REDUCE_OP(max);
REGISTER_REDUCE_OP(min);
REGISTER_REDUCE_OP(prod);
149

Q
QI JUN 已提交
150 151 152
#define REGISTER_REDUCE_CPU_KERNEL(reduce_type, functor, grad_functor)         \
  REGISTER_OP_CPU_KERNEL(reduce_type,                                          \
                         ops::ReduceKernel<paddle::platform::CPUDeviceContext, \
153 154 155 156 157 158 159
                                           float, ops::functor>,               \
                         ops::ReduceKernel<paddle::platform::CPUDeviceContext, \
                                           double, ops::functor>,              \
                         ops::ReduceKernel<paddle::platform::CPUDeviceContext, \
                                           int, ops::functor>,                 \
                         ops::ReduceKernel<paddle::platform::CPUDeviceContext, \
                                           int64_t, ops::functor>);            \
Q
QI JUN 已提交
160 161 162
  REGISTER_OP_CPU_KERNEL(                                                      \
      reduce_type##_grad,                                                      \
      ops::ReduceGradKernel<paddle::platform::CPUDeviceContext, float,         \
163 164 165 166 167 168
                            ops::grad_functor>,                                \
      ops::ReduceGradKernel<paddle::platform::CPUDeviceContext, double,        \
                            ops::grad_functor>,                                \
      ops::ReduceGradKernel<paddle::platform::CPUDeviceContext, int,           \
                            ops::grad_functor>,                                \
      ops::ReduceGradKernel<paddle::platform::CPUDeviceContext, int64_t,       \
Q
QI JUN 已提交
169
                            ops::grad_functor>);
170 171

FOR_EACH_KERNEL_FUNCTOR(REGISTER_REDUCE_CPU_KERNEL);