reduce_op.cc 7.0 KB
Newer Older
G
guosheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* 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"

namespace paddle {
namespace operators {

using framework::Tensor;
G
guosheng 已提交
21
using framework::LoDTensor;
G
guosheng 已提交
22 23 24 25 26 27 28

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

 protected:
  void InferShape(const framework::InferShapeContext &ctx) const override {
G
guosheng 已提交
29 30 31 32
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("X"),
                            "Input(X) of ReduceOp should not be null.");
    PADDLE_ENFORCE_NOT_NULL(ctx.OutputVar("Out"),
                            "Output(Out) of ReduceOp should not be null.");
G
guosheng 已提交
33 34
    auto x_dims = ctx.Input<Tensor>("X")->dims();
    auto x_rank = x_dims.size();
G
guosheng 已提交
35
    PADDLE_ENFORCE_LE(x_rank, 6, "Tensors with rank at most 6 are supported.");
36
    int dim = ctx.Attr<int>("dim");
G
guosheng 已提交
37 38 39
    if (dim < 0) dim = x_rank + dim;
    PADDLE_ENFORCE_LT(
        dim, x_rank,
G
guosheng 已提交
40 41
        "The dim should be in the range [-rank(input), rank(input)).");
    bool keep_dim = ctx.Attr<bool>("keep_dim");
G
guosheng 已提交
42 43 44 45 46 47 48
    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);
G
guosheng 已提交
49
    ctx.Output<framework::LoDTensor>("Out")->Resize(out_dims);
G
guosheng 已提交
50 51 52 53 54 55 56 57 58
  }
};

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

 protected:
  void InferShape(const framework::InferShapeContext &ctx) const override {
G
guosheng 已提交
59
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("X"), "Input(X) should not be null.");
G
guosheng 已提交
60
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar(framework::GradVarName("Out")),
G
guosheng 已提交
61
                            "Input(Out@GRAD) should not be null.");
G
guosheng 已提交
62 63
    auto x_dims = ctx.Input<Tensor>("X")->dims();
    auto x_rank = x_dims.size();
G
guosheng 已提交
64
    PADDLE_ENFORCE_LE(x_rank, 6, "Tensors with rank at most 6 are supported.");
65
    int dim = ctx.Attr<int>("dim");
G
guosheng 已提交
66 67 68
    if (dim < 0) dim = x_rank + dim;
    PADDLE_ENFORCE_LT(
        dim, x_rank,
G
guosheng 已提交
69 70 71
        "The dim should be in the range [-rank(input), rank(input)).");
    auto *x_grad =
        ctx.Output<framework::LoDTensor>(framework::GradVarName("X"));
G
guosheng 已提交
72 73 74 75
    if (x_grad) x_grad->Resize(x_dims);
  }
};

G
guosheng 已提交
76
class ReduceOpMaker : public framework::OpProtoAndCheckerMaker {
G
guosheng 已提交
77
 public:
G
guosheng 已提交
78
  ReduceOpMaker(framework::OpProto *proto, framework::OpAttrChecker *op_checker)
G
guosheng 已提交
79 80 81 82 83 84 85
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput(
        "X",
        "(Tensor) The input tensor. Tensors with rank at most 6 are supported");
    AddOutput("Out", "(Tensor) The result tensor.");
    AddAttr<int>("dim",
                 "(int, default 0) The dimension to reduce. "
86 87
                 "Must be in the range [-rank(input), rank(input))")
        .SetDefault(0);
G
guosheng 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
    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 已提交
114 115 116
  }
};

G
guosheng 已提交
117 118 119 120 121 122 123 124 125 126 127
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 已提交
128 129 130
 public:
  ReduceMeanOpMaker(framework::OpProto *proto,
                    framework::OpAttrChecker *op_checker)
G
guosheng 已提交
131 132 133
      : ReduceOpMaker(proto, op_checker) {
    SetComment("ReduceMean", "mean");
    AddComment(comment_);
G
guosheng 已提交
134 135 136
  }
};

G
guosheng 已提交
137
class ReduceMaxOpMaker : public ReduceOpMaker {
G
guosheng 已提交
138 139 140
 public:
  ReduceMaxOpMaker(framework::OpProto *proto,
                   framework::OpAttrChecker *op_checker)
G
guosheng 已提交
141 142 143
      : ReduceOpMaker(proto, op_checker) {
    SetComment("ReduceMax", "max");
    AddComment(comment_);
G
guosheng 已提交
144 145 146
  }
};

G
guosheng 已提交
147
class ReduceMinOpMaker : public ReduceOpMaker {
G
guosheng 已提交
148 149 150
 public:
  ReduceMinOpMaker(framework::OpProto *proto,
                   framework::OpAttrChecker *op_checker)
G
guosheng 已提交
151 152 153
      : ReduceOpMaker(proto, op_checker) {
    SetComment("ReduceMin", "min");
    AddComment(comment_);
G
guosheng 已提交
154 155 156 157 158 159 160 161 162 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
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OP(reduce_sum, ops::ReduceOp, ops::ReduceSumOpMaker, reduce_sum_grad,
            ops::ReduceGradOp);
REGISTER_OP_CPU_KERNEL(
    reduce_sum,
    ops::ReduceKernel<paddle::platform::CPUPlace, float, ops::SumFunctor>);
REGISTER_OP_CPU_KERNEL(reduce_sum_grad,
                       ops::ReduceGradKernel<paddle::platform::CPUPlace, float,
                                             ops::SumGradFunctor>);

REGISTER_OP(reduce_mean, ops::ReduceOp, ops::ReduceMeanOpMaker,
            reduce_mean_grad, ops::ReduceGradOp);
REGISTER_OP_CPU_KERNEL(
    reduce_mean,
    ops::ReduceKernel<paddle::platform::CPUPlace, float, ops::MeanFunctor>);
REGISTER_OP_CPU_KERNEL(reduce_mean_grad,
                       ops::ReduceGradKernel<paddle::platform::CPUPlace, float,
                                             ops::MeanGradFunctor>);

REGISTER_OP(reduce_max, ops::ReduceOp, ops::ReduceMaxOpMaker, reduce_max_grad,
            ops::ReduceGradOp);
REGISTER_OP_CPU_KERNEL(
    reduce_max,
    ops::ReduceKernel<paddle::platform::CPUPlace, float, ops::MaxFunctor>);
REGISTER_OP_CPU_KERNEL(reduce_max_grad,
                       ops::ReduceGradKernel<paddle::platform::CPUPlace, float,
                                             ops::MaxOrMinGradFunctor>);

REGISTER_OP(reduce_min, ops::ReduceOp, ops::ReduceMaxOpMaker, reduce_min_grad,
            ops::ReduceGradOp);
REGISTER_OP_CPU_KERNEL(
    reduce_min,
    ops::ReduceKernel<paddle::platform::CPUPlace, float, ops::MinFunctor>);
REGISTER_OP_CPU_KERNEL(reduce_min_grad,
                       ops::ReduceGradKernel<paddle::platform::CPUPlace, float,
                                             ops::MaxOrMinGradFunctor>);