data_norm_op.cc 31.8 KB
Newer Older
H
heqiaozhi 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2016 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/data_norm_op.h"
16

P
phlrain 已提交
17
#include <memory>
H
heqiaozhi 已提交
18
#include <string>
19

H
heqiaozhi 已提交
20
#include "paddle/fluid/framework/data_layout.h"
21
#include "paddle/fluid/framework/op_version_registry.h"
H
heqiaozhi 已提交
22 23 24 25

namespace paddle {
namespace operators {

26
using Tensor = phi::DenseTensor;
27
using LoDTensor = phi::DenseTensor;
H
heqiaozhi 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
using DataLayout = framework::DataLayout;

template <typename T>
using EigenArrayMap =
    Eigen::Map<Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic>>;
template <typename T>
using ConstEigenArrayMap =
    Eigen::Map<const Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic>>;
template <typename T>
using EigenVectorArrayMap = Eigen::Map<Eigen::Array<T, Eigen::Dynamic, 1>>;
template <typename T>
using ConstEigenVectorArrayMap =
    Eigen::Map<const Eigen::Array<T, Eigen::Dynamic, 1>>;

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

  void InferShape(framework::InferShapeContext *ctx) const override {
47
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "DataNorm");
48 49
    OP_INOUT_CHECK(
        ctx->HasInput("BatchSize"), "Input", "BatchSize", "DataNorm");
50
    OP_INOUT_CHECK(ctx->HasInput("BatchSum"), "Input", "BatchSum", "DataNorm");
51 52
    OP_INOUT_CHECK(
        ctx->HasInput("BatchSquareSum"), "Input", "BatchSquareSum", "DataNorm");
53 54 55
    OP_INOUT_CHECK(ctx->HasOutput("Means"), "Output", "Means", "DataNorm");
    OP_INOUT_CHECK(ctx->HasOutput("Scales"), "Output", "Scales", "DataNorm");
    OP_INOUT_CHECK(ctx->HasOutput("Y"), "Output", "Y", "DataNorm");
56 57 58 59
    bool enable_scale_and_shift =
        ctx->Attrs().Get<bool>("enable_scale_and_shift");
    if (enable_scale_and_shift) {
      PADDLE_ENFORCE_EQ(
60 61
          ctx->HasInput("scale_w"),
          true,
62 63
          platform::errors::InvalidArgument(
              "Input(scale_w) of DataNormOp should not be null."));
64 65
      PADDLE_ENFORCE_EQ(ctx->HasInput("bias"),
                        true,
66 67 68
                        platform::errors::InvalidArgument(
                            "Input(bias) of DataNormOp should not be null."));
    }
H
heqiaozhi 已提交
69 70 71 72 73

    const auto x_dims = ctx->GetInputDim("X");
    const DataLayout data_layout = framework::StringToDataLayout(
        ctx->Attrs().Get<std::string>("data_layout"));

74 75
    PADDLE_ENFORCE_EQ(x_dims.size() >= 2 && x_dims.size() <= 5,
                      true,
76 77
                      platform::errors::InvalidArgument(
                          "Input X must have 2 to 5 dimensions."));
H
heqiaozhi 已提交
78 79 80 81 82

