instance_norm_op.cc 9.4 KB
Newer Older
L
lvmengsi 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2019 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. */

#include "paddle/fluid/operators/instance_norm_op.h"
16

L
lvmengsi 已提交
17 18 19
#include <memory>
#include <string>
#include <unordered_map>
20

L
lvmengsi 已提交
21
#include "paddle/fluid/framework/data_layout.h"
22
#include "paddle/fluid/framework/infershape_utils.h"
23
#include "paddle/fluid/framework/op_version_registry.h"
24 25 26
#include "paddle/fluid/prim/api/composite_backward/composite_backward_api.h"
#include "paddle/fluid/prim/utils/static/composite_grad_desc_maker.h"
#include "paddle/fluid/prim/utils/static/desc_tensor.h"
27 28 29
#include "paddle/phi/core/infermeta_utils.h"
#include "paddle/phi/infermeta/backward.h"
#include "paddle/phi/infermeta/ternary.h"
30
#include "paddle/phi/kernels/funcs/math_function.h"
L
lvmengsi 已提交
31 32 33 34

namespace paddle {
namespace operators {

35
phi::KernelKey InstanceNormOp::GetExpectedKernelType(
L
lvmengsi 已提交
36
    const framework::ExecutionContext &ctx) const {
37
  auto input_data_type = OperatorWithKernel::IndicateVarDataType(ctx, "X");
L
lvmengsi 已提交
38 39 40 41 42 43 44
  // By default, the type of the scale, bias, mean,
  // and var tensors should both be float. (For float or float16 input tensor)
  // or double (For double input tensor).
  auto in_param_type = framework::proto::VarType::FP32;
  if (input_data_type == framework::proto::VarType::FP64) {
    in_param_type = framework::proto::VarType::FP64;
  }
C
ceci3 已提交
45
  if (ctx.HasInput("Scale")) {
46 47 48 49 50
    PADDLE_ENFORCE_EQ(in_param_type,
                      framework::TransToProtoVarType(
                          ctx.Input<phi::DenseTensor>("Scale")->dtype()),
                      platform::errors::InvalidArgument(
                          "Scale input should be of float type"));
C
ceci3 已提交
51 52
  }
  if (ctx.HasInput("Bias")) {
53 54 55 56 57
    PADDLE_ENFORCE_EQ(in_param_type,
                      framework::TransToProtoVarType(
                          ctx.Input<phi::DenseTensor>("Bias")->dtype()),
                      platform::errors::InvalidArgument(
                          "Bias input should be of float type"));
C
ceci3 已提交
58
  }
L
lvmengsi 已提交
59

60
  return phi::KernelKey(input_data_type, ctx.GetPlace());
L
lvmengsi 已提交
61 62 63 64 65 66
}

void InstanceNormOpMaker::Make() {
  AddAttr<float>("epsilon", "")
      .SetDefault(1e-5)
      .AddCustomChecker([](const float &epsilon) {
67 68
        PADDLE_ENFORCE_EQ(epsilon >= 0.0f && epsilon <= 0.001f,
                          true,
69 70
                          platform::errors::InvalidArgument(
                              "'epsilon' should be between 0.0 and 0.001."));
L
lvmengsi 已提交
71 72 73 74
      });
  AddInput("X", "The input tensor");
  AddInput("Scale",
           "Scale is a 1-dimensional tensor of size C "
C
ceci3 已提交
75 76
           "that is applied to the output")
      .AsDispensable();
L
lvmengsi 已提交
77 78
  AddInput("Bias",
           "Bias is a 1-dimensional tensor of size C "
C
ceci3 已提交
79 80
           "that is applied to the output")
      .AsDispensable();
L
lvmengsi 已提交
81 82 83 84
  AddOutput("Y", "result after normalization");
  AddOutput("SavedMean",
            "Mean of the current mini batch, "
            "will apply to output when training")
C
ceci3 已提交
85 86
      .AsIntermediate()
      .AsExtra();
L
lvmengsi 已提交
87 88 89
  AddOutput("SavedVariance",
            "Variance of the current mini batch, "
            "will apply to output when training")
C
ceci3 已提交
90 91
      .AsIntermediate()
      .AsExtra();
L
lvmengsi 已提交
92 93 94 95 96 97 98 99 100 101 102 103
  AddComment(R"DOC(
Instance Normalization.

Instance Norm has been implemented as disscussed in the paper:
https://arxiv.org/pdf/1607.08022.pdf
Can be used as a normalizer function for conv2d and fully_connected operations.
The required data format for this layer is as following:
NCHW `[batch, in_channels, in_height, in_width]`

)DOC");
}

104
phi::KernelKey InstanceNormGradOp::GetExpectedKernelType(
L
lvmengsi 已提交
105 106 107
    const framework::ExecutionContext &ctx) const {
  const auto *var = ctx.InputVar(framework::GradVarName("Y"));
  if (var == nullptr) {
C
ceci3 已提交
108 109
    PADDLE_THROW(
        platform::errors::NotFound("cannot find gradient variable of Y"));
L
lvmengsi 已提交
110
  }
111 112 113
  const phi::DenseTensor *t = nullptr;
  if (var->IsType<phi::DenseTensor>()) {
    t = &var->Get<phi::DenseTensor>();
114 115
  } else if (var->IsType<phi::DenseTensor>()) {
    t = &var->Get<phi::DenseTensor>();
L
lvmengsi 已提交
116 117
  }
  if (t == nullptr) {
C
ceci3 已提交
118 119
    PADDLE_THROW(
        platform::errors::InvalidArgument("gradient variable of Y is empty"));
L
lvmengsi 已提交
120
  }
121 122
  return phi::KernelKey(OperatorWithKernel::IndicateVarDataType(ctx, "X"),
                        ctx.GetPlace());
L
lvmengsi 已提交
123 124
}

125
phi::KernelKey InstanceNormDoubleGradOp::GetExpectedKernelType(
L
lvmengsi 已提交
126 127 128
    const framework::ExecutionContext &ctx) const {
  const auto *var = ctx.InputVar("DY");
  if (var == nullptr) {
C
ceci3 已提交
129 130
    PADDLE_THROW(
        platform::errors::NotFound("cannot find gradient variable of Y"));
L
lvmengsi 已提交
131
  }
132 133 134
  const phi::DenseTensor *t = nullptr;
  if (var->IsType<phi::DenseTensor>()) {
    t = &var->Get<phi::DenseTensor>();
135 136
  } else if (var->IsType<phi::DenseTensor>()) {
    t = &var->Get<phi::DenseTensor>();
L
lvmengsi 已提交
137 138
  }
  if (t == nullptr) {
C
ceci3 已提交
139 140
    PADDLE_THROW(
        platform::errors::InvalidArgument("gradient variable of Y is empty"));
L
lvmengsi 已提交
141
  }
142 143
  return phi::KernelKey(OperatorWithKernel::IndicateVarDataType(ctx, "X"),
                        ctx.GetPlace());
L
lvmengsi 已提交
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
class InstanceNormCompositeGradOpMaker : public prim::CompositeGradOpMakerBase {
  using prim::CompositeGradOpMakerBase::CompositeGradOpMakerBase;

 public:
  void Apply() override {
    // inputs and outputs of batch_norm
    paddle::Tensor x = this->GetSingleForwardInput("X");
    paddle::Tensor scale = this->GetSingleForwardInput("Scale");
    paddle::Tensor saved_mean = this->GetSingleForwardOutput("SavedMean");
    paddle::Tensor saved_variance =
        this->GetSingleForwardOutput("SavedVariance");

    paddle::Tensor y_grad = this->GetSingleOutputGrad("Y");
    paddle::Tensor x_grad = this->GetSingleInputGrad("X");
    paddle::Tensor scale_grad = this->GetSingleInputGrad("Scale");
    paddle::Tensor bias_grad = this->GetSingleInputGrad("Bias");

    auto x_grad_ptr = this->GetOutputPtr(&x_grad);
    std::string x_grad_name = this->GetOutputName(x_grad);
    auto scale_grad_ptr = this->GetOutputPtr(&scale_grad);
    std::string scale_grad_name = this->GetOutputName(scale_grad);
    auto bias_grad_ptr = this->GetOutputPtr(&bias_grad);
    std::string bias_grad_name = this->GetOutputName(bias_grad);

    auto epsilon = this->Attr<float>("epsilon");

    VLOG(3) << "Runing instance_norm composite func";
    prim::instance_norm_grad<prim::DescTensor>(x,
                                               scale,
                                               saved_mean,
                                               saved_variance,
                                               y_grad,
                                               epsilon,
                                               x_grad_ptr,
                                               scale_grad_ptr,
                                               bias_grad_ptr);
    this->RecoverOutputName(x_grad, x_grad_name);
    this->RecoverOutputName(scale_grad, scale_grad_name);
    this->RecoverOutputName(bias_grad, bias_grad_name);
  }
};

188
DECLARE_INPLACE_OP_INFERER(InstanceNormDoubleGradOpInplaceInferer,
L
lvmengsi 已提交
189 190 191 192 193 194
                           {"DY", "DDY"});

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
195 196
DECLARE_INFER_SHAPE_FUNCTOR(instance_norm,
                            InstanceNormInferShapeFunctor,
197 198 199 200 201
                            PD_INFER_META(phi::InstanceNormInferMeta));
DECLARE_INFER_SHAPE_FUNCTOR(instance_norm_grad,
                            InstanceNormGradInferShapeFunctor,
                            PD_INFER_META(phi::InstanceNormGradInferMeta));
DECLARE_INFER_SHAPE_FUNCTOR(
202 203
    instance_norm_grad_grad,
    InstanceNormDoubleGradInferShapeFunctor,
204
    PD_INFER_META(phi::InstanceNormDoubleGradInferMeta));
205 206 207
REGISTER_OPERATOR(instance_norm,
                  ops::InstanceNormOp,
                  ops::InstanceNormOpMaker,
H
hong 已提交
208 209
                  ops::InstanceNormOpInferVarType,
                  ops::InstanceNormGradMaker<paddle::framework::OpDesc>,
210
                  ops::InstanceNormGradMaker<paddle::imperative::OpBase>,
211 212
                  InstanceNormInferShapeFunctor,
                  ops::InstanceNormCompositeGradOpMaker);
213 214
REGISTER_OPERATOR(instance_norm_grad,
                  ops::InstanceNormGradOp,
H
hong 已提交
215
                  ops::InstanceNormDoubleGradMaker<paddle::framework::OpDesc>,
216 217
                  ops::InstanceNormDoubleGradMaker<paddle::imperative::OpBase>,
                  InstanceNormGradInferShapeFunctor);
218 219
REGISTER_OPERATOR(instance_norm_grad_grad,
                  ops::InstanceNormDoubleGradOp,
220 221
                  ops::InstanceNormDoubleGradOpInplaceInferer,
                  InstanceNormDoubleGradInferShapeFunctor);
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238

REGISTER_OP_VERSION(instance_norm)
    .AddCheckpoint(
        R"ROC(
      Change dispensable of attribute from False to True in instance_norm.
    )ROC",
        paddle::framework::compatible::OpVersionDesc()
            .ModifyAttr(
                "Bias",
                "The arg 'dispensable' of Input 'Bias' is changed: from "
                "'False' to 'True'.",
                true)
            .ModifyAttr(
                "Scale",
                "The arg 'dispensable' of Input 'Scale' is changed: from "
                "'False' to 'True'.",
                true));