group_norm_op.cc 10.6 KB
Newer Older
D
Dun 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2018 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/group_norm_op.h"
L
liuwei1031 已提交
16
#include <memory>
17
#include <string>
L
liuwei1031 已提交
18
#include <unordered_map>
19
#include <vector>
D
Dun 已提交
20 21 22 23 24 25 26 27 28 29 30 31 32

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
using LoDTensor = framework::LoDTensor;
using DataLayout = framework::DataLayout;

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

  void InferShape(framework::InferShapeContext *ctx) const override {
33 34 35 36 37 38
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "GroupNorm");
    OP_INOUT_CHECK(ctx->HasOutput("Y"), "Output", "Y", "GroupNorm");
    OP_INOUT_CHECK(ctx->HasOutput("Mean"), "Output", "Mean", "GroupNorm");
    OP_INOUT_CHECK(ctx->HasOutput("Variance"), "Output", "Variance",
                   "GroupNorm");

D
Dun 已提交
39
    auto x_dim = ctx->GetInputDim("X");
40 41 42 43 44 45 46
    PADDLE_ENFORCE_GE(
        x_dim.size(), 2,
        platform::errors::InvalidArgument(
            "The Input(X)'s dimension of Op(group_norm) must be "
            "greater than 1. But received: %u-D Tensor, which shape is [%s].",
            x_dim.size(), x_dim));

47 48 49 50
    const std::string data_layout_str =
        ctx->Attrs().Get<std::string>("data_layout");
    const framework::DataLayout data_layout =
        framework::StringToDataLayout(data_layout_str);
51 52
    const int64_t channel_num =
        (data_layout == DataLayout::kNCHW ? x_dim[1] : x_dim[x_dim.size() - 1]);
D
Dun 已提交
53 54 55 56
    auto batch_size = x_dim[0];
    auto groups = ctx->Attrs().Get<int>("groups");
    PADDLE_ENFORCE_LE(
        groups, channel_num,
57 58 59 60 61 62
        platform::errors::InvalidArgument(
            "The Attr(groups) of Op(group_norm) must be less than or "
            "equal to the number of channels. But received: groups "
            "is [%s], channels is [%s], the Attr(data_layout) "
            "is [%s]. The error may come from wrong data_layout setting.",
            groups, channel_num, data_layout_str));
63 64
    PADDLE_ENFORCE_GE(
        groups, 1,
65 66 67 68
        platform::errors::InvalidArgument(
            "The Attr(groups) of Op(group_norm) must be "
            "greater than or equal to 1. But received: groups is [%s].",
            groups));
69 70 71 72 73 74
    PADDLE_ENFORCE_EQ(
        channel_num % groups, 0,
        platform::errors::InvalidArgument(
            "Expected number of channels in input to be divisible by "
            "num_groups, but got input channel is %d and num_groups is %d",
            channel_num, groups));
