unpool_op.cc 7.4 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Indicesou 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. */
S
sweetsky0901 已提交
14

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/unpool_op.h"
16
#include <memory>
17 18
#include <string>
#include <vector>
S
sweetsky0901 已提交
19 20 21 22 23
namespace paddle {
namespace operators {

class Unpool2dOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
24
  void Make() override {
S
sweetsky0901 已提交
25 26
    AddInput(
        "X",
S
sweetsky0901 已提交
27 28 29
        "(Tensor) The input tensor of unpool operator. "
        "The format of input tensor is NCHW. Where N is batch size, C is the "
        "number of channels, H and W is the height and width of feature.");
S
sweetsky0901 已提交
30 31
    AddInput(
        "Indices",
S
sweetsky0901 已提交
32 33 34
        "(Tensor) The input tensor of the indices given out by MaxPool2d. "
        "The format of input tensor is NCHW. Where N is batch size, C is the "
        "number of channels, H and W is the height and width of feature.");
S
sweetsky0901 已提交
35
    AddOutput("Out",
S
sweetsky0901 已提交
36 37 38 39 40
              "(Tensor) The output tensor of unpool operator."
              "The format of output tensor is also NCHW."
              "Where N is batch size, C is "
              "the number of channels, H and W is the height and "
              "width of feature.");
S
sweetsky0901 已提交
41 42
    AddAttr<std::vector<int>>(
        "ksize",
S
sweetsky0901 已提交
43
        "(vector), the unpooling window size(height, width) "
S
sweetsky0901 已提交
44
        "of unpooling operator.");
S
sweetsky0901 已提交
45 46 47
    AddAttr<std::vector<int>>("strides",
                              "(vector, default:{1, 1}), "
                              "strides (height, width) of unpooling operator.")
S
sweetsky0901 已提交
48
        .SetDefault({1, 1});
S
sweetsky0901 已提交
49
    AddAttr<std::vector<int>>("paddings",
翟飞跃 已提交
50
                              "(vector default:{0,0}), "
S
sweetsky0901 已提交
51
                              "paddings (height, width) of unpooling operator.")
S
sweetsky0901 已提交
52
        .SetDefault({0, 0});
S
sweetsky0901 已提交
53 54
    AddAttr<std::string>(
        "unpooling_type",
S
sweetsky0901 已提交
55 56
        "(string), unpooling type, can be \"max\" for max-unpooling ")
        .InEnum({"max"});
57 58 59 60 61 62 63 64 65 66
    AddAttr<std::vector<int>>("output_size",
                              "(vector, optional). The shape of output.")
        .SetDefault({0, 0});
    AddAttr<std::string>(
        "data_format",
        "(string, default NCHW) Only used in "
        "An optional string from: \"NHWC\", \"NCHW\". "
        "Defaults to \"NHWC\". Specify the data format of the output data, "
        "the input will be transformed automatically. ")
        .SetDefault("NCHW");
S
sweetsky0901 已提交
67
    AddComment(R"DOC(
Y
ying 已提交
68 69
Input shape is: $(N, C_{in}, H_{in}, W_{in})$, Output shape is:
$(N, C_{out}, H_{out}, W_{out})$, where
Y
ying 已提交
70
$$
P
peizhilin 已提交
71 72
H_{out} = (H_{in}-1) * strides[0] - 2 * paddings[0] + ksize[0] \\
W_{out} = (W_{in}-1) * strides[1] - 2 * paddings[1] + ksize[1]
Y
ying 已提交
73 74 75
$$
Paper: http://www.matthewzeiler.com/wp-content/uploads/2017/07/iccv2011.pdf
)DOC");
S
sweetsky0901 已提交
76 77 78
  }
};

Y
Yang Yang 已提交
79
int UnpoolOutputSize(int input_size, int ksize, int padding, int stride) {
S
sweetsky0901 已提交
80
  int output_size = (input_size - 1) * stride - 2 * padding + ksize;
S
sweetsky0901 已提交
81 82 83 84
  return output_size;
}

class UnpoolOp : public framework::OperatorWithKernel {
S
sweetsky0901 已提交
85
 protected:
86
  framework::OpKernelType GetExpectedKernelType(
S
sweetsky0901 已提交
87
      const framework::ExecutionContext& ctx) const override {
88 89 90
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        ctx.device_context());
S
sweetsky0901 已提交
91
  }
S
sweetsky0901 已提交
92

S
sweetsky0901 已提交
93 94 95
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
  void InferShape(framework::InferShapeContext* ctx) const override {
96 97 98
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "Unpool");
    OP_INOUT_CHECK(ctx->HasInput("Indices"), "Input", "Indices", "Unpool");
    OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "Unpool");
