instance_norm_op.cc 7.0 KB
Newer Older
L
lvmengsi 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/* 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"
#include <memory>
#include <string>
#include <unordered_map>
#include "paddle/fluid/framework/data_layout.h"
20
#include "paddle/fluid/framework/infershape_utils.h"
21
#include "paddle/fluid/framework/op_version_registry.h"
22 23 24
#include "paddle/phi/core/infermeta_utils.h"
#include "paddle/phi/infermeta/backward.h"
#include "paddle/phi/infermeta/ternary.h"
25
#include "paddle/phi/kernels/funcs/math_function.h"
L
lvmengsi 已提交
26 27 28 29 30 31

namespace paddle {
namespace operators {

framework::OpKernelType InstanceNormOp::GetExpectedKernelType(
    const framework::ExecutionContext &ctx) const {
32
  auto input_data_type = OperatorWithKernel::IndicateVarDataType(ctx, "X");
L
lvmengsi 已提交
33 34 35 36 37 38 39
  // 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 已提交
40
  if (ctx.HasInput("Scale")) {
41 42
    PADDLE_ENFORCE_EQ(in_param_type, framework::TransToProtoVarType(
                                         ctx.Input<Tensor>("Scale")->dtype()),
C
ceci3 已提交
43 44 45 46
                      platform::errors::InvalidArgument(
                          "Scale input should be of float type"));
  }
  if (ctx.HasInput("Bias")) {
47 48
    PADDLE_ENFORCE_EQ(in_param_type, framework::TransToProtoVarType(
                                         ctx.Input<Tensor>("Bias")->dtype()),
C
ceci3 已提交
49 50 51
                      platform::errors::InvalidArgument(
                          "Bias input should be of float type"));
  }
L
lvmengsi 已提交
52 53 54 55 56 57 58 59 60

  return framework::OpKernelType(input_data_type, ctx.GetPlace());
}

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

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

framework::OpKernelType InstanceNormDoubleGradOp::GetExpectedKernelType(
    const framework::ExecutionContext &ctx) const {
  const auto *var = ctx.InputVar("DY");
  if (var == nullptr) {
C
ceci3 已提交
121 122
    PADDLE_THROW(
        platform::errors::NotFound("cannot find gradient variable of Y"));
L
lvmengsi 已提交
123 124 125 126 127 128 129 130
  }
  const Tensor *t = nullptr;
  if (var->IsType<Tensor>()) {
    t = &var->Get<Tensor>();
  } else if (var->IsType<LoDTensor>()) {
    t = &var->Get<LoDTensor>();
  }
  if (t == nullptr) {
C
ceci3 已提交
131 132
    PADDLE_THROW(
        platform::errors::InvalidArgument("gradient variable of Y is empty"));
L
lvmengsi 已提交
133
  }
134 135
  return framework::OpKernelType(
      OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.GetPlace());
L
lvmengsi 已提交
136 137
}

138
DECLARE_INPLACE_OP_INFERER(InstanceNormDoubleGradOpInplaceInferer,
L
lvmengsi 已提交
139 140 141 142 143 144
                           {"DY", "DDY"});

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
145 146 147 148 149 150 151 152
DECLARE_INFER_SHAPE_FUNCTOR(instance_norm, InstanceNormInferShapeFunctor,
                            PD_INFER_META(phi::InstanceNormInferMeta));
DECLARE_INFER_SHAPE_FUNCTOR(instance_norm_grad,
                            InstanceNormGradInferShapeFunctor,
                            PD_INFER_META(phi::InstanceNormGradInferMeta));
DECLARE_INFER_SHAPE_FUNCTOR(
    instance_norm_grad_grad, InstanceNormDoubleGradInferShapeFunctor,
    PD_INFER_META(phi::InstanceNormDoubleGradInferMeta));
L
lvmengsi 已提交
153
REGISTER_OPERATOR(instance_norm, ops::InstanceNormOp, ops::InstanceNormOpMaker,
H
hong 已提交
154 155
                  ops::InstanceNormOpInferVarType,
                  ops::InstanceNormGradMaker<paddle::framework::OpDesc>,
156 157
                  ops::InstanceNormGradMaker<paddle::imperative::OpBase>,
                  InstanceNormInferShapeFunctor);
L
lvmengsi 已提交
158
REGISTER_OPERATOR(instance_norm_grad, ops::InstanceNormGradOp,
H
hong 已提交
159
                  ops::InstanceNormDoubleGradMaker<paddle::framework::OpDesc>,
160 161
                  ops::InstanceNormDoubleGradMaker<paddle::imperative::OpBase>,
                  InstanceNormGradInferShapeFunctor);
L
lvmengsi 已提交
162
REGISTER_OPERATOR(instance_norm_grad_grad, ops::InstanceNormDoubleGradOp,
163 164
                  ops::InstanceNormDoubleGradOpInplaceInferer,
                  InstanceNormDoubleGradInferShapeFunctor);
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181

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));