fold_op.cc 13.0 KB
Newer Older
X
xiaoting 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
 *
 * 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/fluid/operators/fold_op.h"

namespace paddle {
namespace operators {

class FoldOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE_EQ(
25 26
        ctx->HasInput("X"),
        true,
X
xiaoting 已提交
27 28
        platform::errors::NotFound("Input(X) of FoldOp should not be null"));
    PADDLE_ENFORCE_EQ(
29 30
        ctx->HasOutput("Y"),
        true,
X
xiaoting 已提交
31 32 33 34 35 36 37 38 39 40 41 42
        platform::errors::NotFound("Output(Y) of FoldOp should not be null"));
    auto in_dims = ctx->GetInputDim("X");
    std::vector<int> output_sizes =
        ctx->Attrs().Get<std::vector<int>>("output_sizes");
    std::vector<int> kernel_sizes =
        ctx->Attrs().Get<std::vector<int>>("kernel_sizes");
    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> dilations =
        ctx->Attrs().Get<std::vector<int>>("dilations");

    PADDLE_ENFORCE_EQ(
43 44
        output_sizes.size(),
        2,
X
xiaoting 已提交
45 46 47 48
        platform::errors::InvalidArgument(
            "It is expected output_size equals to 2, but got size %d",
            output_sizes.size()));
    PADDLE_ENFORCE_EQ(
49 50
        kernel_sizes.size(),
        2,
X
xiaoting 已提交
51 52 53 54
        platform::errors::InvalidArgument(
            "It is expected kernel_size equals to 2, but got size %d",
            kernel_sizes.size()));
    PADDLE_ENFORCE_EQ(
55 56
        strides.size(),
        2,
X
xiaoting 已提交
57 58 59 60
        platform::errors::InvalidArgument(
            "It is expected strides_size equals to 2, but got size %d",
            strides.size()));
    PADDLE_ENFORCE_EQ(
61 62
        paddings.size(),
        4,
X
xiaoting 已提交
63 64 65 66
        platform::errors::InvalidArgument(
            "It is expected paddings_size equals to 4, but got size %d",
            paddings.size()));
    PADDLE_ENFORCE_EQ(
67 68
        dilations.size(),
        2,
X
xiaoting 已提交
69 70 71 72 73 74 75 76 77 78 79 80 81 82
        platform::errors::InvalidArgument(
            "It is expected dilations_size equals to 2, but got size %d",
            dilations.size()));

    int output_height = output_sizes[0];
    int output_width = output_sizes[1];
    int kernel_height = kernel_sizes[0];
    int kernel_width = kernel_sizes[1];
    int dilation_height = dilations[0];
    int dilation_width = dilations[1];
    int stride_height = strides[0];
    int stride_width = strides[1];

    // check kernel_sizes
83 84
    PADDLE_ENFORCE_GT(kernel_height,
                      0,
X
xiaoting 已提交
85 86
                      platform::errors::InvalidArgument(
                          "The `kernel_sizes` should be greater than zero, "
87
                          "but received kernel_height: %d kernel_width: %d.",
88 89 90 91
                          kernel_sizes[0],
                          kernel_sizes[1]));
    PADDLE_ENFORCE_GT(kernel_width,
                      0,
X
xiaoting 已提交
92 93
                      platform::errors::InvalidArgument(
                          "The `kernel_sizes` should be greater than zero, "
94
                          "but received kernel_height: %d kernel_width: %d.",
95 96
                          kernel_sizes[0],
                          kernel_sizes[1]));
X
xiaoting 已提交
97
    // check strides
98 99
    PADDLE_ENFORCE_GT(stride_height,
                      0,
X
xiaoting 已提交
100 101
                      platform::errors::InvalidArgument(
                          "The `strides` should be greater than zero, "
102
                          "but received strides_height: %d strides_width: %d.",
103 104 105 106
                          strides[0],
                          strides[1]));
    PADDLE_ENFORCE_GT(stride_width,
                      0,
X
xiaoting 已提交
107 108
                      platform::errors::InvalidArgument(
                          "The `strides` should be greater than zero, "
109
                          "but received strides_height: %d strides_width: %d.",
110 111
                          strides[0],
                          strides[1]));
X
xiaoting 已提交
112
    // check dilations
113 114
    PADDLE_ENFORCE_GT(output_height,
                      1,
X
xiaoting 已提交
115 116
                      platform::errors::InvalidArgument(
                          "The `output_height` should be greater than one, "
117
                          "but received output_height: %d .",
X
xiaoting 已提交
118
                          output_height));
119 120
    PADDLE_ENFORCE_GT(output_width,
                      1,
X
xiaoting 已提交
121 122
                      platform::errors::InvalidArgument(
                          "The `output_width` should be greater than one, "
123
                          "but received output_width: %d .",
X
xiaoting 已提交
124 125
                          output_width));
    // check output size
X
xiaoting 已提交
126
    PADDLE_ENFORCE_GT(
127 128
        dilation_height,
        0,
X
xiaoting 已提交
129 130
        platform::errors::InvalidArgument(
            "The `dilations` should be greater than zero, "
131
            "but received dilations_height: %d dilations_width: %d.",
132 133
            dilations[0],
            dilations[1]));
X
xiaoting 已提交
134
    PADDLE_ENFORCE_GT(
135 136
        dilation_width,
        0,
X
xiaoting 已提交
137 138
        platform::errors::InvalidArgument(
            "The `dilations` should be greater than zero, "
139
            "but received dilations_height: %d dilations_width: %d.",
140 141
            dilations[0],
            dilations[1]));
X
xiaoting 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160