    const int64_t C =
        (data_layout == DataLayout::kNCHW ? x_dims[1]
                                          : x_dims[x_dims.size() - 1]);

83 84
    PADDLE_ENFORCE_EQ(ctx->GetInputDim("BatchSize").size(),
                      1UL,
85 86
                      platform::errors::InvalidArgument(
                          "The input dim of BatchSize shouold be 1"));
87 88
    PADDLE_ENFORCE_EQ(ctx->GetInputDim("BatchSum").size(),
                      1UL,
89 90
                      platform::errors::InvalidArgument(
                          "The input dim of BatchSum shouold be 1"));
91 92
    PADDLE_ENFORCE_EQ(ctx->GetInputDim("BatchSquareSum").size(),
                      1UL,
93 94
                      platform::errors::InvalidArgument(
                          "The input dim of BatchSquareSum shouold be 1"));
P
phlrain 已提交
95
    if (ctx->IsRuntime()) {
96 97
      PADDLE_ENFORCE_EQ(ctx->GetInputDim("BatchSize")[0],
                        C,
98 99
                        platform::errors::InvalidArgument(
                            "The input dim[0] of BatchSize shouold be C"));
100 101
      PADDLE_ENFORCE_EQ(ctx->GetInputDim("BatchSum")[0],
                        C,
102 103
                        platform::errors::InvalidArgument(
                            "The input dim[0] of BatchSum shouold be C"));
104 105
      PADDLE_ENFORCE_EQ(ctx->GetInputDim("BatchSquareSum")[0],
                        C,
106 107
                        platform::errors::InvalidArgument(
                            "The input dim[0] of BatchSqureSum shouold be C"));
P
phlrain 已提交
108
    }
H
heqiaozhi 已提交
109

110 111 112 113 114
    if (enable_scale_and_shift) {
      auto scale_dim = ctx->GetInputDim("scale_w");
      auto bias_dim = ctx->GetInputDim("bias");

      PADDLE_ENFORCE_EQ(
115 116
          scale_dim.size(),
          1UL,
117 118 119 120
          platform::errors::InvalidArgument("the dimensionof scale"
                                            "must equal to 1. But received: "
                                            "the shape of scale is [%s], "
                                            "the dimensionof scale is [%d]",
121 122
                                            scale_dim,
                                            scale_dim.size()));
123
      PADDLE_ENFORCE_EQ(
124 125
          bias_dim.size(),
          1UL,
126 127 128 129
          platform::errors::InvalidArgument("the dimension of bias"
                                            "must equal to 1. But received: "
                                            "the shape of bias is [%s],"
                                            "the dimension of bias is [%d]",
130 131
                                            bias_dim,
                                            bias_dim.size()));
132 133

      bool check = true;
134
      if ((!ctx->IsRuntime()) &&
135
          (phi::product(scale_dim) <= 0 || phi::product(bias_dim) <= 0)) {
136 137 138 139
        check = false;
      }

      if (check) {
140 141
        PADDLE_ENFORCE_EQ(scale_dim[0],
                          C,
142 143 144
                          platform::errors::InvalidArgument(
                              "the shape of scale must equal to [%d]"
                              "But received: the shape of scale is [%d]",
145 146 147 148
                              C,
                              scale_dim[0]));
        PADDLE_ENFORCE_EQ(bias_dim[0],
                          C,
149 150 151
                          platform::errors::InvalidArgument(
                              "the shape of bias must equal to [%d]"
                              "But received: the shape of bias is [%d]",
152 153
                              C,
                              bias_dim[0]));
154 155 156
      }
    }

H
heqiaozhi 已提交
157 158 159 160 161 162 163 164 165
    ctx->SetOutputDim("Y", x_dims);
    ctx->SetOutputDim("Means", {C});
    ctx->SetOutputDim("Scales", {C});
    ctx->ShareLoD("X", "Y");
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
166
    auto input_data_type = OperatorWithKernel::IndicateVarDataType(ctx, "X");
H
heqiaozhi 已提交
167 168 169 170 171 172 173
    // 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 dn_param_type = framework::proto::VarType::FP32;
    if (input_data_type == framework::proto::VarType::FP64) {
      dn_param_type = framework::proto::VarType::FP64;
    }
174 175
    PADDLE_ENFORCE_EQ(dn_param_type,
                      OperatorWithKernel::IndicateVarDataType(ctx, "BatchSize"),
176 177
                      platform::errors::InvalidArgument(
                          "BatchSize input should be of float type"));
H
heqiaozhi 已提交
178
    PADDLE_ENFORCE_EQ(dn_param_type,
179
                      OperatorWithKernel::IndicateVarDataType(ctx, "BatchSum"),
180 181
                      platform::errors::InvalidArgument(
                          "BatchSum input should be of float type"));
182 183 184 185 186
    PADDLE_ENFORCE_EQ(
        dn_param_type,
        OperatorWithKernel::IndicateVarDataType(ctx, "BatchSquareSum"),
        platform::errors::InvalidArgument(
            "BatchSquareSum input should be of float type"));
H
heqiaozhi 已提交
187

188 189 190 191 192 193 194 195 196 197 198
    bool enable_scale_and_shift = ctx.Attr<bool>("enable_scale_and_shift");
    if (enable_scale_and_shift) {
      PADDLE_ENFORCE_EQ(dn_param_type,
                        OperatorWithKernel::IndicateVarDataType(ctx, "scale_w"),
                        platform::errors::InvalidArgument(
                            "scale_w input should be of float type"));
      PADDLE_ENFORCE_EQ(dn_param_type,
                        OperatorWithKernel::IndicateVarDataType(ctx, "bias"),
                        platform::errors::InvalidArgument(
                            "bias input should be of float type"));
    }
H
heqiaozhi 已提交
199

200
    return framework::OpKernelType(input_data_type, ctx.GetPlace());
H
heqiaozhi 已提交
201 202 203 204 205 206 207 208 209 210
  }
};

class DataNormOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    // AddAttr<bool>("is_test", "").SetDefault(false);
    AddAttr<float>("epsilon", "")
        .SetDefault(1e-4)
        .AddCustomChecker([](const float &epsilon) {
211 212
          PADDLE_ENFORCE_EQ(epsilon >= 0.0f && epsilon <= 0.001f,
                            true,
213 214
                            platform::errors::InvalidArgument(
                                "'epsilon' should be between 0.0 and 0.001."));
H
heqiaozhi 已提交
215
        });
216 217 218 219
    AddAttr<int>("slot_dim",
                 "(int, default -1) Dimension of one slot if set, "
                 "when the input is concated by slot-wise embeddings")
        .SetDefault(-1);
H
hutuxian 已提交
220 221 222 223
    AddAttr<float>(
        "summary_decay_rate",
        "(float, default 0.9999999) The decay rate when update the summary")
        .SetDefault(0.9999999);
224 225 226 227 228 229 230 231 232 233 234 235 236
    AddAttr<bool>(
        "enable_scale_and_shift",
        "(bool, default false) Set to true to enable scale and shift such as "
        "batch_norm op")
        .SetDefault(false);
    AddInput("scale_w",
             "scale_w 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();
H
heqiaozhi 已提交
237
    AddAttr<std::string>("data_layout", "").SetDefault("NCHW");
H
hutuxian 已提交
238 239
    AddAttr<bool>("sync_stats", "(bool, default false) only used in multi-GPU")
        .SetDefault(false);
H
heqiaozhi 已提交
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
    AddInput("X", "The input tensor");
    AddInput("BatchSize",
             "BatchSize is a 1-dimensional tensor of size C "
             "that is applied to the output");
    AddInput("BatchSum",
             "BatchSum is a 1-dimensional tensor of size C "
             "that is applied to the output");
    AddInput("BatchSquareSum",
             "The global BatchSquareSum (for training) or "
             "estimated BatchSquareSum (for testing)");
    AddOutput("Y", "result after normalization");
    AddOutput("Means",
              "Mean of the history data batch, "
              "will apply to output when training")
        .AsIntermediate();
    AddOutput("Scales",
              "Scales of the history data batch, "
              "will apply to output when training")
        .AsIntermediate();
    AddComment(R"DOC(
Data Normalization.

Can be used as a normalizer function for data
The required data format for this layer is one of the following:
1. NHWC `[batch, in_height, in_width, in_channels]`
2. NCHW `[batch, in_channels, in_height, in_width]`

)DOC");
  }
};

template <typename T>
L
Leo Chen 已提交
272
class DataNormKernel<phi::CPUContext, T> : public framework::OpKernel<T> {
H
heqiaozhi 已提交
273 274 275 276 277 278 279
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
    // const bool is_test = ctx.Attr<bool>("is_test");
    const std::string data_layout_str = ctx.Attr<std::string>("data_layout");
    const DataLayout data_layout =
        framework::StringToDataLayout(data_layout_str);

280
    const auto *x = ctx.Input<phi::DenseTensor>("X");
H
heqiaozhi 已提交
281
    const auto &x_dims = x->dims();
282
    PADDLE_ENFORCE_EQ(
283 284
        x_dims.size(),
        2,
285
        platform::errors::InvalidArgument("The Input dim size should be 2"));
H
heqiaozhi 已提交
286 287 288 289
    const int N = x_dims[0];
    const int C =
        (data_layout == DataLayout::kNCHW ? x_dims[1]
                                          : x_dims[x_dims.size() - 1]);
290 291 292
    auto *y = ctx.Output<phi::DenseTensor>("Y");
    auto *mean_out = ctx.Output<phi::DenseTensor>("Means");
    auto *scales = ctx.Output<phi::DenseTensor>("Scales");
H
heqiaozhi 已提交
293 294

    // alloc memory
295
    T *y_data = y->mutable_data<T>(ctx.GetPlace());
H
heqiaozhi 已提交
296 297

