grid_sampler_op.cc 9.5 KB
Newer Older
1
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dengkaipeng 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15

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/grid_sampler_op.h"
16
#include <memory>
17
#include <string>
D
dengkaipeng 已提交
18
#include "paddle/fluid/framework/op_registry.h"
19
#include "paddle/fluid/framework/op_version_registry.h"
D
dengkaipeng 已提交
20 21 22
#ifdef PADDLE_WITH_CUDA
#include "paddle/fluid/platform/cudnn_helper.h"
#endif
23 24 25
#ifdef PADDLE_WITH_HIP
#include "paddle/fluid/platform/miopen_helper.h"
#endif
D
dengkaipeng 已提交
26 27 28 29 30 31 32

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;

class GridSampleOp : public framework::OperatorWithKernel {
33 34 35
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
  void InferShape(framework::InferShapeContext* ctx) const override {
K
Kaipeng Deng 已提交
36 37 38
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "GridSampler");
    OP_INOUT_CHECK(ctx->HasInput("Grid"), "Input", "Grid", "GridSampler");
    OP_INOUT_CHECK(ctx->HasOutput("Output"), "Output", "Output", "GridSampler");
39 40 41

    auto x_dims = ctx->GetInputDim("X");
    auto grid_dims = ctx->GetInputDim("Grid");
42 43 44 45 46 47 48 49 50 51
    PADDLE_ENFORCE_EQ(x_dims.size(), 4,
                      platform::errors::InvalidArgument(
                          "Input(X) of GridSampleOp should be 4-D Tensor, but "
                          "received X dimension size(%d)",
                          x_dims.size()));
    PADDLE_ENFORCE_EQ(grid_dims.size(), 4,
                      platform::errors::InvalidArgument(
                          "Input(Grid) of GridSampleOp should be 4-D Tensor, "
                          "but received X dimension size(%d)",
                          grid_dims.size()));
52
    if (ctx->IsRuntime() || grid_dims[3] > 0) {
53 54 55 56 57
      PADDLE_ENFORCE_EQ(
          grid_dims[3], 2,
          platform::errors::InvalidArgument(
              "Input(Grid) dimension[3] should be 2, but received %d",
              grid_dims[3]));
58
    }
59
    if (ctx->IsRuntime()) {
60 61 62 63 64 65
      PADDLE_ENFORCE_EQ(
          grid_dims[0], x_dims[0],
          platform::errors::InvalidArgument(
              "Input(X) and Input(Grid) dimension[0] should be equal, but "
              "received X dimension[0](%d) != Grid dimension[0](%d)",
              x_dims[0], grid_dims[0]));
66
    }
67

68 69
    ctx->SetOutputDim("Output",
                      {x_dims[0], x_dims[1], grid_dims[1], grid_dims[2]});
70 71 72 73 74 75 76
    ctx->ShareLoD("X", "Output");
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    framework::LibraryType library_{framework::LibraryType::kPlain};
77
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
78 79
    if (platform::CanCUDNNBeUsed(ctx)) {
      library_ = framework::LibraryType::kCUDNN;
D
dengkaipeng 已提交
80
    }
81
#endif
82 83 84
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.GetPlace(),
        framework::DataLayout::kAnyLayout, library_);
85
  }
D
dengkaipeng 已提交
86 87 88
};

class GridSampleOpMaker : public framework::OpProtoAndCheckerMaker {
89 90 91 92 93 94 95 96 97
 public:
  void Make() override {
    AddInput("X",
             "(Tensor) The input data of GridSampleOp, "
             "This is a 4-D tensor with shape of [N, C, H, W]");
    AddInput(
        "Grid",
        "(Tensor) The input grid of GridSampleOp generated by AffineGridOp, "
        "This is a 4-D tensor with shape of [N, H, W, 2] is the concatenation "
T
tianshuo78520a 已提交
98
        "of x and y coordinates with shape [N, H, W] in last dimension");
99 100 101 102 103 104
    AddOutput("Output", "(Tensor) Output tensor with shape [N, C, H, W]");
    AddAttr<bool>(
        "use_cudnn",
        "(bool, default true) Only used in cudnn kernel, need install cudnn")
        .SetDefault(true);

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
    AddAttr<bool>(
        "align_corners",
        "(bool, default true) If align_corners is true, it will project"
        "-1 and 1 to the centers of the corner pixels. Otherwise, it will "
        "project"
        "-1 and 1 to the image edges.")
        .SetDefault(true);

    AddAttr<std::string>(
        "mode",
        "(bool, default true) The interpolation method which can be 'bilinear'"
        " or 'nearest'.")
        .SetDefault("bilinear");

    AddAttr<std::string>(
        "padding_mode",
        "(bool, default true) The padding method used when source"
122
        "index is out of input images. It can be 'zeros', 'reflection' and "
123 124 125
        "'border'.")
        .SetDefault("zeros");

126
    AddComment(R"DOC(
127
      This operation samples input X by using bilinear or nearest interpolation based on 
T
tianshuo78520a 已提交
128
      flow field grid, which is usually generated by affine_grid. The grid of
129 130
      shape [N, H, W, 2] is the concatenation of (grid_x, grid_y) coordinates 
      with shape [N, H, W] each, where grid_x is indexing the 4th dimension 
T
tianshuo78520a 已提交
131 132
      (in width dimension) of input data x and grid_y is indexing the 3rd 
      dimension (in height dimension), finally results is the bilinear 
133
      interpolation value or nearest value of 4 nearest corner points.
134

135
      For bilinear interpolation mode:
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
      Step 1:
        Get (x, y) grid coordinates and scale to [0, H-1/W-1].

        grid_x = 0.5 * (grid[:, :, :, 0] + 1) * (W - 1)
        grid_y = 0.5 * (grid[:, :, :, 1] + 1) * (H - 1)

      Step 2:
        Indices input data X with grid (x, y) in each [H, W] area, and bilinear 
        interpolate point value by 4 nearest points.

          wn ------- y_n ------- en
          |           |           |
          |          d_n          |
          |           |           |
         x_w --d_w-- grid--d_e-- x_e
          |           |           |
          |          d_s          |
          |           |           |
          ws ------- y_s ------- wn

        x_w = floor(x)              // west side x coord
        x_e = x_w + 1               // east side x coord
        y_n = floor(y)              // north side y coord
        y_s = y_s + 1               // south side y coord

        d_w = grid_x - x_w          // distance to west side
        d_e = x_e - grid_x          // distance to east side
        d_n = grid_y - y_n          // distance to north side
        d_s = y_s - grid_y          // distance to south side

        wn = X[:, :, y_n, x_w]      // north-west point value
        en = X[:, :, y_n, x_e]      // north-east point value
        ws = X[:, :, y_s, x_w]      // south-east point value
        es = X[:, :, y_s, x_w]      // north-east point value

        output = wn * d_e * d_s + en * d_w * d_s
               + ws * d_e * d_n + es * d_w * d_n
        )DOC");
174
  }
D
dengkaipeng 已提交
175 176 177
};

