pool_op.cc 7.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/* 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/pool_op.h"

namespace paddle {
namespace operators {

C
chengduoZH 已提交
20
int OutputSizePool(int input_size, int filter_size, int padding, int stride) {
21 22 23 24 25 26 27 28 29
  int output_size = (input_size - filter_size + 2 * padding) / stride + 1;
  return output_size;
}

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

 protected:
30
  void InferShape(framework::InferShapeContext *ctx) const override {
31 32 33 34 35 36 37 38 39 40 41
    PADDLE_ENFORCE(ctx->HasInput("X"),
                   "X(Input) of Pooling should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput("Out"),
                   "Out(Output) of Pooling should not be null.");

    auto in_x_dims = ctx->GetInputDim("X");

    std::string pooling_type = ctx->Attrs().Get<std::string>("poolingType");
    std::vector<int> ksize = ctx->Attrs().Get<std::vector<int>>("ksize");
    std::vector<int> strides = ctx->Attrs().Get<std::vector<int>>("strides");
    std::vector<int> paddings = ctx->Attrs().Get<std::vector<int>>("paddings");
42

C
chengduoZH 已提交
43 44
    PADDLE_ENFORCE(pooling_type == "max" || pooling_type == "avg",
                   "pooling_type should be 'max' or 'avg'");
45
    PADDLE_ENFORCE(in_x_dims.size() == 4 || in_x_dims.size() == 5,
C
chengduoZH 已提交
46
                   "Pooling intput should be 4-D or 5-D");
47

48 49
    if (ctx->Attrs().Get<bool>("globalPooling")) {
      ksize.resize(static_cast<size_t>(in_x_dims.size()) - 2);
50
      for (size_t i = 0; i < ksize.size(); ++i)
51
        ksize[i] = static_cast<int>(in_x_dims[i + 2]);
52 53
    }

54
    PADDLE_ENFORCE(in_x_dims.size() - ksize.size() == 2U,
55
                   "Input size and Pooling size should be consistent.");
C
chengduoZH 已提交
56 57 58 59 60 61
    PADDLE_ENFORCE(ksize.size() == 2 || ksize.size() == 3,
                   "Pooling size should be 2 elements. or 3 elements.");
    PADDLE_ENFORCE_EQ(ksize.size(), strides.size(),
                      "strides size and pooling size should be the same.");
    PADDLE_ENFORCE_EQ(ksize.size(), paddings.size(),
                      "paddings size and pooling size should be the same.");
62

63
    std::vector<int64_t> output_shape({in_x_dims[0], in_x_dims[1]});
64
    for (size_t i = 0; i < ksize.size(); ++i) {
65 66
      output_shape.push_back(
          OutputSizePool(in_x_dims[i + 2], ksize[i], paddings[i], strides[i]));
67
    }
68
    ctx->SetOutputDim("Out", framework::make_ddim(output_shape));
69 70 71 72 73 74 75 76
  }
};

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

 protected:
77
  void InferShape(framework::InferShapeContext *ctx) const override {
78 79 80 81 82
    PADDLE_ENFORCE(ctx->HasInput("X"),
                   "X(Input) of Pooling should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("X")),
                   "Input@Grad of Pooling should not be null.");
    ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X"));
83 84 85
  }
};

C
chengduoZH 已提交
86
class Pool2dOpMaker : public framework::OpProtoAndCheckerMaker {
87
 public:
C
chengduoZH 已提交
88
  Pool2dOpMaker(framework::OpProto *proto, framework::OpAttrChecker *op_checker)
89 90
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput(
91
        "X",
92
        "The input tensor of pooling operator. "
C
chengduoZH 已提交
93
        "The format of input tensor is NCHW. Where N is batch size, C is the "
C
chengduoZH 已提交
94
        "number of channels, H and W is the height and width of feature.");
95
    AddOutput("Out",
96
              "The output tensor of pooling operator."
C
chengduoZH 已提交
97
              "The format of output tensor is also NCHW.");
98

99
    AddAttr<std::string>("poolingType",
100 101 102
                         "PoolingType of pooling operator."
                         "Str constant equal to 'max' or 'avg'.")
        .InEnum({"max", "avg"});
103
    AddAttr<std::vector<int>>(
104 105
        "ksize",
        "Pooling size(depth, height, width) of pooling operator."
106 107
        "If globalPooling = true, ksize is ignored and need not be "
        "specified.");  // TODO(Add checker)
108
    AddAttr<bool>(
C
chengduoZH 已提交
109
        "globalPooling",
110 111 112
        "Whether to use the globalPooling."
        "Bool constant equal to false or true."
        "Default false."
113 114
        "If globalPooling = true, ksize is ignored and need not be specified.")
        .SetDefault(false);
C
chengduoZH 已提交
115
    AddAttr<std::vector<int>>("strides",
116 117 118
                              "Strides(height, width) of pooling operator."
                              "Default {1,1}")
        .SetDefault({1, 1});  // TODO(Add checker)
C
chengduoZH 已提交
119
    AddAttr<std::vector<int>>("paddings",
120 121 122
                              "Paddings(height, width) of pooling operator."
                              "Default {0,0}.")
        .SetDefault({0, 0});  // TODO(Add checker)
123
    AddComment(R"DOC(
C
chengduoZH 已提交
124
The pooling2d operation calculates the output based on
125
the input, poolingType and ksize, strides, paddings parameters.
126 127 128
)DOC");
  }
};
129

C
chengduoZH 已提交
130
class Pool3dOpMaker : public framework::OpProtoAndCheckerMaker {
131
 public:
C
chengduoZH 已提交
132
  Pool3dOpMaker(framework::OpProto *proto, framework::OpAttrChecker *op_checker)
133
      : OpProtoAndCheckerMaker(proto, op_checker) {
C
chengduoZH 已提交
134 135 136 137 138
    AddInput("X",
             "The input tensor of pooling operator. "
             "The format of input tensor is NCDHW. Where N is batch size, C is "
             "the "
             "number of channels, D, H and W is the depth, height and width of "
C
chengduoZH 已提交
139
             "feature.");
140
    AddOutput("Out",
141
              "The output tensor of pooling operator."
C
chengduoZH 已提交
142
              "The format of output tensor is also NCDHW.");
143

144
    AddAttr<std::string>("poolingType",
145 146 147
                         "PoolingType of pooling operator."
                         "str constant equal to 'max' or 'avg'.")
        .InEnum({"max", "avg"});
148
    AddAttr<std::vector<int>>(
149
        "ksize",
150 151 152
        "Pooling size(depth, height, width) of pooling operator."
        "If globalPooling = true, ksize is ignored and need not be "
        "specified.");  // TODO(Add checker)
153
    AddAttr<bool>(
C
chengduoZH 已提交
154
        "globalPooling",
155 156 157
        "Whether to use the globalPooling."
        "Bool constant equal to false or true."
        "Default false."
158 159
        "If globalPooling = true, ksize is ignored and need not be specified.")
        .SetDefault(false);
C
chengduoZH 已提交
160 161
    AddAttr<std::vector<int>>(
        "strides",
162 163 164
        "Strides(depth, height, width) of pooling operator."
        "Default {1,1,1}.")
        .SetDefault({1, 1, 1});  // TODO(Add checker)
C
chengduoZH 已提交
165 166
    AddAttr<std::vector<int>>(
        "paddings",
167 168 169
        "Paddings(depth, height, width) of pooling operator."
        "Default {0,0,0}.")
        .SetDefault({0, 0, 0});  // TODO(Add checker)
170
    AddComment(R"DOC(
C
chengduoZH 已提交
171
The pooling3d operation calculates the output based on
172
the input, poolingType and ksize, strides, paddings parameters.
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
)DOC");
  }
};
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OP(pool2d, ops::PoolOp, ops::Pool2dOpMaker, pool2d_grad,
            ops::PoolOpGrad);

REGISTER_OP_CPU_KERNEL(pool2d,
                       ops::PoolKernel<paddle::platform::CPUPlace, float>);
REGISTER_OP_CPU_KERNEL(pool2d_grad,
                       ops::PoolGradKernel<paddle::platform::CPUPlace, float>)

REGISTER_OP(pool3d, ops::PoolOp, ops::Pool3dOpMaker, pool3d_grad,
            ops::PoolOpGrad);

REGISTER_OP_CPU_KERNEL(pool3d,
                       ops::PoolKernel<paddle::platform::CPUPlace, float>);
REGISTER_OP_CPU_KERNEL(pool3d_grad,
                       ops::PoolGradKernel<paddle::platform::CPUPlace, float>);