    ConstEigenVectorArrayMap<T> b_size_arr(
298
        ctx.Input<phi::DenseTensor>("BatchSize")->data<T>(), C);
H
heqiaozhi 已提交
299
    ConstEigenVectorArrayMap<T> b_sum_arr(
300
        ctx.Input<phi::DenseTensor>("BatchSum")->data<T>(), C);
H
heqiaozhi 已提交
301
    ConstEigenVectorArrayMap<T> b_square_sum_arr(
302
        ctx.Input<phi::DenseTensor>("BatchSquareSum")->data<T>(), C);
H
heqiaozhi 已提交
303 304 305 306 307 308 309
    EigenVectorArrayMap<T> means_arr(mean_out->mutable_data<T>(ctx.GetPlace()),
                                     C);
    EigenVectorArrayMap<T> scales_arr(scales->mutable_data<T>(ctx.GetPlace()),
                                      C);
    means_arr = b_sum_arr / b_size_arr;
    scales_arr = (b_size_arr / b_square_sum_arr).sqrt();

310 311
    const T *means_data = mean_out->data<T>();
    const T *x_data = x->data<T>();
312

313 314 315
    const T *scales_data = scales->data<T>();
    const int slot_dim = ctx.Attr<int>("slot_dim");
    T min_precision = 1e-7f;
H
heqiaozhi 已提交
316
    switch (data_layout) {
317
      case DataLayout::kNCHW:  // It's two dimensions, so make no difference
H
heqiaozhi 已提交
318
      case DataLayout::kNHWC: {
319 320
        // if slot_dim is set and batch size is larger than zero, we choose
        // to check if show number is zero, if so, skip normalization.
321 322
        if (slot_dim > 0 && N > 0 &&
            (!ctx.Attr<bool>("enable_scale_and_shift"))) {
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
          const int item_size = x->numel() / N;
          // location of show number in one embedding
          int offset = 0;
          for (int k = 0; k < N; ++k) {
            for (int i = 0; i < item_size; i += slot_dim) {
              if (x_data[offset + i] > -min_precision &&
                  x_data[offset + i] < min_precision) {
                // show = 0
                memset(y_data + offset + i, 0, sizeof(T) * slot_dim);
              } else {
                for (int j = i; j < i + slot_dim; ++j) {
                  y_data[offset + j] =
                      (x_data[offset + j] - means_data[j]) * scales_data[j];
                }
              }
            }

            offset += item_size;
          }
        } else {
343 344 345 346 347 348 349 350
          if (!ctx.Attr<bool>("enable_scale_and_shift") && slot_dim <= 0) {
            EigenArrayMap<T>(y_data, C, N) =
                (ConstEigenArrayMap<T>(x->data<T>(), C, N).colwise() -
                 means_arr)
                    .colwise() *
                scales_arr;
          } else if (ctx.Attr<bool>("enable_scale_and_shift") &&
                     slot_dim <= 0) {
351 352
            const auto *scale_w = ctx.Input<phi::DenseTensor>("scale_w");
            const auto *bias = ctx.Input<phi::DenseTensor>("bias");
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
            ConstEigenVectorArrayMap<T> scale_w_arr(scale_w->data<T>(), C);
            ConstEigenVectorArrayMap<T> bias_arr(bias->data<T>(), C);

            Eigen::Array<T, Eigen::Dynamic, 1> new_scale =
                scales_arr * scale_w_arr;
            Eigen::Array<T, Eigen::Dynamic, 1> new_bias =
                bias_arr - means_arr * scales_arr * scale_w_arr;
            EigenArrayMap<T>(y_data, C, N) =
                (ConstEigenArrayMap<T>(x->data<T>(), C, N).colwise() *
                 new_scale)
                    .colwise() +
                new_bias;

          } else {
            const int item_size = x->numel() / N;
368 369
            const auto *scale_w = ctx.Input<phi::DenseTensor>("scale_w");
            const auto *bias = ctx.Input<phi::DenseTensor>("bias");
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
            const T *scale_w_data = scale_w->data<T>();
            const T *bias_data = bias->data<T>();
            // location of show number in one embedding
            int offset = 0;
            for (int k = 0; k < N; ++k) {
              for (int i = 0; i < item_size; i += slot_dim) {
                if (x_data[offset + i] > -min_precision &&
                    x_data[offset + i] < min_precision) {
                  // show = 0
                  memset(y_data + offset + i, 0, sizeof(T) * slot_dim);
                } else {
                  for (int j = i; j < i + slot_dim; ++j) {
                    y_data[offset + j] = ((x_data[offset + j] - means_data[j]) *
                                          scales_data[j]) *
                                             scale_w_data[j] +
                                         bias_data[j];
                  }
                }
              }  // end for i

              offset += item_size;
            }  // end for k
          }
393
        }
H
heqiaozhi 已提交
394 395 396
        break;
      }
      default:
397
        PADDLE_THROW(platform::errors::InvalidArgument(
Y
yaoxuefeng 已提交
398
            "Unknown storage order: %d, please use NCHW or NHWC", data_layout));
H
heqiaozhi 已提交
399 400 401 402 403 404 405 406 407 408
    }
  }
};

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

  void InferShape(framework::InferShapeContext *ctx) const override {
    // check input
409
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "DataNormGrad");
410 411 412 413
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Y")),
                   "Input",
                   framework::GradVarName("Y"),
                   "DataNormGrad");
