/* 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/batch_norm_op.h" #include #include #include #include "paddle/fluid/framework/data_layout.h" #ifdef PADDLE_WITH_MKLDNN #include "paddle/fluid/platform/mkldnn_helper.h" #endif namespace paddle { namespace operators { void BatchNormOp::InferShape(framework::InferShapeContext *ctx) const { PADDLE_ENFORCE_EQ(ctx->HasInput("X"), true, platform::errors::InvalidArgument( "Input(X) of BatchNormOp should not be null.")); PADDLE_ENFORCE_EQ(ctx->HasInput("Scale"), true, platform::errors::InvalidArgument( "Input(Scale) of BatchNormOp should not be null.")); PADDLE_ENFORCE_EQ(ctx->HasInput("Bias"), true, platform::errors::InvalidArgument( "Input(Bias) of BatchNormOp should not be null.")); PADDLE_ENFORCE_EQ(ctx->HasInput("Mean"), true, platform::errors::InvalidArgument( "Input(Mean) of BatchNormOp should not be null.")); PADDLE_ENFORCE_EQ(ctx->HasInput("Variance"), true, platform::errors::InvalidArgument( "Input(Variance) of BatchNormOp should not be null.")); PADDLE_ENFORCE_EQ(ctx->HasOutput("Y"), true, platform::errors::InvalidArgument( "Output(Y) of BatchNormOp should not be null.")); bool is_test = ctx->Attrs().Get("is_test"); if (!is_test) { PADDLE_ENFORCE_EQ( ctx->HasOutput("MeanOut"), true, platform::errors::InvalidArgument( "Output(MeanOut) of BatchNormOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasOutput("VarianceOut"), true, platform::errors::InvalidArgument( "Output(VarianceOut) of BatchNormOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasOutput("SavedMean"), true, platform::errors::InvalidArgument( "Output(SavedMean) of BatchNormOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasOutput("SavedVariance"), true, platform::errors::InvalidArgument( "Output(SavedVariance) of BatchNormOp should not be null.")); } // make sure Mean/MeanOut and Variance/VarianceOut share memory in Python PADDLE_ENFORCE_EQ(ctx->Inputs("Mean")[0], ctx->Outputs("MeanOut")[0], "Mean and MeanOut should share the same memory"); PADDLE_ENFORCE_EQ(ctx->Inputs("Variance")[0], ctx->Outputs("VarianceOut")[0], "Variance and VarianceOut should share the same memory"); const auto x_dims = ctx->GetInputDim("X"); const DataLayout data_layout = framework::StringToDataLayout( ctx->Attrs().Get("data_layout")); if (ctx->IsRuntime() && ctx->HasInput("MomentumTensor")) { auto mom = ctx->Inputs("MomentumTensor"); PADDLE_ENFORCE_EQ(mom.size(), 1, platform::errors::InvalidArgument( "Input(MomentumTensor) size must be 1")); } PADDLE_ENFORCE_GE( x_dims.size(), 2, platform::errors::InvalidArgument( "ShapeError: the dimension of input " "X must greater than or equal to 2. But received: the shape of input " "X = [%s], the dimension of input X =[%d]", x_dims, x_dims.size())); PADDLE_ENFORCE_LE( x_dims.size(), 5, platform::errors::InvalidArgument( "ShapeError: the dimension of input X " "must smaller than or equal to 5. But received: the shape of input X " "= [%s], the dimension of input X = [%d]", x_dims, x_dims.size())); const int64_t C = ((this->IsMKLDNNType() == true) || (data_layout == DataLayout::kNCHW) ? x_dims[1] : x_dims[x_dims.size() - 1]); auto scale_dim = ctx->GetInputDim("Scale"); auto bias_dim = ctx->GetInputDim("Bias"); PADDLE_ENFORCE_EQ(scale_dim.size(), 1UL, "ShapeError: the dimension of scale must equal to 1." "But received: the shape of scale is [%s], the dimension " "of scale is [%d]", scale_dim, scale_dim.size()); PADDLE_ENFORCE_EQ( bias_dim.size(), 1UL, "ShapeError: the dimension of bias must equal to 1." "But received: the shape of bias is [%s],the dimension of bias is [%d]", bias_dim, bias_dim.size()); bool check = true; if ((!ctx->IsRuntime()) && (framework::product(scale_dim) <= 0 || framework::product(bias_dim) <= 0)) { check = false; } if (check) { PADDLE_ENFORCE_EQ(scale_dim[0], C, "ShapeError: the shape of scale must equal to [%d]" "But received: the shape of scale is [%d]", C, scale_dim[0]); PADDLE_ENFORCE_EQ(bias_dim[0], C, "ShapeError: the shape of bias must equal to [%d]" "But received: the shape of bias is [%d]", C, bias_dim[0]); } ctx->SetOutputDim("Y", x_dims); ctx->SetOutputDim("MeanOut", {C}); ctx->SetOutputDim("VarianceOut", {C}); ctx->SetOutputDim("SavedMean", {C}); ctx->SetOutputDim("SavedVariance", {C}); ctx->ShareLoD("X", "Y"); } framework::OpKernelType BatchNormOp::GetExpectedKernelType( const framework::ExecutionContext &ctx) const { auto input_data_type = OperatorWithKernel::IndicateVarDataType(ctx, "X"); // 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 bn_param_type = framework::proto::VarType::FP32; if (input_data_type == framework::proto::VarType::FP64) { bn_param_type = framework::proto::VarType::FP64; } PADDLE_ENFORCE_EQ( bn_param_type, ctx.Input("Scale")->type(), platform::errors::InvalidArgument("Scale input should be of float type")); PADDLE_ENFORCE_EQ( bn_param_type, ctx.Input("Bias")->type(), platform::errors::InvalidArgument("Bias input should be of float type")); PADDLE_ENFORCE_EQ( bn_param_type, ctx.Input("Mean")->type(), platform::errors::InvalidArgument("Mean input should be of float type")); PADDLE_ENFORCE_EQ(bn_param_type, ctx.Input("Variance")->type(), platform::errors::InvalidArgument( "Variance input should be of float type")); // TODO(pzelazko-intel): enable MKLDNN layout when it's ready framework::LibraryType library = framework::LibraryType::kPlain; framework::DataLayout layout = framework::DataLayout::kAnyLayout; #ifdef PADDLE_WITH_MKLDNN if (library == framework::LibraryType::kPlain && platform::CanMKLDNNBeUsed(ctx)) { library = framework::LibraryType::kMKLDNN; layout = framework::DataLayout::kMKLDNN; } #endif return framework::OpKernelType(input_data_type, ctx.GetPlace(), layout, library); } framework::OpKernelType BatchNormOp::GetKernelTypeForVar( const std::string &var_name, const Tensor &tensor, const framework::OpKernelType &expected_kernel_type) const { #ifdef PADDLE_WITH_MKLDNN // Only input require reshaping, weights and // bias are having shape in NCHW order if ((var_name == "X") && (expected_kernel_type.data_layout_ == framework::DataLayout::kMKLDNN) && (tensor.layout() != framework::DataLayout::kMKLDNN)) { auto attrs = Attrs(); auto ar = paddle::framework::AttrReader(attrs); const std::string data_layout = ar.Get("data_layout"); auto dl = framework::StringToDataLayout(data_layout); // Some models may have intentionally set "AnyLayout" for pool // op. Treat this as NCHW (default data_format value) if (dl != framework::DataLayout::kAnyLayout) { return framework::OpKernelType(expected_kernel_type.data_type_, tensor.place(), dl); } } #endif return framework::OpKernelType(expected_kernel_type.data_type_, tensor.place(), tensor.layout()); } void BatchNormOpMaker::Make() { AddAttr("is_test", "(bool, default false) Set to true for inference only, false " "for training. Some layers may run faster when this is true.") .SetDefault(false); AddAttr("momentum", "").SetDefault(0.9); AddAttr("epsilon", "") .SetDefault(1e-5) .AddCustomChecker([](const float &epsilon) { PADDLE_ENFORCE_GE( epsilon, 0.0f, platform::errors::InvalidArgument( "'epsilon' should be greater or equal than 0.0.")); PADDLE_ENFORCE_LE(epsilon, 0.001f, platform::errors::InvalidArgument( "'epsilon' should be less or equal than 0.001.")); }); AddAttr("data_layout", "").SetDefault("NCHW"); AddInput("X", "The input tensor"); AddInput("Scale", "Scale is a 1-dimensional tensor of size C " "that is applied to the output"); AddInput("Bias", "Bias is a 1-dimensional tensor of size C " "that is applied to the output"); AddInput("Mean", "The global mean (for training) or " "estimated mean (for testing)"); AddInput("Variance", "The global variance (for training) " "or estimated Variance (for testing)"); AddInput("MomentumTensor", "(Tensor, optional) If provided, batch_norm will " "use this as momentum, this has a higher priority than " "attr(momentum), the shape of this tensor MUST BE [1].") .AsDispensable(); AddOutput("Y", "result after normalization"); AddOutput("MeanOut", "Share memory with Mean. " "Store the global mean when training"); AddOutput("VarianceOut", "Share memory with Variance. " "Store the global Variance when training"); AddOutput("SavedMean", "Mean of the current mini batch, " "will apply to output when training") .AsIntermediate(); AddOutput("SavedVariance", "Variance of the current mini batch, " "will apply to output when training") .AsIntermediate(); AddOutput("ReserveSpace", "Reserve GPU space for triggering the new semi-persistent " "NHWC kernel") .AsDispensable(); AddAttr("use_mkldnn", "(bool, default false) Only used in mkldnn kernel") .SetDefault(false); AddAttr("fuse_with_relu", "(bool, default false) Only used in mkldnn kernel") .SetDefault(false); AddAttr("use_global_stats", "(bool, default false) Whether to use global mean and " "variance. In inference or test mode, set use_global_stats " "to true or is_test true. the behavior is equivalent. " "In train mode, when setting use_global_stats True, the " "global mean and variance are also used during train time, " "the BN acts as scaling and shiffting.") .SetDefault(false); AddComment(R"DOC( Batch Normalization. Batch Norm has been implemented as discussed in the paper: https://arxiv.org/pdf/1502.03167.pdf Can be used as a normalizer function for conv2d and fully_connected operations. 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 class BatchNormKernel : public framework::OpKernel { public: void Compute(const framework::ExecutionContext &ctx) const override { const float epsilon = ctx.Attr("epsilon"); float momentum = ctx.Attr("momentum"); const bool is_test = ctx.Attr("is_test"); const bool use_global_stats = ctx.Attr("use_global_stats"); bool global_stats = is_test || use_global_stats; const std::string data_layout_str = ctx.Attr("data_layout"); const DataLayout data_layout = framework::StringToDataLayout(data_layout_str); const auto *x = ctx.Input("X"); const auto &x_dims = x->dims(); PADDLE_ENFORCE_GE(x_dims.size(), 2, platform::errors::InvalidArgument( "The Input X dim size should be larger than 1.")); PADDLE_ENFORCE_LE(x_dims.size(), 5, platform::errors::InvalidArgument( "The Input X dim size should be less than 6.")); const int N = x_dims[0]; const int C = (data_layout == DataLayout::kNCHW ? x_dims[1] : x_dims[x_dims.size() - 1]); const int sample_size = x->numel() / N / C; auto *y = ctx.Output("Y"); auto *mean_out = ctx.Output("MeanOut"); auto *variance_out = ctx.Output("VarianceOut"); auto *saved_mean = ctx.Output("SavedMean"); auto *saved_variance = ctx.Output("SavedVariance"); // alloc memory y->mutable_data(ctx.GetPlace()); mean_out->mutable_data(ctx.GetPlace()); variance_out->mutable_data(ctx.GetPlace()); saved_mean->mutable_data(ctx.GetPlace()); saved_variance->mutable_data(ctx.GetPlace()); if (!global_stats) { // saved_xx is use just in this batch of data EigenVectorArrayMap saved_mean_e( saved_mean->mutable_data(ctx.GetPlace()), C); EigenVectorArrayMap saved_variance_e( saved_variance->mutable_data(ctx.GetPlace()), C); saved_mean_e.setZero(); saved_variance_e.setZero(); EigenVectorArrayMap running_mean_arr( mean_out->mutable_data(ctx.GetPlace()), C); EigenVectorArrayMap running_var_arr( variance_out->mutable_data(ctx.GetPlace()), C); if ((N * sample_size) == 1) { // Only 1 element in normalization dimension, // we skip the batch norm calculation, let y = x. framework::TensorCopy(*x, ctx.GetPlace(), y); return; } switch (data_layout) { case DataLayout::kNCHW: { ConstEigenArrayMap x_arr(x->data(), sample_size, N * C); for (int nc = 0; nc < N * C; ++nc) { saved_mean_e(nc % C) += x_arr.col(nc).sum(); } saved_mean_e /= N * sample_size; for (int nc = 0; nc < N * C; ++nc) { saved_variance_e(nc % C) += (x_arr.col(nc) - saved_mean_e(nc % C)).matrix().squaredNorm(); } saved_variance_e /= N * sample_size; break; } case DataLayout::kNHWC: { ConstEigenArrayMap x_arr(x->data(), C, N * sample_size); for (int i = 0; i < N * sample_size; ++i) { saved_mean_e += x_arr.col(i); } saved_mean_e /= N * sample_size; for (int i = 0; i < N * sample_size; ++i) { saved_variance_e += (x_arr.col(i) - saved_mean_e) * (x_arr.col(i) - saved_mean_e); } saved_variance_e /= N * sample_size; break; } default: PADDLE_THROW("Unknown storage order: %s", data_layout_str); } // if MomentumTensor is set, use MomentumTensor value, momentum // is only used in this training branch if (ctx.HasInput("MomentumTensor")) { const auto *mom_tensor = ctx.Input("MomentumTensor"); momentum = mom_tensor->data()[0]; } running_mean_arr = running_mean_arr * momentum + saved_mean_e * (1. - momentum); running_var_arr = running_var_arr * momentum + saved_variance_e * (1. - momentum); } // use SavedMean and SavedVariance to do normalize Eigen::Array inv_std(C); if (global_stats) { ConstEigenVectorArrayMap var_arr( ctx.Input("Variance")->data(), C); inv_std = (var_arr + epsilon).sqrt().inverse(); } else { EigenVectorArrayMap saved_inv_std( ctx.Output("SavedVariance")->data(), C); // inverse SavedVariance first, gradient will use it too. saved_inv_std = (saved_inv_std + epsilon).inverse().sqrt(); inv_std = saved_inv_std; } ConstEigenVectorArrayMap mean_arr( global_stats ? ctx.Input("Mean")->data() : ctx.Output("SavedMean")->data(), C); // ((x - est_mean) * (inv_var) * scale + bias // formula transform ====> // (x * inv_var * scale) + (bias - est_mean * inv_var * scale) const auto *scale = ctx.Input("Scale"); const auto *bias = ctx.Input("Bias"); ConstEigenVectorArrayMap scale_arr(scale->data(), C); ConstEigenVectorArrayMap bias_arr(bias->data(), C); Eigen::Array new_scale = inv_std * scale_arr; Eigen::Array new_bias = bias_arr - mean_arr * inv_std * scale_arr; switch (data_layout) { case DataLayout::kNCHW: { EigenArrayMap y_arr(y->mutable_data(ctx.GetPlace()), sample_size, N * C); ConstEigenArrayMap x_arr(x->data(), sample_size, N * C); for (int nc = 0; nc < N * C; ++nc) { y_arr.col(nc) = x_arr.col(nc) * new_scale(nc % C) + new_bias(nc % C); } break; } case DataLayout::kNHWC: { EigenArrayMap(y->mutable_data(ctx.GetPlace()), C, N * sample_size) = (ConstEigenArrayMap(x->data(), C, N * sample_size).colwise() * new_scale) .colwise() + new_bias; break; } default: PADDLE_THROW("Unknown storage order: %d", data_layout); } } }; void BatchNormGradOp::InferShape(framework::InferShapeContext *ctx) const { // check input PADDLE_ENFORCE_EQ( ctx->HasInput("Scale"), true, platform::errors::InvalidArgument("Input(scale) should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasInput(framework::GradVarName("Y")), true, platform::errors::InvalidArgument("Input(Y@GRAD) should not be null.")); PADDLE_ENFORCE_EQ(ctx->HasInput("SavedMean"), true, platform::errors::InvalidArgument( "Input(SavedMean) should not be null.")); PADDLE_ENFORCE_EQ(ctx->HasInput("SavedVariance"), true, platform::errors::InvalidArgument( "Input(SavedVariance) should not be null")); // check output PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("X")), ""); const bool has_scale_grad = ctx->HasOutput(framework::GradVarName("Scale")); const bool has_bias_grad = ctx->HasOutput(framework::GradVarName("Bias")); PADDLE_ENFORCE_EQ((has_scale_grad == has_bias_grad), true, 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]", has_scale_grad, has_bias_grad)); const bool use_global_stats = ctx->Attrs().Get("use_global_stats"); if (use_global_stats) { PADDLE_ENFORCE_EQ( !ctx->Attrs().Get("use_mkldnn"), true, platform::errors::InvalidArgument( "Using global stats during training is not supported " "in gradient op kernel of batch_norm_mkldnn_op now.")); } // batch_norm_grad with inplace takes Y as input, without inplace // takes X as input. HasInput will throw exception in compile time, // so only infer shape in run time here. if (ctx->IsRuntime()) { PADDLE_ENFORCE_EQ(ctx->HasInput("X") || ctx->HasInput("Y"), true, platform::errors::InvalidArgument( "Input(X) and Input(Y) should not be all null.")); auto input_name = "Y"; if (ctx->HasInput("X")) input_name = "X"; const auto x_dims = ctx->GetInputDim(input_name); const DataLayout data_layout = framework::StringToDataLayout( ctx->Attrs().Get("data_layout")); const int C = ((this->IsMKLDNNType() == true) || (data_layout == DataLayout::kNCHW) ? x_dims[1] : x_dims[x_dims.size() - 1]); ctx->SetOutputDim(framework::GradVarName("X"), x_dims); // has_scale_grad == has_bias_grad, judge has_scale_grad is enough if (has_scale_grad) { ctx->SetOutputDim(framework::GradVarName("Scale"), {C}); ctx->SetOutputDim(framework::GradVarName("Bias"), {C}); } } } framework::OpKernelType BatchNormGradOp::GetExpectedKernelType( const framework::ExecutionContext &ctx) const { const auto *var = ctx.InputVar(framework::GradVarName("Y")); if (var == nullptr) { PADDLE_THROW( platform::errors::InvalidArgument("can't find gradient variable of Y")); } const Tensor *t = nullptr; if (var->IsType()) { t = &var->Get(); } else if (var->IsType()) { t = &var->Get(); } if (t == nullptr) { PADDLE_THROW( platform::errors::InvalidArgument("gradient variable of Y is empty")); } // TODO(pzelazko-intel): enable MKLDNN layout when it's ready framework::LibraryType library = framework::LibraryType::kPlain; framework::DataLayout layout = framework::DataLayout::kAnyLayout; #ifdef PADDLE_WITH_MKLDNN if (library == framework::LibraryType::kPlain && platform::CanMKLDNNBeUsed(ctx)) { library = framework::LibraryType::kMKLDNN; layout = framework::DataLayout::kMKLDNN; } #endif return framework::OpKernelType( OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.GetPlace(), layout, library); } framework::OpKernelType BatchNormGradOp::GetKernelTypeForVar( const std::string &var_name, const Tensor &tensor, const framework::OpKernelType &expected_kernel_type) const { #ifdef PADDLE_WITH_MKLDNN // Only input require reshaping, weights and // bias are having shape in NCHW order if (((var_name == "X") || (var_name == framework::GradVarName("Y"))) && (expected_kernel_type.data_layout_ == framework::DataLayout::kMKLDNN) && (tensor.layout() != framework::DataLayout::kMKLDNN)) { auto attrs = Attrs(); auto ar = paddle::framework::AttrReader(attrs); const std::string data_layout = ar.Get("data_layout"); auto dl = framework::StringToDataLayout(data_layout); // Some models may have intentionally set "AnyLayout" for pool // op. Treat this as NCHW (default data_format value) if (dl != framework::DataLayout::kAnyLayout) { return framework::OpKernelType(expected_kernel_type.data_type_, tensor.place(), dl); } } #endif return framework::OpKernelType(expected_kernel_type.data_type_, tensor.place(), tensor.layout()); } template class BatchNormGradKernel : public framework::OpKernel { public: void Compute(const framework::ExecutionContext &ctx) const override { const auto *d_y = ctx.Input(framework::GradVarName("Y")); const auto *scale = ctx.Input("Scale"); const auto *bias = ctx.Input("Bias"); const auto *saved_mean = ctx.Input("SavedMean"); // SavedVariance have been reverted in forward operator const auto *saved_inv_variance = ctx.Input("SavedVariance"); const std::string data_layout_str = ctx.Attr("data_layout"); const bool use_global_stats = ctx.Attr("use_global_stats"); const bool is_test = ctx.Attr("is_test"); const float epsilon = ctx.Attr("epsilon"); const DataLayout data_layout = framework::StringToDataLayout(data_layout_str); auto *d_x = ctx.Output(framework::GradVarName("X")); auto *d_scale = ctx.Output(framework::GradVarName("Scale")); auto *d_bias = ctx.Output(framework::GradVarName("Bias")); // batch_norm with inplace as false will take X as grad input, which // is same as cuDNN batch_norm backward calculation, batch_norm // with inplace as true only take Y as input and X should be calculate // by inverse operation of batch_norm on Y const Tensor *x; bool is_inplace; if (ctx.HasInput("Y")) { x = ctx.Input("Y"); is_inplace = true; PADDLE_ENFORCE_EQ(d_x, d_y, platform::errors::InvalidArgument( "X@GRAD and Y@GRAD not inplace in inplace mode")); } else { x = ctx.Input("X"); is_inplace = false; PADDLE_ENFORCE_NE(d_x, d_y, platform::errors::InvalidArgument( "X@GRAD and Y@GRAD inplaced in non-inplace mode")); } PADDLE_ENFORCE_EQ( is_test, false, platform::errors::InvalidArgument( "`is_test = True` CANNOT be used in train program. If " "you want to use global status in pre_train model, " "please set `use_global_stats = True`")); // Get the size for each dimension. // NCHW [batch_size, in_channels, in_height, in_width] const auto &x_dims = x->dims(); PADDLE_ENFORCE_GE(x_dims.size(), 2, platform::errors::InvalidArgument( "The Input X dim size should be larger than 1.")); PADDLE_ENFORCE_LE(x_dims.size(), 5, platform::errors::InvalidArgument( "The Input X dim size should be less than 6.")); const int N = x_dims[0]; const int C = (data_layout == DataLayout::kNCHW ? x_dims[1] : x_dims[x_dims.size() - 1]); const int sample_size = x->numel() / N / C; // init output d_x->mutable_data(ctx.GetPlace()); const T *mean_data = saved_mean->data(); const T *inv_var_data = saved_inv_variance->data(); Tensor inv_var_tensor; if (use_global_stats) { const auto *running_mean = ctx.Input("Mean"); const auto *running_variance = ctx.Input("Variance"); mean_data = running_mean->data(); inv_var_tensor.Resize({C}); T *running_inv_var_data = inv_var_tensor.mutable_data(ctx.GetPlace()); EigenVectorArrayMap inv_var_tmp(running_inv_var_data, C); ConstEigenVectorArrayMap var_arr(running_variance->data(), C); inv_var_tmp = (var_arr + epsilon).sqrt().inverse(); inv_var_data = running_inv_var_data; } ConstEigenVectorArrayMap scale_arr(scale->data(), C); ConstEigenVectorArrayMap bias_arr(bias->data(), C); ConstEigenVectorArrayMap mean_arr(mean_data, C); ConstEigenVectorArrayMap inv_var_arr(inv_var_data, C); T *d_bias_data = nullptr; T *d_scale_data = nullptr; if (d_scale && d_bias) { d_scale->mutable_data(ctx.GetPlace()); d_bias->mutable_data(ctx.GetPlace()); d_bias_data = d_bias->mutable_data(ctx.GetPlace()); d_scale_data = d_scale->mutable_data(ctx.GetPlace()); } // d_bias = np.sum(d_y, axis=0) // d_scale = np.sum((X - mean) / inv_std * dy, axis=0) // d_x = (1. / N) * scale * inv_var * (N * d_y - np.sum(d_y, axis=0) // - (X - mean) * inv_var * inv_var * np.sum(d_y * (X - mean), axis=0)) EigenVectorArrayMap d_bias_arr(d_bias_data, C); EigenVectorArrayMap d_scale_arr(d_scale_data, C); if (d_scale && d_bias) { d_bias_arr.setZero(); d_scale_arr.setZero(); } if ((N * sample_size) == 1 && !use_global_stats) { framework::TensorCopy(*d_y, ctx.GetPlace(), d_x); return; } int scale_coefff = use_global_stats ? 1 : N * sample_size; const auto scale_inv_var_nhw = scale_arr * inv_var_arr / scale_coefff; Tensor dy_sum; dy_sum.Resize({C}); dy_sum.mutable_data(ctx.GetPlace()); EigenVectorArrayMap dy_sum_arr(dy_sum.mutable_data(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(ctx.GetPlace()); EigenVectorArrayMap dy_mul_x_sub_mean_mul_invstd_sum_arr( dy_mul_x_sub_mean_mul_invstd_sum.mutable_data(ctx.GetPlace()), C); dy_sum_arr.setZero(); dy_mul_x_sub_mean_mul_invstd_sum_arr.setZero(); // inplace calculation // Y: ((x - est_mean) * (inv_var) * scale + bias // formula transform ====> // (x * inv_var * scale) + (bias - est_mean * inv_var * scale) // X: (y - bias) / scale / (inv_var) + est_mean // formula transform ====> // (y - bias) / (scale * inv_var) + est_mean switch (data_layout) { case DataLayout::kNCHW: { if (is_inplace) { auto px = *x; EigenArrayMap x_data(px.mutable_data(ctx.GetPlace()), sample_size, N * C); ConstEigenArrayMap y_data(x->data(), sample_size, N * C); for (int nc = 0; nc < N * C; ++nc) { x_data.col(nc) = (y_data.col(nc) - bias_arr(nc % C)) / scale_inv_var_nhw(nc % C) / scale_coefff + mean_arr(nc % C); } } ConstEigenArrayMap x_arr(x->data(), sample_size, N * C); ConstEigenArrayMap d_y_arr(d_y->data(), sample_size, N * C); EigenArrayMap d_x_arr(d_x->mutable_data(ctx.GetPlace()), sample_size, N * C); for (int nc = 0; nc < N * C; ++nc) { int c = nc % C; dy_sum_arr(c) += d_y_arr.col(nc).sum(); dy_mul_x_sub_mean_mul_invstd_sum_arr(c) += ((x_arr.col(nc) - mean_arr(c)) * inv_var_arr(c) * d_y_arr.col(nc)) .sum(); } if (d_scale && d_bias) { d_bias_arr = dy_sum_arr; d_scale_arr = dy_mul_x_sub_mean_mul_invstd_sum_arr; } if (!use_global_stats) { for (int nc = 0; nc < N * C; ++nc) { int c = nc % C; d_x_arr.col(nc) = scale_inv_var_nhw(c) * (d_y_arr.col(nc) * N * sample_size - dy_sum_arr(c) - (x_arr.col(nc) - mean_arr[c]) * dy_mul_x_sub_mean_mul_invstd_sum_arr(c) * inv_var_arr(c)); } } else { for (int nc = 0; nc < N * C; ++nc) { int c = nc % C; d_x_arr.col(nc) = scale_inv_var_nhw(c) * d_y_arr.col(nc); } } break; } case DataLayout::kNHWC: { if (is_inplace) { auto px = *x; EigenArrayMap x_data(px.mutable_data(ctx.GetPlace()), C, N * sample_size); ConstEigenArrayMap y_data(x->data(), C, N * sample_size); for (int nhw = 0; nhw < N * sample_size; nhw++) { x_data.col(nhw) = (y_data.col(nhw) - bias_arr) / scale_inv_var_nhw / scale_coefff + mean_arr; } } ConstEigenArrayMap x_arr(x->data(), C, N * sample_size); ConstEigenArrayMap d_y_arr(d_y->data(), C, N * sample_size); EigenArrayMap d_x_arr(d_x->mutable_data(ctx.GetPlace()), C, N * sample_size); for (int nhw = 0; nhw < N * sample_size; ++nhw) { dy_sum_arr += d_y_arr.col(nhw); dy_mul_x_sub_mean_mul_invstd_sum_arr += (x_arr.col(nhw) - mean_arr) * inv_var_arr * d_y_arr.col(nhw); } if (d_scale && d_bias) { d_bias_arr = dy_sum_arr; d_scale_arr = dy_mul_x_sub_mean_mul_invstd_sum_arr; } if (!use_global_stats) { for (int nhw = 0; nhw < N * sample_size; ++nhw) { d_x_arr.col(nhw) = scale_inv_var_nhw * (d_y_arr.col(nhw) * N * sample_size - dy_sum_arr - (x_arr.col(nhw) - mean_arr) * dy_mul_x_sub_mean_mul_invstd_sum_arr * inv_var_arr); } } else { for (int nhw = 0; nhw < N * sample_size; ++nhw) { d_x_arr.col(nhw) = scale_inv_var_nhw * d_y_arr.col(nhw); } } break; } default: PADDLE_THROW("Unknown storage order: %s", data_layout_str); } } }; template void BatchNormGradMaker::Apply(GradOpPtr op) const { op->SetType(this->ForwardOpType() + "_grad"); op->SetInput("X", this->Input("X")); op->SetInput(framework::GradVarName("Y"), this->OutputGrad("Y")); op->SetInput("Scale", this->Input("Scale")); op->SetInput("Bias", this->Input("Bias")); op->SetInput("SavedMean", this->Output("SavedMean")); op->SetInput("SavedVariance", this->Output("SavedVariance")); if (this->HasOutput("ReserveSpace")) { op->SetInput("ReserveSpace", this->Output("ReserveSpace")); } // used when setting use_global_stats True during training if (boost::get(this->GetAttr("use_global_stats"))) { op->SetInput("Mean", this->Output("MeanOut")); op->SetInput("Variance", this->Output("VarianceOut")); } op->SetAttrMap(this->Attrs()); op->SetOutput(framework::GradVarName("X"), this->InputGrad("X")); op->SetOutput(framework::GradVarName("Scale"), this->InputGrad("Scale")); op->SetOutput(framework::GradVarName("Bias"), this->InputGrad("Bias")); } } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(batch_norm, ops::BatchNormOp, ops::BatchNormOpMaker, ops::BatchNormOpInferVarType, ops::BatchNormGradMaker, ops::BatchNormGradMaker); REGISTER_OPERATOR(batch_norm_grad, ops::BatchNormGradOp); REGISTER_OP_CPU_KERNEL( batch_norm, ops::BatchNormKernel, ops::BatchNormKernel); REGISTER_OP_CPU_KERNEL( batch_norm_grad, ops::BatchNormGradKernel, ops::BatchNormGradKernel);