    std::vector<int> out_dims;
    // batch_size
    out_dims.push_back(in_dims[0]);
    // output_plane
    int output_channels = in_dims[1] / (kernel_width * kernel_height);
    out_dims.push_back(output_channels);

    int blocks_height = (output_sizes[0] + 2 * paddings[0] -
                         (dilations[0] * (kernel_sizes[0] - 1) + 1)) /
                            strides[0] +
                        1;
    int blocks_width = (output_sizes[1] + 2 * paddings[1] -
                        (dilations[1] * (kernel_sizes[1] - 1) + 1)) /
                           strides[1] +
                       1;

    // check output height and width
    PADDLE_ENFORCE_GT(
161 162
        blocks_height,
        0,
X
xiaoting 已提交
163 164 165 166
        platform::errors::InvalidArgument(
            "The sliding blocks calculated from input spatial size (%d, %d), "
            "kernel_sizes (%d, %d), strides (%d, %d), dilations (%d, %d), "
            "is (%d, %d), which should be a positive integer.",
167 168 169 170 171 172 173 174 175
            in_dims[2],
            in_dims[3],
            kernel_sizes[0],
            kernel_sizes[1],
            strides[0],
            strides[1],
            dilations[0],
            dilations[1],
            output_height,
X
xiaoting 已提交
176 177 178
            output_width));

    PADDLE_ENFORCE_GT(
179 180
        blocks_width,
        0,
X
xiaoting 已提交
181 182 183 184
        platform::errors::InvalidArgument(
            "The sliding blocks calculated from input spatial size (%d, %d), "
            "kernel_sizes (%d, %d), strides (%d, %d), dilations (%d, %d), "
            "is (%d, %d), which should be a positive integer.",
185 186 187 188 189 190 191 192 193
            in_dims[2],
            in_dims[3],
            kernel_sizes[0],
            kernel_sizes[1],
            strides[0],
            strides[1],
            dilations[0],
            dilations[1],
            output_height,
X
xiaoting 已提交
194 195 196
            output_width));