S
sweetsky0901 已提交
99 100
    auto in_x_dims = ctx->GetInputDim("X");
    auto in_y_dims = ctx->GetInputDim("Indices");
S
sweetsky0901 已提交
101 102
    std::string unpooling_type =
        ctx->Attrs().Get<std::string>("unpooling_type");
S
sweetsky0901 已提交
103 104
    std::vector<int> ksize = ctx->Attrs().Get<std::vector<int>>("ksize");
    std::vector<int> strides = ctx->Attrs().Get<std::vector<int>>("strides");
S
sweetsky0901 已提交
105
    std::vector<int> paddings = ctx->Attrs().Get<std::vector<int>>("paddings");
106 107
    std::vector<int> output_size =
        ctx->Attrs().Get<std::vector<int>>("output_size");
108 109
    PADDLE_ENFORCE_EQ(in_x_dims.size() == 4, true,
                      platform::errors::InvalidArgument(
110 111
                          "Unpool Intput(X) must be of 4-dimensional, but "
                          "received Input(X)'s dimensions is %d.",
112
                          in_x_dims.size()));
113 114 115 116 117 118 119
    PADDLE_ENFORCE_EQ(in_x_dims, in_y_dims,
                      platform::errors::InvalidArgument(
                          "The dimensions of Input(X) must equal to be"
                          "the dimensions of Input(Indices), but received"
                          "dimensions of Input(X) is [%d], received dimensions"
                          "of Input(Indices) is [%d]",
                          in_x_dims, in_y_dims));
T
tink2123 已提交
120

S
sweetsky0901 已提交
121 122
    std::vector<int64_t> output_shape({in_x_dims[0], in_x_dims[1]});
    for (size_t i = 0; i < ksize.size(); ++i) {
T
tink2123 已提交
123
      if (!ctx->IsRuntime() && in_x_dims[i + 2] <= 0) {
T
tink2123 已提交
124 125
        output_shape.push_back(-1);
      } else {
126
        output_shape.push_back(output_size[i]);
T
tink2123 已提交
127
      }
S
sweetsky0901 已提交
128 129 130
    }
    ctx->SetOutputDim("Out", framework::make_ddim(output_shape));
  }
S
sweetsky0901 已提交
131 132
};

133 134 135 136
template <typename T>
class UnpoolOpGradMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
137
  void Apply(GradOpPtr<T> op) const override {
138 139 140 141 142 143 144 145 146 147
    op->SetType(this->ForwardOpType() + "_grad");
    op->SetInput("X", this->Input("X"));
    op->SetInput("Indices", this->Input("Indices"));
    op->SetInput("Out", this->Output("Out"));
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetAttrMap(this->Attrs());
  }
};

S
sweetsky0901 已提交
148
class UnpoolOpGrad : public framework::OperatorWithKernel {
S
sweetsky0901 已提交
149
 protected:
150
  framework::OpKernelType GetExpectedKernelType(
S
sweetsky0901 已提交
151
      const framework::ExecutionContext& ctx) const override {
152 153 154
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        ctx.device_context());
S
sweetsky0901 已提交
155
  }
S
sweetsky0901 已提交
156

S
sweetsky0901 已提交
157 158 159
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
  void InferShape(framework::InferShapeContext* ctx) const override {
160 161 162
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "UnpoolGrad");
    OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("X")), "Output",
                   framework::GradVarName("X"), "UnpoolGrad");
S
sweetsky0901 已提交
163 164
    ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X"));
  }
S
sweetsky0901 已提交
165
};
S
sweetsky0901 已提交
166 167
}  // namespace operators
}  // namespace paddle
S
sweetsky0901 已提交
168 169

namespace ops = paddle::operators;
170 171 172
REGISTER_OPERATOR(unpool, ops::UnpoolOp, ops::Unpool2dOpMaker,
                  ops::UnpoolOpGradMaker<paddle::framework::OpDesc>,
                  ops::UnpoolOpGradMaker<paddle::imperative::OpBase>);
H
hong 已提交
173

174
REGISTER_OPERATOR(unpool_grad, ops::UnpoolOpGrad);
S
sweetsky0901 已提交
175
REGISTER_OP_CPU_KERNEL(
Q
QI JUN 已提交
176 177 178 179 180 181
    unpool, ops::UnpoolKernel<paddle::platform::CPUDeviceContext, float>,
    ops::UnpoolKernel<paddle::platform::CPUDeviceContext, double>);
REGISTER_OP_CPU_KERNEL(
    unpool_grad,
    ops::UnpoolGradKernel<paddle::platform::CPUDeviceContext, float>,
    ops::UnpoolGradKernel<paddle::platform::CPUDeviceContext, double>);