unpool_op.cc 14.1 KB
Newer Older
1
/* Copyright (c) 2022 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

17
#include <memory>
18 19
#include <string>
#include <vector>
S
sweetsky0901 已提交
20 21 22 23 24
namespace paddle {
namespace operators {

class Unpool2dOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
25
  void Make() override {
S
sweetsky0901 已提交
26 27
    AddInput(
        "X",
S
sweetsky0901 已提交
28 29 30
        "(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 已提交
31 32
    AddInput(
        "Indices",
S
sweetsky0901 已提交
33 34 35
        "(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 已提交
36
    AddOutput("Out",
S
sweetsky0901 已提交
37 38 39 40 41
              "(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 已提交
42 43
    AddAttr<std::vector<int>>(
        "ksize",
S
sweetsky0901 已提交
44
        "(vector), the unpooling window size(height, width) "
S
sweetsky0901 已提交
45
        "of unpooling operator.");
S
sweetsky0901 已提交
46 47 48
    AddAttr<std::vector<int>>("strides",
                              "(vector, default:{1, 1}), "
                              "strides (height, width) of unpooling operator.")
S
sweetsky0901 已提交
49
        .SetDefault({1, 1});
S
sweetsky0901 已提交
50
    AddAttr<std::vector<int>>("paddings",
翟飞跃 已提交
51
                              "(vector default:{0,0}), "
S
sweetsky0901 已提交
52
                              "paddings (height, width) of unpooling operator.")
S
sweetsky0901 已提交
53
        .SetDefault({0, 0});
S
sweetsky0901 已提交
54 55
    AddAttr<std::string>(
        "unpooling_type",
S
sweetsky0901 已提交
56 57
        "(string), unpooling type, can be \"max\" for max-unpooling ")
        .InEnum({"max"});
58 59 60 61 62 63 64 65 66 67
    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 已提交
68
    AddComment(R"DOC(
Y
ying 已提交
69 70
Input shape is: $(N, C_{in}, H_{in}, W_{in})$, Output shape is:
$(N, C_{out}, H_{out}, W_{out})$, where
Y
ying 已提交
71
$$
P
peizhilin 已提交
72 73
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 已提交
74 75 76
$$
Paper: http://www.matthewzeiler.com/wp-content/uploads/2017/07/iccv2011.pdf
)DOC");
S
sweetsky0901 已提交
77 78 79
  }
};

80 81 82 83 84 85 86 87 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 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
class Unpool3dOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput(
        "X",
        "(Tensor) The input tensor of unpool 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 "
        "feature.");
    AddInput(
        "Indices",
        "(Tensor) The input tensor of the indices given out by MaxPool3d. "
        "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 "
        "feature.");
    AddOutput("Out",
              "(Tensor) The output tensor of unpool operator."
              "The format of output tensor is also NCDHW."
              "Where N is batch size, C is "
              "the number of channels, D, H and W is the depth, height and "
              "width of feature.");
    AddAttr<std::vector<int>>(
        "ksize",
        "(vector), the unpooling window size(depth, height, width) "
        "of unpooling operator.");
    AddAttr<std::vector<int>>(
        "strides",
        "(vector, default:{1, 1, 1}), "
        "strides (depth, height, width) of unpooling operator.")
        .SetDefault({1, 1, 1});
    AddAttr<std::vector<int>>(
        "paddings",
        "(vector default:{0, 0,0}), "
        "paddings (depth, height, width) of unpooling operator.")
        .SetDefault({0, 0, 0});
    AddAttr<std::string>(
        "unpooling_type",
        "(string), unpooling type, can be \"max\" for max-unpooling ")
        .InEnum({"max"});
    AddAttr<std::vector<int>>("output_size",
                              "(vector, optional). The shape of output.")
        .SetDefault({0, 0, 0});
    AddAttr<std::string>(
        "data_format",
        "(string, default NCDHW)"
        "Defaults to \"NCDHW\". Specify the data format of the output data, ")
        .SetDefault("NCDHW");
    AddComment(R"DOC(
Input shape is: $(N, C_{in}, D_{in}, H_{in}, W_{in})$, Output shape is:
$(N, C_{out}, D_{out}, H_{out}, W_{out})$, where
$$
D_{out} = (D_{in}-1) * strides[0] - 2 * paddings[0] + ksize[0] \\
H_{out} = (H_{in}-1) * strides[1] - 2 * paddings[1] + ksize[1] \\
W_{out} = (W_{in}-1) * strides[2] - 2 * paddings[2] + ksize[2]
$$
)DOC");
  }
};

Y
Yang Yang 已提交
139
int UnpoolOutputSize(int input_size, int ksize, int padding, int stride) {
S
sweetsky0901 已提交
140
  int output_size = (input_size - 1) * stride - 2 * padding + ksize;
S
sweetsky0901 已提交
141 142 143 144
  return output_size;
}

class UnpoolOp : public framework::OperatorWithKernel {
S
sweetsky0901 已提交
145
 protected:
146
  framework::OpKernelType GetExpectedKernelType(
S
sweetsky0901 已提交
147
      const framework::ExecutionContext& ctx) const override {
148 149 150
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        ctx.device_context());
S
sweetsky0901 已提交
151
  }
S
sweetsky0901 已提交
152

S
sweetsky0901 已提交
153 154 155
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
  void InferShape(framework::InferShapeContext* ctx) const override {
156 157 158
    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 已提交
159 160
    auto in_x_dims = ctx->GetInputDim("X");
    auto in_y_dims = ctx->GetInputDim("Indices");
S
sweetsky0901 已提交
161 162
    std::string unpooling_type =
        ctx->Attrs().Get<std::string>("unpooling_type");
S
sweetsky0901 已提交
163 164
    std::vector<int> ksize = ctx->Attrs().Get<std::vector<int>>("ksize");
    std::vector<int> strides = ctx->Attrs().Get<std::vector<int>>("strides");
S
sweetsky0901 已提交
165
    std::vector<int> paddings = ctx->Attrs().Get<std::vector<int>>("paddings");
166 167
    std::vector<int> output_size =
        ctx->Attrs().Get<std::vector<int>>("output_size");
168 169
    PADDLE_ENFORCE_EQ(in_x_dims.size() == 4,
                      true,
170
                      platform::errors::InvalidArgument(
171 172
                          "Unpool Intput(X) must be of 4-dimensional, but "
                          "received Input(X)'s dimensions is %d.",
173
                          in_x_dims.size()));
174 175
    PADDLE_ENFORCE_EQ(in_x_dims,
                      in_y_dims,
176 177 178 179 180
                      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]",
181 182
                          in_x_dims,
                          in_y_dims));
T
tink2123 已提交
183

S
sweetsky0901 已提交
184 185
    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 已提交
186
      if (!ctx->IsRuntime() && in_x_dims[i + 2] <= 0) {
T
tink2123 已提交
187 188
        output_shape.push_back(-1);
      } else {
189
        output_shape.push_back(output_size[i]);
T
tink2123 已提交
190
      }
S
sweetsky0901 已提交
191
    }
192
    ctx->SetOutputDim("Out", phi::make_ddim(output_shape));
S
sweetsky0901 已提交
193
  }
S
sweetsky0901 已提交
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
class Unpool3dOp : public framework::OperatorWithKernel {
 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        ctx.device_context());
  }

 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
  void InferShape(framework::InferShapeContext* ctx) const override {
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "Unpool3d");
    OP_INOUT_CHECK(ctx->HasInput("Indices"), "Input", "Indices", "Unpool3d");
    OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "Unpool3d");
    auto in_x_dims = ctx->GetInputDim("X");
    auto in_y_dims = ctx->GetInputDim("Indices");
    std::string unpooling_type =
        ctx->Attrs().Get<std::string>("unpooling_type");
    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");
    std::vector<int> output_size =
        ctx->Attrs().Get<std::vector<int>>("output_size");
220 221
    PADDLE_ENFORCE_EQ(in_x_dims.size() == 5,
                      true,
222 223 224 225
                      platform::errors::InvalidArgument(
                          "Unpool Intput(X) must be of 5-dimensional, but "
                          "received Input(X)'s dimensions is %d.",
                          in_x_dims.size()));
226 227
    PADDLE_ENFORCE_EQ(in_x_dims,
                      in_y_dims,
228 229 230 231 232
                      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]",
233 234
                          in_x_dims,
                          in_y_dims));
235 236 237 238 239 240 241 242 243

    std::vector<int64_t> output_shape({in_x_dims[0], in_x_dims[1]});
    for (size_t i = 0; i < ksize.size(); ++i) {
      if (!ctx->IsRuntime() && in_x_dims[i + 2] <= 0) {
        output_shape.push_back(-1);
      } else {
        output_shape.push_back(output_size[i]);
      }
    }
244
    ctx->SetOutputDim("Out", phi::make_ddim(output_shape));
245 246 247
  }
};

248 249 250 251
template <typename T>
class UnpoolOpGradMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
252
  void Apply(GradOpPtr<T> op) const override {
253 254 255 256 257 258 259 260 261 262
    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());
  }
};

263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
template <typename T>
class Unpool3dOpGradMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
  void Apply(GradOpPtr<T> op) const override {
    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 已提交
278
class UnpoolOpGrad : public framework::OperatorWithKernel {
S
sweetsky0901 已提交
279
 protected:
280
  framework::OpKernelType GetExpectedKernelType(
S
sweetsky0901 已提交
281
      const framework::ExecutionContext& ctx) const override {
282 283 284
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        ctx.device_context());
S
sweetsky0901 已提交
285
  }
S
sweetsky0901 已提交
286

S
sweetsky0901 已提交
287 288 289
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
  void InferShape(framework::InferShapeContext* ctx) const override {
290
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "UnpoolGrad");
291 292 293 294
    OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("X")),
                   "Output",
                   framework::GradVarName("X"),
                   "UnpoolGrad");
S
sweetsky0901 已提交
295 296
    ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X"));
  }
S
sweetsky0901 已提交
297
};
298 299 300 301 302 303 304 305 306 307 308 309 310 311

class Unpool3dOpGrad : public framework::OperatorWithKernel {
 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        ctx.device_context());
  }

 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
  void InferShape(framework::InferShapeContext* ctx) const override {
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "Unpool3dGrad");
312 313 314 315
    OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("X")),
                   "Output",
                   framework::GradVarName("X"),
                   "Unpool3dGrad");
316 317 318 319
    ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X"));
  }
};

S
sweetsky0901 已提交
320 321
}  // namespace operators
}  // namespace paddle
S
sweetsky0901 已提交
322 323

namespace ops = paddle::operators;
324 325 326
REGISTER_OPERATOR(unpool,
                  ops::UnpoolOp,
                  ops::Unpool2dOpMaker,
327 328
                  ops::UnpoolOpGradMaker<paddle::framework::OpDesc>,
                  ops::UnpoolOpGradMaker<paddle::imperative::OpBase>);
H
hong 已提交
329

330
REGISTER_OPERATOR(unpool_grad, ops::UnpoolOpGrad);
L
Leo Chen 已提交
331 332 333 334 335 336
REGISTER_OP_CPU_KERNEL(unpool,
                       ops::UnpoolKernel<phi::CPUContext, float>,
                       ops::UnpoolKernel<phi::CPUContext, double>);
REGISTER_OP_CPU_KERNEL(unpool_grad,
                       ops::UnpoolGradKernel<phi::CPUContext, float>,
                       ops::UnpoolGradKernel<phi::CPUContext, double>);
337

338 339 340
REGISTER_OPERATOR(unpool3d,
                  ops::Unpool3dOp,
                  ops::Unpool3dOpMaker,
341 342 343 344
                  ops::Unpool3dOpGradMaker<paddle::framework::OpDesc>,
                  ops::Unpool3dOpGradMaker<paddle::imperative::OpBase>);

REGISTER_OPERATOR(unpool3d_grad, ops::Unpool3dOpGrad);
L
Leo Chen 已提交
345 346 347 348 349 350
REGISTER_OP_CPU_KERNEL(unpool3d,
                       ops::Unpool3dKernel<phi::CPUContext, float>,
                       ops::Unpool3dKernel<phi::CPUContext, double>);
REGISTER_OP_CPU_KERNEL(unpool3d_grad,
                       ops::Unpool3dGradKernel<phi::CPUContext, float>,
                       ops::Unpool3dGradKernel<phi::CPUContext, double>);