H
hutuxian 已提交
414
    PADDLE_ENFORCE_EQ(
415 416
        ctx->HasOutput("BatchSize"),
        true,
H
hutuxian 已提交
417 418 419
        platform::errors::NotFound(
            "Output(BatchSize) of DataNormGradOp should not be null."));
    PADDLE_ENFORCE_EQ(
420 421
        ctx->HasOutput("BatchSum"),
        true,
H
hutuxian 已提交
422 423 424
        platform::errors::NotFound(
            "Output(BatchSum) of DataNormGradOp should not be null."));
    PADDLE_ENFORCE_EQ(
425 426
        ctx->HasOutput("BatchSquareSum"),
        true,
H
hutuxian 已提交
427 428
        platform::errors::NotFound(
            "Output(BatchSquareSum) of DataNormGradOp should not be null."));
429 430
    OP_INOUT_CHECK(ctx->HasInput("Means"), "Input", "Means", "DataNormGrad");
    OP_INOUT_CHECK(ctx->HasInput("Scales"), "Input", "Scales", "DataNormGrad");
431 432
    bool enable_scale_and_shift =
        ctx->Attrs().Get<bool>("enable_scale_and_shift");
H
heqiaozhi 已提交
433
    // check output
434
    OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("BatchSize")),
435 436 437 438 439 440
                   "Output",
                   framework::GradVarName("BatchSize"),
                   "DataNormGrad");
    OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("BatchSum")),
                   "Output",
                   framework::GradVarName("BatchSum"),
441 442
                   "DataNormGrad");
    OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("BatchSquareSum")),
443 444
                   "Output",
                   framework::GradVarName("BatchSquareSum"),
445
                   "DataNormGrad");
H
heqiaozhi 已提交
446 447 448 449 450 451 452 453

    const auto x_dims = ctx->GetInputDim("X");
    const DataLayout data_layout = framework::StringToDataLayout(
        ctx->Attrs().Get<std::string>("data_layout"));
    const int C =
        (data_layout == DataLayout::kNCHW ? x_dims[1]
                                          : x_dims[x_dims.size() - 1]);

454 455 456
    if (ctx->HasOutput(framework::GradVarName("X"))) {
      ctx->SetOutputDim(framework::GradVarName("X"), x_dims);
    }
H
heqiaozhi 已提交
457 458 459
    ctx->SetOutputDim(framework::GradVarName("BatchSize"), {C});
    ctx->SetOutputDim(framework::GradVarName("BatchSum"), {C});
    ctx->SetOutputDim(framework::GradVarName("BatchSquareSum"), {C});
460 461 462 463 464
    if (enable_scale_and_shift) {
      const bool has_scale_grad =
          ctx->HasOutput(framework::GradVarName("scale_w"));
      const bool has_bias_grad = ctx->HasOutput(framework::GradVarName("bias"));

465 466
      PADDLE_ENFORCE_EQ((has_scale_grad == has_bias_grad),
                        true,
467 468 469 470
                        platform::errors::InvalidArgument(
                            "Output(Scale@GRAD) and Output(Bias@GRAD)"
                            "must be null or not be null at same time. "
                            "But now, has Scale@Grad=[%d], has Bias@GRAD=[%d]",
471 472
                            has_scale_grad,
                            has_bias_grad));
473 474 475 476 477
      if (has_scale_grad) {
        ctx->SetOutputDim(framework::GradVarName("scale_w"), {C});
        ctx->SetOutputDim(framework::GradVarName("bias"), {C});
      }
    }
H
heqiaozhi 已提交
478 479 480 481 482 483 484
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
    const auto *var = ctx.InputVar(framework::GradVarName("Y"));
    if (var == nullptr) {
485 486
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Y@GRAD can not be found for computation"));
H
heqiaozhi 已提交
487 488 489 490 491 492 493 494
    }
    const Tensor *t = nullptr;
    if (var->IsType<Tensor>()) {
      t = &var->Get<Tensor>();
    } else if (var->IsType<LoDTensor>()) {
      t = &var->Get<LoDTensor>();
    }
    if (t == nullptr) {
495 496
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Y@GRAD can not be found for computation"));
H
heqiaozhi 已提交
497 498
    }

499
    auto data_type = OperatorWithKernel::IndicateVarDataType(ctx, "X");
500
    return framework::OpKernelType(data_type, ctx.GetPlace());
H
heqiaozhi 已提交
501 502 503 504
  }
};

