grid_sampler_op.cc 7.8 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

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>
16
#include <string>
17

18
#include "paddle/fluid/framework/infershape_utils.h"
D
dengkaipeng 已提交
19
#include "paddle/fluid/framework/op_registry.h"
20
#include "paddle/fluid/framework/op_version_registry.h"
21
#include "paddle/fluid/platform/device/gpu/gpu_dnn.h"
22 23 24
#include "paddle/phi/core/infermeta_utils.h"
#include "paddle/phi/infermeta/backward.h"
#include "paddle/phi/infermeta/binary.h"
D
dengkaipeng 已提交
25 26 27 28 29 30 31

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;

class GridSampleOp : public framework::OperatorWithKernel {
32 33 34 35 36 37 38
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    framework::LibraryType library_{framework::LibraryType::kPlain};
39
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
40 41
    if (platform::CanCUDNNBeUsed(ctx)) {
      library_ = framework::LibraryType::kCUDNN;
D
dengkaipeng 已提交
42
    }
43
#endif
44
    return framework::OpKernelType(
45 46 47 48
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        ctx.GetPlace(),
        framework::DataLayout::kAnyLayout,
        library_);
49
  }
D
dengkaipeng 已提交
50 51 52
};

class GridSampleOpMaker : public framework::OpProtoAndCheckerMaker {
53 54 55 56
 public:
  void Make() override {
    AddInput("X",
             "(Tensor) The input data of GridSampleOp, "
57 58
             "This is a 4-D tensor with shape of [N, C, H, W] or"
             "        a 5-D tensot with shape of [N, C, D, H, W]");
59 60 61 62
    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 "
63 64 65 66 67 68 69
        "of x and y coordinates with shape [N, H, W] in last dimension or "
        "a 5-D tensor with shape of [N, D, H, W, 3] is the concatenation "
        "of depth, x and y coordinates with shape [N, D, H, W] in last "
        "dimension ");
    AddOutput("Output",
              "(Tensor) Output tensor with shape [N, C, H, W] or shape [N,C, "
              "D, H ,W]");
70 71 72
    AddAttr<bool>(
        "use_cudnn",
        "(bool, default true) Only used in cudnn kernel, need install cudnn")
73 74
        .SetDefault(true)
        .AsExtra();
75

76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
    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"
93
        "index is out of input images. It can be 'zeros', 'reflection' and "
94 95 96
        "'border'.")
        .SetDefault("zeros");

97
    AddComment(R"DOC(
98
      This operation samples input X by using bilinear or nearest interpolation based on 
T
tianshuo78520a 已提交
99
      flow field grid, which is usually generated by affine_grid. The grid of
100 101
      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 已提交
102 103
      (in width dimension) of input data x and grid_y is indexing the 3rd 
      dimension (in height dimension), finally results is the bilinear 
104
      interpolation value or nearest value of 4 nearest corner points.
105

106
      For bilinear interpolation mode:
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 139 140 141 142 143 144
      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");
145
  }
D
dengkaipeng 已提交
146 147 148
};

class GridSampleOpGrad : public framework::OperatorWithKernel {
149
 public:
D
dengkaipeng 已提交
150 151
  using framework::OperatorWithKernel::OperatorWithKernel;

152 153 154 155
 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    framework::LibraryType library_{framework::LibraryType::kPlain};
156
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
157 158
    if (platform::CanCUDNNBeUsed(ctx)) {
      library_ = framework::LibraryType::kCUDNN;
D
dengkaipeng 已提交
159
    }
160
#endif
161
    return framework::OpKernelType(
162 163 164 165
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        ctx.GetPlace(),
        framework::DataLayout::kAnyLayout,
        library_);
166
  }
D
dengkaipeng 已提交
167 168
};

H
hong 已提交
169 170
template <typename T>
class GridSampleGradMaker : public framework::SingleGradOpMaker<T> {
171
 public:
H
hong 已提交
172
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
173 174

 protected:
175
  void Apply(GradOpPtr<T> op) const override {
176
    op->SetType("grid_sampler_grad");
H
hong 已提交
177 178 179
    op->SetInput("X", this->Input("X"));
    op->SetInput("Grid", this->Input("Grid"));
    op->SetInput(framework::GradVarName("Output"), this->OutputGrad("Output"));
180

H
hong 已提交
181
    op->SetAttrMap(this->Attrs());
182

H
hong 已提交
183 184
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetOutput(framework::GradVarName("Grid"), this->InputGrad("Grid"));
185
  }
D
dengkaipeng 已提交
186 187
};

188 189
}  // namespace operators
}  // namespace paddle
D
dengkaipeng 已提交
190 191

namespace ops = paddle::operators;
192 193
DECLARE_INFER_SHAPE_FUNCTOR(grid_sampler,
                            GridSamplerInferShapeFunctor,
194
                            PD_INFER_META(phi::GridSampleBaseInferMeta));
195 196 197
REGISTER_OPERATOR(grid_sampler,
                  ops::GridSampleOp,
                  ops::GridSampleOpMaker,
H
hong 已提交
198
                  ops::GridSampleGradMaker<paddle::framework::OpDesc>,
199 200
                  ops::GridSampleGradMaker<paddle::imperative::OpBase>,
                  GridSamplerInferShapeFunctor);
201 202
DECLARE_INFER_SHAPE_FUNCTOR(grid_sampler_grad,
                            GridSamplerGradInferShapeFunctor,
203
                            PD_INFER_META(phi::GeneralBinaryGradInferMeta));
204 205
REGISTER_OPERATOR(grid_sampler_grad,
                  ops::GridSampleOpGrad,
206
                  GridSamplerGradInferShapeFunctor);
D
dengkaipeng 已提交
207

208 209 210 211 212 213 214
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"));