affine_grid_op.cc 11.5 KB
Newer Older
W
whs 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2018 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. */

15
#include <memory>
W
whs 已提交
16
#include <string>
17
#include <vector>
18

19
#include "paddle/fluid/framework/infershape_utils.h"
W
whs 已提交
20
#include "paddle/fluid/framework/op_registry.h"
W
whs 已提交
21
#include "paddle/fluid/framework/op_version_registry.h"
22
#include "paddle/fluid/platform/device/gpu/gpu_dnn.h"
23 24 25 26
#include "paddle/fluid/platform/for_range.h"
#include "paddle/phi/core/infermeta_utils.h"
#include "paddle/phi/infermeta/backward.h"
#include "paddle/phi/infermeta/unary.h"
W
whs 已提交
27 28 29 30 31 32 33 34 35 36

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;

class AffineGridOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
  void InferShape(framework::InferShapeContext* ctx) const override {
37 38
    PADDLE_ENFORCE_EQ(ctx->HasInput("Theta"),
                      true,
39 40
                      platform::errors::NotFound(
                          "The input 'Theta' of AffineGridOp is not found."));
41 42
    PADDLE_ENFORCE_EQ(ctx->HasOutput("Output"),
                      true,
43 44
                      platform::errors::NotFound(
                          "The output 'Output' of AffineGridOp is not found."));
W
whs 已提交
45
    auto theta_dims = ctx->GetInputDim("Theta");
46
    PADDLE_ENFORCE_EQ(
47 48
        theta_dims.size(),
        3,
49 50 51
        platform::errors::InvalidArgument(
            "The input Theta's dimensions size should be 3. But received "
            "Theta's demensions size=[%d],  Theta's dimensions=[%s].",
52 53
            theta_dims.size(),
            theta_dims));
W
whs 已提交
54 55 56

    auto output_shape = ctx->Attrs().Get<std::vector<int>>("output_shape");
    if (output_shape.size() == 0) {
57
      PADDLE_ENFORCE_EQ(
58 59
          ctx->HasInput("OutputShape"),
          true,
60 61 62
          platform::errors::NotFound(
              "The input 'OutputShape' of AffineGridOp should not be null if "
              "'output_shape' is not configured."));
W
whs 已提交
63
      auto output_shape_dims = ctx->GetInputDim("OutputShape");
64
      PADDLE_ENFORCE_EQ(
65 66
          output_shape_dims.size(),
          1,
67 68 69 70
          platform::errors::InvalidArgument(
              "The dimesions size of input OutputShape in AffineGridOp should "
              "be 1. But received OutputShape's  dimesions size=[%d], "
              "OutputShape's  dimesions=[%s]",
71 72
              output_shape_dims.size(),
              output_shape_dims));
W
whs 已提交
73
    } else {
74 75 76 77 78 79 80 81 82 83 84 85 86 87
      PADDLE_ENFORCE_GE(output_shape.size(),
                        4,
                        platform::errors::InvalidArgument(
                            "The size of attribute 'output_shape' in "
                            "AffineGridOp should be >= "
                            "4. But received output_shape's size=[%d].",
                            output_shape.size()));
      PADDLE_ENFORCE_LE(output_shape.size(),
                        5,
                        platform::errors::InvalidArgument(
                            "The size of attribute 'output_shape' in "
                            "AffineGridOp should be <= "
                            "5. But received output_shape's size=[%d].",
                            output_shape.size()));
W
whs 已提交
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
    PADDLE_ENFORCE_GE(theta_dims[1],
                      2,
                      platform::errors::InvalidArgument(
                          "The second dimesion of input 'theta' in "
                          "AffineGridOp should be >= 2. "
                          "But received second dimesion=[%d], dimesions=[%s]",
                          theta_dims[1],
                          theta_dims));
    PADDLE_ENFORCE_LE(theta_dims[1],
                      3,
                      platform::errors::InvalidArgument(
                          "The second dimesion of input 'theta' in "
                          "AffineGridOp should be <= 3. "
                          "But received second dimesion=[%d], dimesions=[%s]",
                          theta_dims[1],
                          theta_dims));
    PADDLE_ENFORCE_GE(theta_dims[2],
                      3,
                      platform::errors::InvalidArgument(
                          "The third dimesion of input 'theta' in AffineGridOp "
                          "should be >= 3. "
                          "But received third dimesion=[%d], dimesions=[%s]",
                          theta_dims[2],
                          theta_dims));
    PADDLE_ENFORCE_LE(theta_dims[2],
                      4,
                      platform::errors::InvalidArgument(
                          "The third dimesion of input 'theta' in AffineGridOp "
                          "should be <= 4. "
                          "But received third dimesion=[%d], dimesions=[%s]",
                          theta_dims[2],
                          theta_dims));
122

123 124 125 126 127 128 129 130
    if (output_shape.size() == 4) {
      // N * H * W * 2
      ctx->SetOutputDim("Output", phi::make_ddim({theta_dims[0], -1, -1, 2}));
    } else {
      // N * D * H * W * 3
      ctx->SetOutputDim("Output",
                        phi::make_ddim({theta_dims[0], -1, -1, -1, 3}));
    }
W
whs 已提交
131 132 133 134 135 136 137
    ctx->ShareLoD("Theta", "Output");
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    framework::LibraryType library{framework::LibraryType::kPlain};
138
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
W
whs 已提交
139 140 141 142
    if (platform::CanCUDNNBeUsed(ctx)) {
      library = framework::LibraryType::kCUDNN;
    }
#endif
143
    auto data_type = OperatorWithKernel::IndicateVarDataType(ctx, "Theta");
144 145
    return framework::OpKernelType(
        data_type, ctx.GetPlace(), framework::DataLayout::kAnyLayout, library);
W
whs 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
  }
};

class AffineGridOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput(
        "Theta",
        "(Tensor) A batch of affine transform parameters with shape [N, 2, 3]. "
        "It is used to transform coordinate (x_0, y_0) to coordinate (x_1, "
        "y_1).");
    AddInput("OutputShape",
             "(Tensor) The shape of target image with format [N, C, H, W].")
        .AsDispensable();
    AddOutput("Output", "(Tensor) Output Tensor with shape [N, H, W, 2].");
161 162
    AddAttr<bool>("align_corners",
                  "(bool, default false) Whether to align the corners of input"
163
                  "and output.")
164
        .SetDefault(true);
W
whs 已提交
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 197 198
    AddAttr<std::vector<int>>(
        "output_shape",
        "The target output image shape with format [N, C, H, W].")
        .SetDefault(std::vector<int>());

    AddComment(R"DOC(
    It generates a grid of (x,y) coordinates using the parameters of the
    affine transformation that correspond to a set of points where the input
    feature map should be sampled to produce the transformed output feature map.

    Given:
        Theta = [[[x_11, x_12, x_13]
                  [x_14, x_15, x_16]]
                 [[x_21, x_22, x_23]
                  [x_24, x_25, x_26]]]
    
        OutputShape = [2, 3, 5, 5]

    Step 1:

        Generate relative coordinates according to OutputShape.
        The values of relative coordinates are in the interval between -1 and 1.
        The shape of the relative coordinates is [2, H, W] as below:
    
        C = [[[-1.  -1.  -1.  -1.  -1. ]
              [-0.5 -0.5 -0.5 -0.5 -0.5]
              [ 0.   0.   0.   0.   0. ]
              [ 0.5  0.5  0.5  0.5  0.5]
              [ 1.   1.   1.   1.   1. ]] 
             [[-1.  -0.5  0.   0.5  1. ]
              [-1.  -0.5  0.   0.5  1. ]
              [-1.  -0.5  0.   0.5  1. ]
              [-1.  -0.5  0.   0.5  1. ]
              [-1.  -0.5  0.   0.5  1. ]]]
199 200
        C[0] is the coordinates in height axis and  C[1] is the coordinates in
        width axis.
W
whs 已提交
201 202
    
    Step2:
203 204
        Tanspose and reshape C to shape [H * W, 2] and append ones to last
        dimension. The we get:
W
whs 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
        C_ = [[-1.  -1.   1. ]
              [-0.5 -1.   1. ]
              [ 0.  -1.   1. ]
              [ 0.5 -1.   1. ]
              [ 1.  -1.   1. ]
              [-1.  -0.5  1. ]
              [-0.5 -0.5  1. ]
              [ 0.  -0.5  1. ]
              [ 0.5 -0.5  1. ]
              [ 1.  -0.5  1. ]
              [-1.   0.   1. ]
              [-0.5  0.   1. ]
              [ 0.   0.   1. ]
              [ 0.5  0.   1. ]
              [ 1.   0.   1. ]
              [-1.   0.5  1. ]
              [-0.5  0.5  1. ]
              [ 0.   0.5  1. ]
              [ 0.5  0.5  1. ]
              [ 1.   0.5  1. ]
              [-1.   1.   1. ]
              [-0.5  1.   1. ]
              [ 0.   1.   1. ]
              [ 0.5  1.   1. ]
              [ 1.   1.   1. ]]
    Step3:
        Compute output by equation $$Output[i] = C_ * Theta[i]^T$$
    )DOC");
  }
};

class AffineGridOpGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
  void InferShape(framework::InferShapeContext* ctx) const override {
    if (ctx->HasOutput(framework::GradVarName("Theta"))) {
241
      auto output_dims = ctx->GetInputDim(framework::GradVarName("Output"));
242 243 244 245 246 247 248
      if (output_dims.size() == 4) {
        ctx->SetOutputDim(framework::GradVarName("Theta"),
                          {output_dims[0], 2, 3});
      } else {
        ctx->SetOutputDim(framework::GradVarName("Theta"),
                          {output_dims[0], 3, 4});
      }
W
whs 已提交
249 250 251 252 253 254 255
    }
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    framework::LibraryType library_{framework::LibraryType::kPlain};
256
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
W
whs 已提交
257 258 259 260
    if (platform::CanCUDNNBeUsed(ctx)) {
      library_ = framework::LibraryType::kCUDNN;
    }
#endif
261 262 263
    return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
                                       ctx, framework::GradVarName("Output")),
                                   ctx.GetPlace(),
264 265
                                   framework::DataLayout::kAnyLayout,
                                   library_);
W
whs 已提交
266 267 268
  }
};

H
hong 已提交
269 270
template <typename T>
class AffineGridGradMaker : public framework::SingleGradOpMaker<T> {
W
whs 已提交
271
 public:
H
hong 已提交
272
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
W
whs 已提交
273 274

 protected:
275
  void Apply(GradOpPtr<T> op) const override {
W
whs 已提交
276
    op->SetType("affine_grid_grad");
H
hong 已提交
277 278
    op->SetInput("OutputShape", this->Input("OutputShape"));
    op->SetInput(framework::GradVarName("Output"), this->OutputGrad("Output"));
W
whs 已提交
279

H
hong 已提交
280
    op->SetAttrMap(this->Attrs());
W
whs 已提交
281

H
hong 已提交
282
    op->SetOutput(framework::GradVarName("Theta"), this->InputGrad("Theta"));
W
whs 已提交
283 284 285 286 287 288 289
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
290 291 292
REGISTER_OPERATOR(affine_grid,
                  ops::AffineGridOp,
                  ops::AffineGridOpMaker,
H
hong 已提交
293 294
                  ops::AffineGridGradMaker<paddle::framework::OpDesc>,
                  ops::AffineGridGradMaker<paddle::imperative::OpBase>);
W
whs 已提交
295

296
REGISTER_OPERATOR(affine_grid_grad, ops::AffineGridOpGrad);
W
whs 已提交
297 298 299 300 301 302 303

REGISTER_OP_VERSION(affine_grid)
    .AddCheckpoint(
        R"ROC(
               Compatible upgrade of affine_grid, add a new attribute [align_corners])ROC",
        paddle::framework::compatible::OpVersionDesc().NewAttr(
            "align_corners",
304 305
            "Whether to align the corners of input and output.",
            true));