    PADDLE_ENFORCE_EQ(
197 198
        blocks_height * blocks_width,
        in_dims[2],
X
xiaoting 已提交
199 200 201 202 203
        platform::errors::InvalidArgument(
            "Given input output_size (%d, %d), "
            "kernel_sizes (%d, %d), strides (%d, %d), dilations (%d, %d), "
            "which should be expected size of input's dimension "
            "2 to match the calculated number of %d * %d = %d, but got %d",
204 205 206 207 208 209 210 211 212 213 214 215
            output_height,
            output_width,
            kernel_sizes[0],
            kernel_sizes[1],
            strides[0],
            strides[1],
            dilations[0],
            dilations[1],
            blocks_height,
            blocks_width,
            blocks_height * blocks_width,
            in_dims[2]));
X
xiaoting 已提交
216

X
xiaoting 已提交
217
    PADDLE_ENFORCE_EQ(
218 219
        in_dims[1] % (kernel_sizes[0] * kernel_sizes[1]),
        0,
X
xiaoting 已提交
220 221 222 223 224
        platform::errors::InvalidArgument(
            "Expected size of input's dimension 1 to be divisible by the"
            "product of kernel_size, but got input.size(1)=%d and "
            "kernel_size=( %d"
            ", %d).",
225 226 227
            in_dims[1],
            kernel_sizes[0],
            kernel_sizes[1]));
X
xiaoting 已提交
228

X
xiaoting 已提交
229 230
    out_dims.push_back(output_height);
    out_dims.push_back(output_width);
231
    ctx->SetOutputDim("Y", phi::make_ddim(out_dims));
X
xiaoting 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
  }

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

class FoldOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X",
             "Tensor, "
             "the input of fold op. "
             "The format of X is [N, C_in, L], "
             "where N is the batch size, C_in is the input channels, "
             "L is the length");
    AddOutput("Y",
              "Tensor, "
              "the output of unfold op. "
              "The format of Y is [N, C_out, output_height, output_width], "
              "where N is the batch size, "
              "C_in is the output channels of Y, output_height and "
              "output_width "
              "is the calculated height and width of output feature map.");
    AddAttr<std::vector<int>>(
        "output_sizes",
        "vector<int>, the output sizes of the convolution operator.");
    AddAttr<std::vector<int>>(
        "kernel_sizes",
        "vector<int>, the kernel sizes of the convolution operator.");
    AddAttr<std::vector<int>>(
        "strides", "vector<int>, the strides of the convolution operator.");
    AddAttr<std::vector<int>>(
        "paddings",
        "vector<int>, the paddings applied to pad the feature map.");
    AddAttr<std::vector<int>>(
        "dilations", "vector<int>, the dilations of the convolution operator.");
    AddComment(R"DOC(
**Fold Operator**

This Operator is used to combines an array of sliding local blocks into a large containing
tensor. also known as col2im when operated on batched 2D image tensor. Fold calculates each 
combined value in the resulting large tensor by summing all values from all containing blocks. 
Unfold extracts the values in the local blocks by copying from the large tensor. So, if the 
blocks overlap, they are not inverses of each other.
    )DOC");
  }
};

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

  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE_EQ(
291 292
        ctx->HasInput(framework::GradVarName("Y")),
        true,
X
xiaoting 已提交
293 294
        platform::errors::NotFound("The gradient of Y should not be null"));
    PADDLE_ENFORCE_EQ(
295 296
        ctx->HasInput("X"),
        true,
X
xiaoting 已提交
297 298
        platform::errors::NotFound("The input X should not be null"));
    PADDLE_ENFORCE_EQ(
299 300
        ctx->HasOutput(framework::GradVarName("X")),
        true,
X
xiaoting 已提交
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
        platform::errors::NotFound("The gradient of X should not be null"));
    ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X"));
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
                                       ctx, framework::GradVarName("Y")),
                                   ctx.device_context());
  }
};

template <typename T>
class FoldGradMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
  void Apply(GradOpPtr<T> op) const override {
    op->SetType("fold_grad");
    op->SetInput(framework::GradVarName("Y"), this->OutputGrad("Y"));
    op->SetInput("X", this->Input("X"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetAttrMap(this->Attrs());
  }
};

DECLARE_NO_NEED_BUFFER_VARS_INFERER(FoldGradOpNoNeedBufferVarsInferer, "X");

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
335 336 337
REGISTER_OPERATOR(fold,
                  ops::FoldOp,
                  ops::FoldOpMaker,
X
xiaoting 已提交
338 339
                  ops::FoldGradMaker<paddle::framework::OpDesc>,
                  ops::FoldGradMaker<paddle::imperative::OpBase>);
340 341
REGISTER_OPERATOR(fold_grad,
                  ops::FoldGradOp,
X
xiaoting 已提交
342 343
                  ops::FoldGradOpNoNeedBufferVarsInferer);

L
Leo Chen 已提交
344 345 346 347 348 349
REGISTER_OP_CPU_KERNEL(fold,
                       ops::FoldOpKernel<phi::CPUContext, float>,
                       ops::FoldOpKernel<phi::CPUContext, double>);
REGISTER_OP_CPU_KERNEL(fold_grad,
                       ops::FoldGradOpKernel<phi::CPUContext, float>,
                       ops::FoldGradOpKernel<phi::CPUContext, double>);