reduce_op.cc 9.4 KB
Newer Older
G
guosheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License. */

#include "paddle/operators/reduce_op.h"
G
guosheng 已提交
16
#include "paddle/operators/net_op.h"
G
guosheng 已提交
17 18 19 20 21 22 23 24 25 26

namespace paddle {
namespace operators {

using framework::Tensor;

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

27
  void InferShape(framework::InferShapeContext *ctx) const override {
28 29 30 31 32
    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 已提交
33
    auto x_rank = x_dims.size();
G
guosheng 已提交
34
    PADDLE_ENFORCE_LE(x_rank, 6, "Tensors with rank at most 6 are supported.");
35
    int dim = ctx->Attrs().Get<int>("dim");
G
guosheng 已提交
36 37 38
    if (dim < 0) dim = x_rank + dim;
    PADDLE_ENFORCE_LT(
        dim, x_rank,
G
guosheng 已提交
39
        "The dim should be in the range [-rank(input), rank(input)).");
40
    bool keep_dim = ctx->Attrs().Get<bool>("keep_dim");
G
guosheng 已提交
41 42 43 44 45 46 47
    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);
48
    ctx->SetOutputDim("Out", out_dims);
49
    if (dim != 0) {
50 51
      // Only pass LoD when not reducing on the first dim.
      ctx->ShareLoD("X", /*->*/ "Out");
52
    }
G
guosheng 已提交
53 54 55 56 57 58 59
  }
};

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

60
  void InferShape(framework::InferShapeContext *ctx) const override {
61 62 63 64
    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 已提交
65
    auto x_rank = x_dims.size();
G
guosheng 已提交
66
    PADDLE_ENFORCE_LE(x_rank, 6, "Tensors with rank at most 6 are supported.");
67
    int dim = ctx->Attrs().Get<int>("dim");
G
guosheng 已提交
68 69 70
    if (dim < 0) dim = x_rank + dim;
    PADDLE_ENFORCE_LT(
        dim, x_rank,
G
guosheng 已提交
71
        "The dim should be in the range [-rank(input), rank(input)).");
72 73 74 75
    auto x_grad_name = framework::GradVarName("X");
    if (ctx->HasOutput(x_grad_name)) {
      ctx->SetOutputDim(x_grad_name, x_dims);
    }
G
guosheng 已提交
76 77 78
  }
};

G
guosheng 已提交
79
class ReduceOpMaker : public framework::OpProtoAndCheckerMaker {
G
guosheng 已提交
80
 public:
G
guosheng 已提交
81
  ReduceOpMaker(framework::OpProto *proto, framework::OpAttrChecker *op_checker)
G
guosheng 已提交
82 83 84 85 86
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput(
        "X",
        "(Tensor) The input tensor. Tensors with rank at most 6 are supported");
    AddOutput("Out", "(Tensor) The result tensor.");
87 88 89 90 91 92
    AddAttr<int>(
        "dim",
        "(int, default 1) The dimension to reduce. "
        "Must be in the range [-rank(input), rank(input)). "
        "If `dim < 0`, the dim to reduce is `rank + dim`. "
        "Noting that reducing on the first dim will make the LoD info lost.")
93
        .SetDefault(0);
G
guosheng 已提交
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
    AddAttr<bool>("keep_dim",
                  "(bool, default false) "
                  "If true, retain the reduced dimension with length 1.")
        .SetDefault(false);
    comment_ = R"DOC(
{ReduceOP} operator computes the {reduce} of input tensor along the given dimension. 
The result tensor has 1 fewer dimension than the input unless `keep_dim` is true.
)DOC";
    AddComment(comment_);
  }

 protected:
  std::string comment_;

  void Replace(std::string &src, std::string from, std::string to) {
    std::size_t len_from = std::strlen(from.c_str());
    std::size_t len_to = std::strlen(to.c_str());
    for (std::size_t pos = src.find(from); pos != std::string::npos;
         pos = src.find(from, pos + len_to)) {
      src.replace(pos, len_from, to);
    }
  }

  void SetComment(std::string name, std::string op) {
    Replace(comment_, "{ReduceOP}", name);
    Replace(comment_, "{reduce}", op);
G
guosheng 已提交
120 121 122
  }
};

G
guosheng 已提交
123 124 125 126 127 128 129 130 131 132 133
class ReduceSumOpMaker : public ReduceOpMaker {
 public:
  ReduceSumOpMaker(framework::OpProto *proto,
                   framework::OpAttrChecker *op_checker)
      : ReduceOpMaker(proto, op_checker) {
    SetComment("ReduceSum", "sum");
    AddComment(comment_);
  }
};

class ReduceMeanOpMaker : public ReduceOpMaker {
G
guosheng 已提交
134 135 136
 public:
  ReduceMeanOpMaker(framework::OpProto *proto,
                    framework::OpAttrChecker *op_checker)
G
guosheng 已提交
137 138 139
      : ReduceOpMaker(proto, op_checker) {
    SetComment("ReduceMean", "mean");
    AddComment(comment_);
G
guosheng 已提交
140 141 142
  }
};

G
guosheng 已提交
143
class ReduceMaxOpMaker : public ReduceOpMaker {
G
guosheng 已提交
144 145 146
 public:
  ReduceMaxOpMaker(framework::OpProto *proto,
                   framework::OpAttrChecker *op_checker)
G
guosheng 已提交
147 148 149
      : ReduceOpMaker(proto, op_checker) {
    SetComment("ReduceMax", "max");
    AddComment(comment_);
G
guosheng 已提交
150 151 152
  }
};

