grid_sampler_op.cc 7.6 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 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

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"
#include "paddle/fluid/framework/op_registry.h"
#ifdef PADDLE_WITH_CUDA
#include "paddle/fluid/platform/cudnn_helper.h"
#endif

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;

class GridSampleOp : public framework::OperatorWithKernel {
  public:
    using framework::OperatorWithKernel::OperatorWithKernel;
    void InferShape(framework::InferShapeContext* ctx) const override {
      PADDLE_ENFORCE(ctx->HasInput("X"),
                    "Input(X) of GridSampleOp should not be null.");
      PADDLE_ENFORCE(ctx->HasInput("Grid"),
                    "Input(Grid) of GridSampleOp should not be null.");
      PADDLE_ENFORCE(ctx->HasOutput("Output"),
                    "Output(Output) of GridSampleOp should not be null.");
      
      auto x_dims = ctx->GetInputDim("X");
      auto grid_dims = ctx->GetInputDim("Grid");
      PADDLE_ENFORCE(x_dims.size() == 4, "Input(X) of GridSampleOp should be 4-D Tensor.");
      PADDLE_ENFORCE(grid_dims.size() == 4, "Input(Grid) of GridSampleOp should be 4-D Tensor.");
      PADDLE_ENFORCE(grid_dims[3] == 2, "Input(Grid) dims[3] should be 2.");
      PADDLE_ENFORCE_EQ(grid_dims[0], x_dims[0], "Input(X) and Input(Grid) dims[0] should be equal.");
      PADDLE_ENFORCE_EQ(grid_dims[1], x_dims[2], "Input(X) dims[2] and Input(Grid) dims[1] should be equal.");
      PADDLE_ENFORCE_EQ(grid_dims[2], x_dims[3], "Input(X) dims[3] and Input(Grid) dims[2] should be equal.");

      ctx->SetOutputDim("Output", x_dims);
      ctx->ShareLoD("X", "Output");
    }
  
  protected:
    framework::OpKernelType GetExpectedKernelType(
        const framework::ExecutionContext& ctx) const override {
      framework::LibraryType library_{framework::LibraryType::kPlain};
#ifdef PADDLE_WITH_CUDA
      if (platform::CanCUDNNBeUsed(ctx)) {
        library_ = framework::LibraryType::kCUDNN;
      }
#endif    
      return framework::OpKernelType(
          framework::ToDataType(ctx.Input<Tensor>("X")->type()),
          ctx.GetPlace(), framework::DataLayout::kAnyLayout, library_);
    }
};

class GridSampleOpMaker : public framework::OpProtoAndCheckerMaker {
  public:
    void Make() override {
      AddInput(
          "X",
70
          "(Tensor) The input data of GridSampleOp, "
D
dengkaipeng 已提交
71 72 73
          "This is a 4-D tensor with shape of [N, C, H, W]");
      AddInput(
          "Grid",
74 75 76
          "(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 "
          "of x and y coordinates with shape [N, H, W] in last dimention");
D
dengkaipeng 已提交
77 78 79 80 81
      AddOutput(
          "Output",
          "(Tensor) Output tensor with shape [N, C, H, W]");
      AddAttr<bool>(
          "use_cudnn",
82
          "(bool, default true) Only used in cudnn kernel, need install cudnn")
D
dengkaipeng 已提交
83 84 85
          .SetDefault(true);

      AddComment(R"DOC(
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
      It sample input X by grid gennerate by AffineGridOp. The grid of shape
      [N, H, W, 2] is the concatenation of (x, y) coordinates with shape 
      [N, H, W] each, with x indexing the 4th-D(W) of input feature map and y to 
      indexng the 3rd-D(H), finally results is the bilinear interpolation value
      of 4 nearest corner points.

      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");
D
dengkaipeng 已提交
130 131 132 133 134 135 136
    }
};

class GridSampleOpGrad : public framework::OperatorWithKernel {
  public:
  using framework::OperatorWithKernel::OperatorWithKernel;
  void InferShape(framework::InferShapeContext* ctx) const override {
137 138 139 140 141 142 143 144
    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 已提交
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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
  }

  protected:
    framework::OpKernelType GetExpectedKernelType(
        const framework::ExecutionContext& ctx) const override {
      framework::LibraryType library_{framework::LibraryType::kPlain};
#ifdef PADDLE_WITH_CUDA
      if (platform::CanCUDNNBeUsed(ctx)) {
        library_ = framework::LibraryType::kCUDNN;
      }
#endif    
      return framework::OpKernelType(
          framework::ToDataType(ctx.Input<Tensor>("X")->type()),
          ctx.GetPlace(), framework::DataLayout::kAnyLayout, library_);
    }
};

class GridSampleGradMaker : public framework::SingleGradOpDescMaker {
  public:
    using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;

  protected:
    std::unique_ptr<framework::OpDesc> Apply() const override {
      auto* op = new framework::OpDesc();
      op->SetType("grid_sampler_grad");
      op->SetInput("X", Input("X"));
      op->SetInput("Grid", Input("Grid"));
      op->SetInput(framework::GradVarName("Output"), OutputGrad("Output"));

      op->SetAttrMap(Attrs());

      op->SetOutput(framework::GradVarName("X"), InputGrad("X"));
      op->SetOutput(framework::GradVarName("Grid"), InputGrad("Grid"));
      return std::unique_ptr<framework::OpDesc>(op);
    }
};

} // namespace operators
} // namespace paddle

namespace ops = paddle::operators;
REGISTER_OPERATOR(grid_sampler, ops::GridSampleOp, ops::GridSampleOpMaker,
                  ops::GridSampleGradMaker);
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>);