template <typename T>
L
Leo Chen 已提交
505
class DataNormGradKernel<phi::CPUContext, T> : public framework::OpKernel<T> {
H
heqiaozhi 已提交
506 507
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
508 509 510 511
    const auto *x = ctx.Input<phi::DenseTensor>("X");
    const auto *d_y = ctx.Input<phi::DenseTensor>(framework::GradVarName("Y"));
    const auto *scales = ctx.Input<phi::DenseTensor>("Scales");
    const auto *means = ctx.Input<phi::DenseTensor>("Means");
H
heqiaozhi 已提交
512 513 514 515 516 517 518 519

    const std::string data_layout_str = ctx.Attr<std::string>("data_layout");
    const DataLayout data_layout =
        framework::StringToDataLayout(data_layout_str);

    // Get the size for each dimension.
    // NCHW [batch_size, in_channels, in_height, in_width]
    const auto &x_dims = x->dims();
520
    PADDLE_ENFORCE_EQ(
521 522
        x_dims.size(),
        2,
523
        platform::errors::InvalidArgument("The Input dim size should be 2"));
H
heqiaozhi 已提交
524 525 526 527 528
    const int N = x_dims[0];
    const int C =
        (data_layout == DataLayout::kNCHW ? x_dims[1]
                                          : x_dims[x_dims.size() - 1]);
    // init output
529 530
    Tensor *d_x = nullptr;
    if (ctx.HasOutput(framework::GradVarName("X"))) {
531
      d_x = ctx.Output<phi::DenseTensor>(framework::GradVarName("X"));
532
    }
533

H
heqiaozhi 已提交
534
    auto *d_batch_size =
535 536 537
        ctx.Output<phi::DenseTensor>(framework::GradVarName("BatchSize"));
    auto *d_batch_sum =
        ctx.Output<phi::DenseTensor>(framework::GradVarName("BatchSum"));
H
heqiaozhi 已提交
538
    auto *d_batch_square_sum =
539
        ctx.Output<phi::DenseTensor>(framework::GradVarName("BatchSquareSum"));
H
heqiaozhi 已提交
540

541 542 543 544 545
    const T *mean_data = means->data<T>();
    const T *inv_var_data = scales->data<T>();
    ConstEigenVectorArrayMap<T> mean_arr(mean_data, C);
    ConstEigenVectorArrayMap<T> inv_var_arr(inv_var_data, C);

546 547 548 549 550 551 552
    T *d_batch_size_data = d_batch_size->mutable_data<T>(ctx.GetPlace());
    T *d_batch_sum_data = d_batch_sum->mutable_data<T>(ctx.GetPlace());
    T *d_batch_square_sum_data =
        d_batch_square_sum->mutable_data<T>(ctx.GetPlace());
    EigenVectorArrayMap<T> d_batch_size_arr(d_batch_size_data, C);
    EigenVectorArrayMap<T> d_batch_sum_arr(d_batch_sum_data, C);
    EigenVectorArrayMap<T> d_batch_square_sum_arr(d_batch_square_sum_data, C);
H
heqiaozhi 已提交
553 554 555
    d_batch_size_arr.setZero();
    d_batch_sum_arr.setZero();
    d_batch_square_sum_arr.setZero();
556 557
    const T *x_data = x->data<T>();
    const T *means_data = means->data<T>();
H
heqiaozhi 已提交
558 559