D
Dun 已提交
75 76

    if (ctx->HasInput("Scale")) {
77 78
      PADDLE_ENFORCE_EQ(
          ctx->GetInputDim("Scale").size(), 1UL,
79 80 81 82
          platform::errors::InvalidArgument(
              "The Input(Scale) of Op(group_norm) should be 1-D Tensor. "
              "But received: %u-D Tensor, the shape of Input(Scale) is [%s].",
              ctx->GetInputDim("Scale").size(), ctx->GetInputDim("Scale")));
83 84
      PADDLE_ENFORCE_EQ(
          ctx->GetInputDim("Scale")[0], channel_num,
85 86 87 88 89 90 91
          platform::errors::InvalidArgument(
              "The Input(Scale)'s first dimension size of Op(group_norm) must "
              "be equal to the number of channels. But received: the "
              "Input(Scale)'s first dimension size is [%s], the channels is "
              "[%s], the Attr(data_layout) is [%s]. The error may come "
              "from wrong data_layout setting.",
              ctx->GetInputDim("Scale")[0], channel_num, data_layout_str));
D
Dun 已提交
92 93
    }
    if (ctx->HasInput("Bias")) {
94 95
      PADDLE_ENFORCE_EQ(
          ctx->GetInputDim("Bias").size(), 1UL,
96 97 98 99
          platform::errors::InvalidArgument(
              "The Input(Bias) of Op(group_norm) should be 1-D Tensor. "
              "But received: %u-D Tensor, the shape of Input(Bias) is [%s].",
              ctx->GetInputDim("Bias").size(), ctx->GetInputDim("Bias")));
100 101
      PADDLE_ENFORCE_EQ(
          ctx->GetInputDim("Bias")[0], channel_num,
102 103 104 105 106 107 108
          platform::errors::InvalidArgument(
              "The Input(Bias)'s first dimension size of "
              "Op(group_norm) must be equal to the number of channels. "
              "But received: the Input(Bias)'s first dimension size is [%s], "
              "the channels is [%s], the Attr(data_layout) is [%s]. The "
              "error may come from wrong data_layout setting.",
              ctx->GetInputDim("Bias")[0], channel_num, data_layout_str));
D
Dun 已提交
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 135 136 137
    }

    ctx->SetOutputDim("Y", ctx->GetInputDim("X"));
    ctx->SetOutputDim("Mean", {batch_size, groups});
    ctx->SetOutputDim("Variance", {batch_size, groups});
    ctx->ShareLoD("X", "Y");
  }
};

class GroupNormOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X", "The input tensor.");
    AddInput("Scale",
             "Scale is a 1-dimensional tensor of size C"
             "that is applied to the output.")
        .AsDispensable();
    AddInput("Bias",
             "Bias is a 1-dimensional tensor of size C "
             "that is applied to the output")
        .AsDispensable();
    AddOutput("Y", "Result after normalization.");
    AddOutput("Mean", "Mean of each group.").AsIntermediate();
    AddOutput("Variance", "Variance of each group.").AsIntermediate();

    AddAttr<float>("epsilon",
                   "Constant for numerical stability [default 1e-5].")
        .SetDefault(1e-5)
        .AddCustomChecker([](const float &epsilon) {
138 139 140 141 142
          PADDLE_ENFORCE_EQ(epsilon >= 0.0f && epsilon <= 1.0f, true,
                            platform::errors::InvalidArgument(
                                "'epsilon' in Op(GroupNorm) should be between"
                                "0.0 and 1.0f, But received [%s].",
                                epsilon));
D
Dun 已提交
143 144 145
        });
    AddAttr<int>("groups", "The number of groups that divided from channels.")
        .AddCustomChecker([](const int &groups) {
146 147 148 149 150 151
          PADDLE_ENFORCE_GT(
              groups, 0,
              platform::errors::InvalidArgument(
                  "'groups' in Op(GroupNorm) should be greater than zero,"
                  "But received [%s].",
                  groups));
D
Dun 已提交
152
        });
153 154 155
    AddAttr<std::string>("data_layout",
                         "An optional string from: \"NHWC\", \"NCHW\". ")
        .SetDefault("NCHW");
D
Dun 已提交
156 157 158 159 160 161 162 163 164 165 166 167 168 169
    AddComment(R"DOC(
Group Normalization

Refer to `Group Normalization <https://arxiv.org/abs/1803.08494>`_
)DOC");
  }
};

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

  void InferShape(framework::InferShapeContext *ctx) const override {
    // check input
170 171 172 173 174
    OP_INOUT_CHECK(ctx->HasInput("Y"), "Input", "Y", "GroupNormGrad");
    OP_INOUT_CHECK(ctx->HasInput("Variance"), "Input", "Variance",
                   "GroupNormGrad");
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Y")), "Input",
                   framework::GradVarName("Y"), "GroupNormGrad");
D
Dun 已提交
175 176 177

    // check output
    if (ctx->HasOutput(framework::GradVarName("X"))) {
178
      ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("Y"));