G
guosheng 已提交
153
class ReduceMinOpMaker : public ReduceOpMaker {
G
guosheng 已提交
154 155 156
 public:
  ReduceMinOpMaker(framework::OpProto *proto,
                   framework::OpAttrChecker *op_checker)
G
guosheng 已提交
157 158 159
      : ReduceOpMaker(proto, op_checker) {
    SetComment("ReduceMin", "min");
    AddComment(comment_);
G
guosheng 已提交
160 161 162
  }
};

G
guosheng 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
class NormOp : public NetOp {
 public:
  NormOp(const std::string &type, const framework::VariableNameMap &inputs,
         const framework::VariableNameMap &outputs,
         const framework::AttributeMap &attrs)
      : NetOp(type, inputs, outputs, attrs) {
    PADDLE_ENFORCE_NE(Input("X"), framework::kEmptyVarName,
                      "Input(X) of NormOp should not be null.");
    PADDLE_ENFORCE_NE(Output("AbsOut"), framework::kEmptyVarName,
                      "Output(AbsOut) of NormOp should not be null.");
    PADDLE_ENFORCE_NE(Output("PowOut"), framework::kEmptyVarName,
                      "Output(PowOut) of NormOp should not be null.");
    PADDLE_ENFORCE_NE(Output("SumOut"), framework::kEmptyVarName,
                      "Output(SumOut) of NormOp should not be null.");
    PADDLE_ENFORCE_NE(Output("Out"), framework::kEmptyVarName,
                      "Output(Out) of NormOp should not be null.");
    auto dim = Attr<int>("dim");
    auto keep_dim = Attr<bool>("keep_dim");
    auto p = Attr<float>("p");
    PADDLE_ENFORCE_GT(p, 0, "Order of the norm should be positive.");
    AppendOp(framework::OpRegistry::CreateOp("abs", {{"X", {Input("X")}}},
                                             {{"Y", {Output("AbsOut")}}}, {}));
    AppendOp(framework::OpRegistry::CreateOp("pow", {{"X", {Output("AbsOut")}}},
                                             {{"Y", {Output("PowOut")}}},
                                             {{"factor", p}}));
    framework::AttributeMap sum_attr;
    sum_attr["dim"] = dim;
    sum_attr["keep_dim"] = keep_dim;
    AppendOp(framework::OpRegistry::CreateOp(
        "reduce_sum", {{"X", {Output("PowOut")}}},
        {{"Out", {Output("SumOut")}}}, sum_attr));
    AppendOp(framework::OpRegistry::CreateOp(
        "pow", {{"X", {Output("SumOut")}}}, {{"Y", {Output("Out")}}},
        {{"factor", static_cast<float>(1. / p)}}));
    CompleteAddOp(false);
  }
};

class NormOpMaker : public ReduceOpMaker {
 public:
  NormOpMaker(framework::OpProto *proto, framework::OpAttrChecker *op_checker)
      : ReduceOpMaker(proto, op_checker) {
    AddOutput("AbsOut",
              "(Tensor) The intermediate output of Norm operator, "
              "saving the absolute value of the input tensor X.")
        .AsIntermediate();
    AddOutput("PowOut",
              "(Tensor) The intermediate output of Norm operator, "
              "saving the p-th power of the output tensor AbsOut.")
        .AsIntermediate();
    AddOutput("SumOut",
              "(Tensor) the intermediate output of Norm operator, "
              "saving the sum of PowOut reduced on the given dimension.")
        .AsIntermediate();
    AddAttr<float>("p", "(float, default 2) The order of Norm.").SetDefault(2);
    SetComment("Norm", "vector p-norm");
    AddComment(comment_);
  }
};

G
guosheng 已提交
223 224 225 226 227 228 229 230 231 232 233 234 235 236
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OP(reduce_sum, ops::ReduceOp, ops::ReduceSumOpMaker, reduce_sum_grad,
            ops::ReduceGradOp);

REGISTER_OP(reduce_mean, ops::ReduceOp, ops::ReduceMeanOpMaker,
            reduce_mean_grad, ops::ReduceGradOp);

REGISTER_OP(reduce_max, ops::ReduceOp, ops::ReduceMaxOpMaker, reduce_max_grad,
            ops::ReduceGradOp);

L
Luo Tao 已提交
237
REGISTER_OP(reduce_min, ops::ReduceOp, ops::ReduceMinOpMaker, reduce_min_grad,
G
guosheng 已提交
238
            ops::ReduceGradOp);
G
guosheng 已提交
239 240

REGISTER_OP_WITHOUT_GRADIENT(norm, ops::NormOp, ops::NormOpMaker);
241

242 243 244 245 246 247 248 249 250
#define REGISTER_REDUCE_CPU_KERNEL(reduce_type, functor, grad_functor)     \
  REGISTER_OP_CPU_KERNEL(                                                  \
      reduce_type,                                                         \
      ops::ReduceKernel<paddle::platform::CPUPlace, float, ops::functor>); \
  REGISTER_OP_CPU_KERNEL(reduce_type##_grad,                               \
                         ops::ReduceGradKernel<paddle::platform::CPUPlace, \
                                               float, ops::grad_functor>);

FOR_EACH_KERNEL_FUNCTOR(REGISTER_REDUCE_CPU_KERNEL);