    const float epsilon = ctx.Attr<float>("epsilon");
560 561 562
    T min_precision = 1e-7f;
    const int slot_dim = ctx.Attr<int>("slot_dim");
    switch (data_layout) {  // it's two dimensions, make no difference
H
heqiaozhi 已提交
563 564 565 566 567 568
      case DataLayout::kNCHW:
      case DataLayout::kNHWC: {
        ConstEigenVectorArrayMap<T> scales_arr(scales->data<T>(), C);
        ConstEigenVectorArrayMap<T> means_arr(means->data<T>(), C);
        ConstEigenArrayMap<T> x_arr(x->data<T>(), C, N);
        ConstEigenArrayMap<T> d_y_arr(d_y->data<T>(), C, N);
569 570 571
        if (d_x != nullptr) {
          EigenArrayMap<T> d_x_arr(d_x->mutable_data<T>(ctx.GetPlace()), C, N);
          d_x_arr.setZero();
572 573 574 575 576
          if (!ctx.Attr<bool>("enable_scale_and_shift")) {
            for (int nc = 0; nc < N; ++nc) {
              d_x_arr.col(nc) = d_y_arr.col(nc) * scales_arr;
            }
          } else {
577
            const auto *scale_w = ctx.Input<phi::DenseTensor>("scale_w");
578
            auto *d_scale =
579 580 581
                ctx.Output<phi::DenseTensor>(framework::GradVarName("scale_w"));
            auto *d_bias =
                ctx.Output<phi::DenseTensor>(framework::GradVarName("bias"));
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
            ConstEigenVectorArrayMap<T> scale_arr(scale_w->data<T>(), C);
            T *d_bias_data = nullptr;
            T *d_scale_data = nullptr;

            d_scale->mutable_data<T>(ctx.GetPlace());
            d_bias->mutable_data<T>(ctx.GetPlace());
            d_bias_data = d_bias->mutable_data<T>(ctx.GetPlace());
            d_scale_data = d_scale->mutable_data<T>(ctx.GetPlace());

            EigenVectorArrayMap<T> d_bias_arr(d_bias_data, C);
            EigenVectorArrayMap<T> d_scale_arr(d_scale_data, C);
            Tensor dy_sum;
            dy_sum.Resize({C});
            dy_sum.mutable_data<T>(ctx.GetPlace());
            EigenVectorArrayMap<T> dy_sum_arr(
                dy_sum.mutable_data<T>(ctx.GetPlace()), C);
            Tensor dy_mul_x_sub_mean_mul_invstd_sum;
            dy_mul_x_sub_mean_mul_invstd_sum.Resize({C});
            dy_mul_x_sub_mean_mul_invstd_sum.mutable_data<T>(ctx.GetPlace());
            EigenVectorArrayMap<T> dy_mul_x_sub_mean_mul_invstd_sum_arr(
                dy_mul_x_sub_mean_mul_invstd_sum.mutable_data<T>(
                    ctx.GetPlace()),
                C);

            dy_sum_arr.setZero();
            dy_mul_x_sub_mean_mul_invstd_sum_arr.setZero();

            if (slot_dim <= 0) {
              for (int n = 0; n < N; ++n) {
                dy_sum_arr += d_y_arr.col(n);
                dy_mul_x_sub_mean_mul_invstd_sum_arr +=
                    ((x_arr.col(n) - mean_arr) * inv_var_arr * d_y_arr.col(n));
              }
              if (d_scale && d_bias) {
                d_bias_arr = dy_sum_arr;
                d_scale_arr = dy_mul_x_sub_mean_mul_invstd_sum_arr;
              }
              for (int nc = 0; nc < N; ++nc) {
                d_x_arr.col(nc) = d_y_arr.col(nc) * scales_arr * scale_arr;
              }
            } else {
              int offset = 0;
              const int item_size = x->numel() / N;
              T *d_x_data = d_x->mutable_data<T>(ctx.GetPlace());
              T *d_scale_data = d_scale->mutable_data<T>(ctx.GetPlace());
              T *d_bias_data = d_bias->mutable_data<T>(ctx.GetPlace());
              const T *dy_data = d_y->data<T>();
              const T *scales_data = scales->data<T>();
              const T *scale_w_data = scale_w->data<T>();
              const T *x_data = x->data<T>();
              for (int i = 0; i < item_size; i++) {
                d_bias_data[i] = 0;
                d_scale_data[i] = 0;
              }
              for (int k = 0; k < N; ++k) {
                for (int i = 0; i < item_size; i += slot_dim) {
                  if (!(x_data[offset + i] > -min_precision &&
                        x_data[offset + i] < min_precision)) {
                    // show != 0
                    for (int j = i; j < i + slot_dim; ++j) {
                      d_x_data[offset + j] = dy_data[offset + j] *
                                             scales_data[j] * scale_w_data[j];
                      d_bias_data[j] += dy_data[offset + j];
                      d_scale_data[j] += (x_data[offset + j] - mean_data[j]) *
                                         inv_var_data[j] * dy_data[offset + j];
                    }
                  }
                }
                offset += item_size;
              }
            }
653
          }
H
heqiaozhi 已提交
654 655
        }

656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
        if (slot_dim > 0 && N > 0) {
          // if slot_dim is set and batch size is larger than zero, we choose
          // to check if show number is zero, if so, skip update statistics.
          int offset = 0;
          const int item_size = x->numel() / N;
          for (int k = 0; k < N; ++k) {
            for (int i = 0; i < item_size; i += slot_dim) {
              if (!(x_data[offset + i] > -min_precision &&
                    x_data[offset + i] < min_precision)) {
                // show != 0
                for (int j = i; j < i + slot_dim; ++j) {
                  d_batch_size_data[j] += 1;
                  d_batch_sum_data[j] += x_data[offset + j];
                  d_batch_square_sum_data[j] +=
                      (x_data[offset + j] - means_data[j]) *
                      (x_data[offset + j] - means_data[j]);
                }
              }
            }
            offset += item_size;
          }

          for (int i = 0; i < item_size; i += slot_dim) {
            for (int j = i; j < i + slot_dim; ++j) {
              if (d_batch_size_data[j] >= 1) {
                d_batch_sum_data[j] /= d_batch_size_data[j];
                d_batch_square_sum_data[j] =
                    d_batch_square_sum_data[j] / d_batch_size_data[j] +
                    d_batch_size_data[j] * epsilon;
                d_batch_size_data[j] = 1;
              }
            }
          }
        } else {
          // calculate data sum and squre sum
          Eigen::Array<T, Eigen::Dynamic, 1> sample_sum(C);
          Eigen::Array<T, Eigen::Dynamic, 1> sample_square_sum(C);
          // calculate data sample sum and square sum
          sample_sum.setZero();
          sample_square_sum.setZero();
          for (int nc = 0; nc < N; ++nc) {
            sample_sum += x_arr.col(nc);
            sample_square_sum += (x_arr.col(nc) - means_arr).square();
          }
          // calculate gradient
          d_batch_size_arr.setConstant(N);
          d_batch_sum_arr = sample_sum;
          d_batch_square_sum_arr =
              sample_square_sum + d_batch_size_arr * epsilon;
H
heqiaozhi 已提交
705 706 707 708
        }
        break;
      }
      default:
709
        PADDLE_THROW(platform::errors::InvalidArgument(
Y
yaoxuefeng 已提交
710 711
            "Unknown storage order: %s, please use NCHW or NHWC",
            data_layout_str));
H
heqiaozhi 已提交
712 713 714 715
    }
  }
};

