instance_norm_op.cc 6.9 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/phi/core/infermeta_utils.h"
#include "paddle/phi/infermeta/backward.h"
#include "paddle/phi/infermeta/ternary.h"
27
#include "paddle/phi/kernels/funcs/math_function.h"
L
lvmengsi 已提交
28 29 30 31 32 33

namespace paddle {
namespace operators {

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

  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,
65 66
                          platform::errors::InvalidArgument(
                              "'epsilon' should be between 0.0 and 0.001."));
L
lvmengsi 已提交
67 68 69 70
      });
  AddInput("X", "The input tensor");
  AddInput("Scale",
           "Scale is a 1-dimensional tensor of size C "
C
ceci3 已提交
71 72
           "that is applied to the output")
      .AsDispensable();
L
lvmengsi 已提交
73 74
  AddInput("Bias",
           "Bias is a 1-dimensional tensor of size C "
C
ceci3 已提交
75 76
           "that is applied to the output")
      .AsDispensable();
L
lvmengsi 已提交
77 78 79 80
  AddOutput("Y", "result after normalization");
  AddOutput("SavedMean",
            "Mean of the current mini batch, "
            "will apply to output when training")
C
ceci3 已提交
81 82
      .AsIntermediate()
      .AsExtra();
L
lvmengsi 已提交
83 84 85
  AddOutput("SavedVariance",
            "Variance of the current mini batch, "
            "will apply to output when training")
C
ceci3 已提交
86 87
      .AsIntermediate()
      .AsExtra();
L
lvmengsi 已提交
88 89 90 91 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");
}

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

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

142
DECLARE_INPLACE_OP_INFERER(InstanceNormDoubleGradOpInplaceInferer,
L
lvmengsi 已提交
143 144 145 146 147 148
                           {"DY", "DDY"});

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
149 150 151 152 153 154 155 156
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 已提交
157
REGISTER_OPERATOR(instance_norm, ops::InstanceNormOp, ops::InstanceNormOpMaker,
H
hong 已提交
158 159
                  ops::InstanceNormOpInferVarType,
                  ops::InstanceNormGradMaker<paddle::framework::OpDesc>,
160 161
                  ops::InstanceNormGradMaker<paddle::imperative::OpBase>,
                  InstanceNormInferShapeFunctor);
L
lvmengsi 已提交
162
REGISTER_OPERATOR(instance_norm_grad, ops::InstanceNormGradOp,
H
hong 已提交
163
                  ops::InstanceNormDoubleGradMaker<paddle::framework::OpDesc>,
164 165
                  ops::InstanceNormDoubleGradMaker<paddle::imperative::OpBase>,
                  InstanceNormGradInferShapeFunctor);
L
lvmengsi 已提交
166
REGISTER_OPERATOR(instance_norm_grad_grad, ops::InstanceNormDoubleGradOp,
167 168
                  ops::InstanceNormDoubleGradOpInplaceInferer,
                  InstanceNormDoubleGradInferShapeFunctor);
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185

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