class GridSampleOpGrad : public framework::OperatorWithKernel {
178
 public:
D
dengkaipeng 已提交
179 180
  using framework::OperatorWithKernel::OperatorWithKernel;
  void InferShape(framework::InferShapeContext* ctx) const override {
181 182
    OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("X")), "Output",
                   framework::GradVarName("X"), "grid_sampler");
183 184 185 186 187 188 189 190
    auto input_dims = ctx->GetInputDim("X");
    auto grid_dims = ctx->GetInputDim("Grid");
    if (ctx->HasOutput(framework::GradVarName("X"))) {
      ctx->SetOutputDim(framework::GradVarName("X"), input_dims);
    }
    if (ctx->HasOutput(framework::GradVarName("Grid"))) {
      ctx->SetOutputDim(framework::GradVarName("Grid"), grid_dims);
    }
D
dengkaipeng 已提交
191 192
  }

193 194 195 196
 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    framework::LibraryType library_{framework::LibraryType::kPlain};
197
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
198 199
    if (platform::CanCUDNNBeUsed(ctx)) {
      library_ = framework::LibraryType::kCUDNN;
D
dengkaipeng 已提交
200
    }
201
#endif
202 203 204
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.GetPlace(),
        framework::DataLayout::kAnyLayout, library_);
205
  }
D
dengkaipeng 已提交
206 207
};

H
hong 已提交
208 209
template <typename T>
class GridSampleGradMaker : public framework::SingleGradOpMaker<T> {
210
 public:
H
hong 已提交
211
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
212 213

 protected:
214
  void Apply(GradOpPtr<T> op) const override {
215
    op->SetType("grid_sampler_grad");
H
hong 已提交
216 217 218
    op->SetInput("X", this->Input("X"));
    op->SetInput("Grid", this->Input("Grid"));
    op->SetInput(framework::GradVarName("Output"), this->OutputGrad("Output"));
219

H
hong 已提交
220
    op->SetAttrMap(this->Attrs());
221

H
hong 已提交
222 223
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetOutput(framework::GradVarName("Grid"), this->InputGrad("Grid"));
224
  }
D
dengkaipeng 已提交
225 226
};

227 228
}  // namespace operators
}  // namespace paddle
D
dengkaipeng 已提交
229 230 231

namespace ops = paddle::operators;
REGISTER_OPERATOR(grid_sampler, ops::GridSampleOp, ops::GridSampleOpMaker,
H
hong 已提交
232 233
                  ops::GridSampleGradMaker<paddle::framework::OpDesc>,
                  ops::GridSampleGradMaker<paddle::imperative::OpBase>);
D
dengkaipeng 已提交
234 235 236 237 238 239 240 241 242 243
REGISTER_OPERATOR(grid_sampler_grad, ops::GridSampleOpGrad);

REGISTER_OP_CPU_KERNEL(
    grid_sampler,
    ops::GridSampleOpKernel<paddle::platform::CPUDeviceContext, float>,
    ops::GridSampleOpKernel<paddle::platform::CPUDeviceContext, double>);
REGISTER_OP_CPU_KERNEL(
    grid_sampler_grad,
    ops::GridSampleGradOpKernel<paddle::platform::CPUDeviceContext, float>,
    ops::GridSampleGradOpKernel<paddle::platform::CPUDeviceContext, double>);
244 245 246 247 248 249 250 251

REGISTER_OP_VERSION(grid_sampler)
    .AddCheckpoint(
        R"ROC(
      Upgrade grid_sampler add a new attribute [mode].
    )ROC",
        paddle::framework::compatible::OpVersionDesc().NewAttr(
            "mode", "In order to specify interpolation mode", "bilinear"));