bilateral_slice_op.cc 7.7 KB
Newer Older
L
LielinJiang 已提交
1 2 3 4 5 6 7 8 9 10 11 12
/* Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
   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/bilateral_slice_op.h"
13

L
LielinJiang 已提交
14 15 16
#include <memory>
#include <string>
#include <vector>
17

L
LielinJiang 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#include "paddle/fluid/framework/op_registry.h"

namespace paddle {
namespace operators {

using DataLayout = framework::DataLayout;

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

 protected:
  void InferShape(framework::InferShapeContext* ctx) const override {
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "BilateralSlice");
    OP_INOUT_CHECK(ctx->HasInput("Grid"), "Input", "Grid", "BilateralSlice");
    OP_INOUT_CHECK(ctx->HasInput("Guide"), "Input", "Guide", "BilateralSlice");
    OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Output", "BilateralSlice");

    auto dim_x = ctx->GetInputDim("X");  // NCHW format
    PADDLE_ENFORCE_EQ(
38 39
        dim_x.size(),
        4,
L
LielinJiang 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
        platform::errors::Unimplemented(
            "Input(X) dimension must be 4, but got dimension = %d .",
            dim_x.size()));

    auto input_dims = ctx->GetInputDim("X");
    auto grid_dims = ctx->GetInputDim("Grid");
    auto guide_dims = ctx->GetInputDim("Guide");
    bool has_offset = ctx->Attrs().Get<bool>("has_offset");
    int64_t h = guide_dims[1];
    int64_t w = guide_dims[2];
    int64_t bs = grid_dims[0];
    int64_t coeffs_chans = grid_dims[1];
    int64_t input_chans = input_dims[1];

    int64_t output_chans;
55 56
    if ((!ctx->IsRuntime()) && ((coeffs_chans < 0) || (input_chans < 0))) {
      output_chans = -1;
L
LielinJiang 已提交
57
    } else {
58
      if (has_offset) {
59 60
        PADDLE_ENFORCE_EQ((coeffs_chans % (input_chans + 1)),
                          0,
61 62 63 64 65 66 67
                          platform::errors::InvalidArgument(
                              "Slicing with affine offset, coefficients grid "
                              "should have n_out*(n_in+1) channels, but got %d",
                              coeffs_chans));
        output_chans = coeffs_chans / (input_chans + 1);
      } else {
        PADDLE_ENFORCE_EQ(
68 69
            (coeffs_chans % input_chans),
            0,
70 71 72 73 74 75
            platform::errors::InvalidArgument(
                "Slicing without affine offset, coefficients grid "
                "should have n_out*n_in channels, but got %d .",
                coeffs_chans));
        output_chans = coeffs_chans / input_chans;
      }
L
LielinJiang 已提交
76 77 78 79 80 81 82 83
    }

    std::vector<int64_t> output_dims;
    output_dims.push_back(bs);
    output_dims.push_back(output_chans);
    output_dims.push_back(h);
    output_dims.push_back(w);

84
    ctx->SetOutputDim("Out", phi::make_ddim(output_dims));
L
LielinJiang 已提交
85 86 87 88 89 90 91 92 93 94
  }

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

  framework::OpKernelType GetKernelTypeForVar(
95
      const std::string& var_name,
96
      const phi::DenseTensor& tensor,
L
LielinJiang 已提交
97
      const framework::OpKernelType& expected_kernel_type) const override {
98 99
    return framework::OpKernelType(
        expected_kernel_type.data_type_, tensor.place(), tensor.layout());
L
LielinJiang 已提交
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 130 131 132 133 134
  }
};

class BilateralSliceOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X",
             "The input tensor of bilateral_slice operator, "
             "This is a 4-D tensor with shape of [N, C, H, W]");
    AddInput("Grid",
             "This is a 5-D tensor. "
             "It should be [N, C, D, H, W].");
    AddInput("Guide",
             "This is a 3-D tensor "
             "It should be [N, H, W].");
    AddOutput("Out",
              "The output tensor of bilateral slice operator, "
              "This is a tensor in same rank with Input(X).");
    AddAttr<bool>("has_offset", "an optional bool. Defaults to False. ")
        .SetDefault(false);
    AddComment(R"DOC(
          This operator enhance input X according guide and grid
          For details of bilateral slice, please refer to paper:
          https://groups.csail.mit.edu/graphics/hdrnet/
         )DOC");
  }
};

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

 protected:
  void InferShape(framework::InferShapeContext* ctx) const override {
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "BilateralSliceOpGrad");
135 136 137 138 139 140 141
    OP_INOUT_CHECK(
        ctx->HasInput("Grid"), "Input", "Grid", "BilateralSliceOpGrad");
    OP_INOUT_CHECK(
        ctx->HasInput("Guide"), "Input", "Guide", "BilateralSliceOpGrad");
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")),
                   "Input",
                   "Out",
L
LielinJiang 已提交
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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
                   "BilateralSliceOpGrad");

    auto dim_x = ctx->GetInputDim("X");
    auto dim_grid = ctx->GetInputDim("Grid");
    auto dim_guide = ctx->GetInputDim("Guide");
    if (ctx->HasOutput(framework::GradVarName("X"))) {
      ctx->SetOutputDim(framework::GradVarName("X"), dim_x);
    }
    if (ctx->HasOutput(framework::GradVarName("Grid"))) {
      ctx->SetOutputDim(framework::GradVarName("Grid"), dim_grid);
    }
    if (ctx->HasOutput(framework::GradVarName("Guide"))) {
      ctx->SetOutputDim(framework::GradVarName("Guide"), dim_guide);
    }
  }

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

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

 protected:
  void Apply(GradOpPtr<T> op) const override {
    op->SetType(this->ForwardOpType() + "_grad");
    op->SetInput("X", this->Input("X"));
    op->SetInput("Grid", this->Input("Grid"));
    op->SetInput("Guide", this->Input("Guide"));

    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetOutput(framework::GradVarName("Grid"), this->InputGrad("Grid"));
    op->SetOutput(framework::GradVarName("Guide"), this->InputGrad("Guide"));
    op->SetAttrMap(this->Attrs());
  }
};

template <typename T>
class BilateralSliceKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
190 191
    PADDLE_ENFORCE_EQ(platform::is_gpu_place(ctx.GetPlace()),
                      true,
L
LielinJiang 已提交
192 193 194 195 196 197 198 199 200
                      platform::errors::Unimplemented(
                          "BilateralSlice only supports GPU now."));
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
201 202
REGISTER_OPERATOR(bilateral_slice,
                  ops::BilateralSliceOp,
L
LielinJiang 已提交
203 204 205 206
                  ops::BilateralSliceOpMaker,
                  ops::BilateralSliceGradMaker<paddle::framework::OpDesc>,
                  ops::BilateralSliceGradMaker<paddle::imperative::OpBase>);
REGISTER_OPERATOR(bilateral_slice_grad, ops::BilateralSliceOpGrad);
207 208
REGISTER_OP_CPU_KERNEL(bilateral_slice,
                       ops::BilateralSliceKernel<float>,
L
LielinJiang 已提交
209
                       ops::BilateralSliceKernel<double>);