D
Dun 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
    }
    if (ctx->HasOutput(framework::GradVarName("Scale"))) {
      ctx->SetOutputDim(framework::GradVarName("Scale"),
                        ctx->GetInputDim("Scale"));
    }
    if (ctx->HasOutput(framework::GradVarName("Bias"))) {
      ctx->SetOutputDim(framework::GradVarName("Bias"),
                        ctx->GetInputDim("Bias"));
    }
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
    const auto *var = ctx.InputVar(framework::GradVarName("Y"));
194 195 196 197

    PADDLE_ENFORCE_NOT_NULL(
        var, platform::errors::InvalidArgument(
                 "Input(Y@GRAD) of GroupNormGradOp should not be null"));
D
Dun 已提交
198 199 200 201 202 203
    const Tensor *t = nullptr;
    if (var->IsType<Tensor>()) {
      t = &var->Get<Tensor>();
    } else if (var->IsType<LoDTensor>()) {
      t = &var->Get<LoDTensor>();
    }
204 205 206
    PADDLE_ENFORCE_NOT_NULL(
        t, platform::errors::InvalidArgument(
               "Input(Y@GRAD) Tensor of GroupNormGradOp should not be null"));
Y
Yu Yang 已提交
207
    return framework::OpKernelType(t->type(), ctx.GetPlace());
D
Dun 已提交
208 209 210
  }
};

H
hong 已提交
211 212
template <typename T>
class GroupNormGradMaker : public framework::SingleGradOpMaker<T> {
213
 public:
H
hong 已提交
214
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
215

216
  void Apply(GradOpPtr<T> op) const override {
217
    op->SetType("group_norm_grad");
H
hong 已提交
218 219 220 221 222
    op->SetInput("Scale", this->Input("Scale"));
    op->SetInput("Bias", this->Input("Bias"));
    op->SetInput(framework::GradVarName("Y"), this->OutputGrad("Y"));
    op->SetInput("Y", this->Output("Y"));
    op->SetInput("Variance", this->Output("Variance"));
223

H
hong 已提交
224 225 226
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetOutput(framework::GradVarName("Bias"), this->InputGrad("Bias"));
    op->SetOutput(framework::GradVarName("Scale"), this->InputGrad("Scale"));
227

H
hong 已提交
228
    op->SetAttrMap(this->Attrs());
229 230 231
  }
};

232 233
DECLARE_INPLACE_OP_INFERER(GroupNormInplaceInferer, {"X", "Y"});
DECLARE_INPLACE_OP_INFERER(GroupNormGradInplaceInferer,
234 235
                           {framework::GradVarName("Y"),
                            framework::GradVarName("X")});
D
Dun 已提交
236 237 238 239

class GroupNormOpInferVarType
    : public framework::PassInDtypeAndVarTypeToOutput {
 protected:
240
  std::unordered_map<std::string, std::string> &GetInputOutputWithSameType()
D
Dun 已提交
241
      const override {
242 243
    static std::unordered_map<std::string, std::string> m{{"X", /*->*/ "Y"}};
    return m;
D
Dun 已提交
244 245 246
  }
};

D
Dun 已提交
247 248 249 250 251
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OPERATOR(group_norm, ops::GroupNormOp, ops::GroupNormOpMaker,
H
hong 已提交
252 253 254
                  ops::GroupNormOpInferVarType,
                  ops::GroupNormGradMaker<paddle::framework::OpDesc>,
                  ops::GroupNormGradMaker<paddle::imperative::OpBase>,
255
                  ops::GroupNormInplaceInferer);
D
Dun 已提交
256
REGISTER_OPERATOR(group_norm_grad, ops::GroupNormGradOp,
257
                  ops::GroupNormGradInplaceInferer);
D
Dun 已提交
258 259 260 261 262 263 264
REGISTER_OP_CPU_KERNEL(
    group_norm, ops::GroupNormKernel<paddle::platform::CPUDeviceContext, float>,
    ops::GroupNormKernel<paddle::platform::CPUDeviceContext, double>);
REGISTER_OP_CPU_KERNEL(
    group_norm_grad,
    ops::GroupNormGradKernel<paddle::platform::CPUDeviceContext, float>,
    ops::GroupNormGradKernel<paddle::platform::CPUDeviceContext, double>);