H
hong 已提交
716 717
template <typename T>
class DataNormGradMaker : public framework::SingleGradOpMaker<T> {
H
heqiaozhi 已提交
718
 public:
H
hong 已提交
719
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
H
heqiaozhi 已提交
720 721

 protected:
722
  void Apply(GradOpPtr<T> op) const override {
H
heqiaozhi 已提交
723
    op->SetType("data_norm_grad");
H
hong 已提交
724 725 726
    op->SetInput("X", this->Input("X"));
    op->SetInput(framework::GradVarName("Y"), this->OutputGrad("Y"));

727 728
    op->SetInput("scale_w", this->Input("scale_w"));
    op->SetInput("bias", this->Input("bias"));
H
hutuxian 已提交
729 730 731
    op->SetOutput("BatchSize", this->Input("BatchSize"));
    op->SetOutput("BatchSum", this->Input("BatchSum"));
    op->SetOutput("BatchSquareSum", this->Input("BatchSquareSum"));
H
hong 已提交
732 733 734 735 736 737 738 739 740 741
    op->SetInput("Scales", this->Output("Scales"));
    op->SetInput("Means", this->Output("Means"));

    op->SetAttrMap(this->Attrs());

    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetOutput(framework::GradVarName("BatchSize"),
                  this->InputGrad("BatchSize"));
    op->SetOutput(framework::GradVarName("BatchSum"),
                  this->InputGrad("BatchSum"));
H
heqiaozhi 已提交
742
    op->SetOutput(framework::GradVarName("BatchSquareSum"),
H
hong 已提交
743
                  this->InputGrad("BatchSquareSum"));
744 745 746
    op->SetOutput(framework::GradVarName("scale_w"),
                  this->InputGrad("scale_w"));
    op->SetOutput(framework::GradVarName("bias"), this->InputGrad("bias"));
H
heqiaozhi 已提交
747 748 749 750 751 752 753
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
754 755 756
REGISTER_OPERATOR(data_norm,
                  ops::DataNormOp,
                  ops::DataNormOpMaker,
H
hong 已提交
757 758
                  ops::DataNormGradMaker<paddle::framework::OpDesc>,
                  ops::DataNormGradMaker<paddle::imperative::OpBase>);
H
heqiaozhi 已提交
759 760
REGISTER_OPERATOR(data_norm_grad, ops::DataNormGradOp);

L
Leo Chen 已提交
761 762 763 764 765 766
REGISTER_OP_CPU_KERNEL(data_norm,
                       ops::DataNormKernel<phi::CPUContext, float>,
                       ops::DataNormKernel<phi::CPUContext, double>);
REGISTER_OP_CPU_KERNEL(data_norm_grad,
                       ops::DataNormGradKernel<phi::CPUContext, float>,
                       ops::DataNormGradKernel<phi::CPUContext, double>);
767 768
REGISTER_OP_VERSION(data_norm).AddCheckpoint(
    R"ROC(
769
              upgrad data_norm op by adding scale_w to support scale and shift.)ROC",
770 771 772
    paddle::framework::compatible::OpVersionDesc().NewInput(
        "scale_w",
        "scale_w is used to do scale duirng data_norm like batchnorm "));