instance_norm_op.cc 7.3 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<phi::DenseTensor>("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<phi::DenseTensor>("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

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

void InstanceNormOpMaker::Make() {
  AddAttr<float>("epsilon", "")
      .SetDefault(1e-5)
      .AddCustomChecker([](const float &epsilon) {
64 65
        PADDLE_ENFORCE_EQ(epsilon >= 0.0f && epsilon <= 0.001f,
                          true,
66 67
                          platform::errors::InvalidArgument(
                              "'epsilon' should be between 0.0 and 0.001."));
L
lvmengsi 已提交
68 69 70 71
      });
  AddInput("X", "The input tensor");
  AddInput("Scale",
           "Scale is a 1-dimensional tensor of size C "
C
ceci3 已提交
72 73
           "that is applied to the output")
      .AsDispensable();
L
lvmengsi 已提交
74 75
  AddInput("Bias",
           "Bias is a 1-dimensional tensor of size C "
C
ceci3 已提交
76 77
           "that is applied to the output")
      .AsDispensable();
L
lvmengsi 已提交
78 79 80 81
  AddOutput("Y", "result after normalization");
  AddOutput("SavedMean",
            "Mean of the current mini batch, "
            "will apply to output when training")
C
ceci3 已提交
82 83
      .AsIntermediate()
      .AsExtra();
L
lvmengsi 已提交
84 85 86
  AddOutput("SavedVariance",
            "Variance of the current mini batch, "
            "will apply to output when training")
C
ceci3 已提交
87 88
      .AsIntermediate()
      .AsExtra();
L
lvmengsi 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
  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 已提交
105 106
    PADDLE_THROW(
        platform::errors::NotFound("cannot find gradient variable of Y"));
L
lvmengsi 已提交
107
  }
108 109 110
  const phi::DenseTensor *t = nullptr;
  if (var->IsType<phi::DenseTensor>()) {
    t = &var->Get<phi::DenseTensor>();
111 112
  } else if (var->IsType<phi::DenseTensor>()) {
    t = &var->Get<phi::DenseTensor>();
L
lvmengsi 已提交
113 114
  }
  if (t == nullptr) {
C
ceci3 已提交
115 116
    PADDLE_THROW(
        platform::errors::InvalidArgument("gradient variable of Y is empty"));
L
lvmengsi 已提交
117
  }
118 119
  return framework::OpKernelType(
      OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.GetPlace());
L
lvmengsi 已提交
120 121 122 123 124 125
}

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

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

}  // namespace operators
}  // namespace paddle

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

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