batch_norm_op_mlu.cc 13.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2022 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. */

Q
qipengh 已提交
15
#include "paddle/fluid/operators/amp/fp16_type_traits.h"
16
#include "paddle/fluid/operators/batch_norm_op.h"
17 18 19 20 21 22 23
#include "paddle/fluid/operators/mlu/mlu_baseop.h"

namespace paddle {
namespace operators {

template <typename T>
class MLUBatchNormOpKernel : public framework::OpKernel<T> {
Q
qipengh 已提交
24 25
  using MPDType = typename details::MPTypeTrait<T>::Type;

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
    const auto &place = ctx.GetPlace();
    const float epsilon = ctx.Attr<float>("epsilon");
    float momentum = ctx.Attr<float>("momentum");
    const bool is_test = ctx.Attr<bool>("is_test");
    const bool use_global_stats = ctx.Attr<bool>("use_global_stats");
    const bool trainable_stats = ctx.Attr<bool>("trainable_statistics");
    bool test_mode = is_test && (!trainable_stats);

    bool global_stats = test_mode || use_global_stats;

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

    const auto *x = ctx.Input<Tensor>("X");
    const auto &x_dims = x->dims();
    PADDLE_ENFORCE_GE(
44 45
        x_dims.size(),
        2,
46 47 48 49 50
        platform::errors::InvalidArgument(
            "The size of input X's dimensions should be larger than 1."
            "But received: the size of input X's dimensions is [%d]",
            x_dims.size()));
    PADDLE_ENFORCE_LE(
51 52
        x_dims.size(),
        5,
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
        platform::errors::InvalidArgument(
            "The size of input X's dimensions should be less than 6."
            "But received: the size of input X's dimensions is [%d]",
            x_dims.size()));
    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;

    const auto *running_mean = ctx.Input<Tensor>("Mean");
    const auto *running_var = ctx.Input<Tensor>("Variance");
    const auto *scale = ctx.Input<Tensor>("Scale");
    const auto *bias = ctx.Input<Tensor>("Bias");

    auto *y = ctx.Output<Tensor>("Y");
    auto *mean_out = ctx.Output<Tensor>("MeanOut");
    auto *variance_out = ctx.Output<Tensor>("VarianceOut");
    auto *saved_mean = ctx.Output<Tensor>("SavedMean");
    auto *saved_variance = ctx.Output<Tensor>("SavedVariance");

    // alloc memory
    y->mutable_data<T>(place);
Q
qipengh 已提交
76 77 78 79
    mean_out->mutable_data<MPDType>(place);
    variance_out->mutable_data<MPDType>(place);
    saved_mean->mutable_data<MPDType>(place);
    saved_variance->mutable_data<MPDType>(place);
80 81 82 83 84

    Tensor transformed_x;
    Tensor transformed_y;
    const int transformed_dim_size = 4;
    const int transformed_shape[transformed_dim_size] = {N, sample_size, 1, C};
85 86 87 88
    MLUCnnlTensorDesc transformed_desc(transformed_dim_size,
                                       transformed_shape,
                                       ToCnnlDataType<T>(),
                                       CNNL_LAYOUT_NHWC);
89 90 91 92 93 94 95 96 97 98 99 100 101
    MLUCnnlTensorDesc others_input_desc(*scale);
    // input dimension is 2 and the format is NCHW. The input can be regarded as
    // NHWC format. Don't need to transpose.
    bool need_transpose =
        (data_layout == DataLayout::kNCHW && x_dims.size() != 2);
    if (need_transpose) {
      auto &dev_ctx = ctx.template device_context<MLUDeviceContext>();
      transformed_x = ctx.AllocateTmpTensor<T, MLUDeviceContext>(
          framework::DDim(transformed_shape, transformed_dim_size), dev_ctx);
      transformed_y = ctx.AllocateTmpTensor<T, MLUDeviceContext>(
          framework::DDim(transformed_shape, transformed_dim_size), dev_ctx);

      const int x_reshaped[] = {N, C, sample_size, 1};
102 103
      MLUCnnlTensorDesc x_reshaped_desc(
          transformed_dim_size, x_reshaped, ToCnnlDataType<T>());
104
      const std::vector<int> perm = {0, 2, 3, 1};
105 106 107 108 109 110
      MLUCnnl::Transpose(ctx,
                         perm,
                         transformed_dim_size,
                         x_reshaped_desc.get(),
                         GetBasePtr(x),
                         transformed_desc.get(),
111 112 113 114 115 116 117 118 119
                         GetBasePtr(&transformed_x));
    } else {
      transformed_x = *x;
      transformed_y = *y;
    }

    if (ctx.HasInput("MomentumTensor")) {
      const auto *mom_tensor = ctx.Input<Tensor>("MomentumTensor");
      Tensor mom_cpu;
Q
qipengh 已提交
120
      framework::TensorCopySync(*mom_tensor, platform::CPUPlace(), &mom_cpu);
121 122 123
      momentum = mom_cpu.data<float>()[0];
    }

124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
    MLUCnnl::FusedBatchNorm(ctx,
                            !global_stats,
                            transformed_desc.get(),
                            GetBasePtr(&transformed_x),
                            others_input_desc.get(),
                            GetBasePtr(scale),
                            GetBasePtr(bias),
                            GetBasePtr(running_mean),
                            GetBasePtr(running_var),
                            epsilon,
                            momentum,
                            transformed_desc.get(),
                            GetBasePtr(&transformed_y),
                            GetBasePtr(mean_out),
                            GetBasePtr(variance_out),
                            GetBasePtr(saved_mean),
                            GetBasePtr(saved_variance));
141 142 143

    if (need_transpose) {
      const int y_reshaped[] = {N, C, sample_size, 1};
144 145
      MLUCnnlTensorDesc y_reshaped_desc(
          transformed_dim_size, y_reshaped, ToCnnlDataType<T>());
146
      const std::vector<int> perm = {0, 3, 1, 2};
147 148 149 150 151 152 153
      MLUCnnl::Transpose(ctx,
                         perm,
                         transformed_y.dims().size(),
                         transformed_desc.get(),
                         GetBasePtr(&transformed_y),
                         y_reshaped_desc.get(),
                         GetBasePtr(y));
154 155 156 157 158 159
    }
  }
};

template <typename T>
class MLUBatchNormGradOpKernel : public framework::OpKernel<T> {
Q
qipengh 已提交
160 161
  using MPDType = typename details::MPTypeTrait<T>::Type;

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
    const auto *x = ctx.Input<Tensor>("X");
    const auto *d_y = ctx.Input<Tensor>(framework::GradVarName("Y"));
    const auto *scale = ctx.Input<Tensor>("Scale");
    const auto *bias = ctx.Input<Tensor>("Bias");
    const auto *saved_mean = ctx.Input<Tensor>("SavedMean");
    // SavedVariance have been reverted in forward operator
    const auto *saved_inv_variance = ctx.Input<Tensor>("SavedVariance");
    const std::string data_layout_str = ctx.Attr<std::string>("data_layout");
    bool use_global_stats = ctx.Attr<bool>("use_global_stats");
    const bool is_test = ctx.Attr<bool>("is_test");
    const float epsilon = ctx.Attr<float>("epsilon");
    DataLayout data_layout = framework::StringToDataLayout(data_layout_str);

    auto *d_x = ctx.Output<Tensor>(framework::GradVarName("X"));
    auto *d_scale = ctx.Output<Tensor>(framework::GradVarName("Scale"));
    auto *d_bias = ctx.Output<Tensor>(framework::GradVarName("Bias"));

    auto &dev_ctx = ctx.template device_context<MLUDeviceContext>();
    auto d_x_tmp =
        ctx.AllocateTmpTensor<T, MLUDeviceContext>(x->dims(), dev_ctx);
Q
qipengh 已提交
184 185
    auto scale_grad_tmp = ctx.AllocateTmpTensor<MPDType, MLUDeviceContext>(
        scale->dims(), dev_ctx);
186
    auto bias_grad_tmp =
Q
qipengh 已提交
187
        ctx.AllocateTmpTensor<MPDType, MLUDeviceContext>(bias->dims(), dev_ctx);
188 189 190 191 192 193 194 195 196 197 198 199 200

    if (d_x == nullptr) {
      d_x = &d_x_tmp;
    }
    if (d_scale == nullptr) {
      d_scale = &scale_grad_tmp;
    }
    if (d_bias == nullptr) {
      d_bias = &bias_grad_tmp;
    }

    const auto &place = ctx.GetPlace();
    d_x->mutable_data<T>(place);
Q
qipengh 已提交
201 202
    d_scale->mutable_data<MPDType>(place);
    d_bias->mutable_data<MPDType>(place);
203 204 205 206 207

    use_global_stats = is_test || use_global_stats;

    const auto &x_dims = x->dims();
    PADDLE_ENFORCE_GE(
208 209
        x_dims.size(),
        2,
210 211 212 213 214
        platform::errors::InvalidArgument(
            "The size of input X's dimensions should be larger than 1."
            "But received: the size of input X's dimensions is [%d]",
            x_dims.size()));
    PADDLE_ENFORCE_LE(
215 216
        x_dims.size(),
        5,
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
        platform::errors::InvalidArgument(
            "The size of input X's dimensions should be less than 6."
            "But received: the size of input X's dimensions is [%d]",
            x_dims.size()));
    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;

    Tensor transformed_d_y;
    Tensor transformed_x;
    Tensor transformed_d_x;
    const int transformed_dim_size = 4;
    const int transformed_shape[transformed_dim_size] = {N, sample_size, 1, C};

233 234 235 236
    MLUCnnlTensorDesc transformed_desc(transformed_dim_size,
                                       transformed_shape,
                                       ToCnnlDataType<T>(),
                                       CNNL_LAYOUT_NHWC);
237 238 239 240 241 242 243 244 245 246 247 248
    MLUCnnlTensorDesc others_input_desc(*scale);

    bool need_transpose =
        (data_layout == DataLayout::kNCHW && x_dims.size() != 2);
    if (need_transpose) {
      transformed_d_y = ctx.AllocateTmpTensor<T, MLUDeviceContext>(
          framework::DDim(transformed_shape, transformed_dim_size), dev_ctx);
      transformed_x = ctx.AllocateTmpTensor<T, MLUDeviceContext>(
          framework::DDim(transformed_shape, transformed_dim_size), dev_ctx);
      transformed_d_x = ctx.AllocateTmpTensor<T, MLUDeviceContext>(
          framework::DDim(transformed_shape, transformed_dim_size), dev_ctx);
      const int org_reshaped[] = {N, C, sample_size, 1};
249 250
      MLUCnnlTensorDesc org_reshaped_desc(
          transformed_dim_size, org_reshaped, ToCnnlDataType<T>());
251
      const std::vector<int> perm = {0, 2, 3, 1};
252 253 254 255 256 257 258 259 260 261 262 263 264 265
      MLUCnnl::Transpose(ctx,
                         perm,
                         transformed_dim_size,
                         org_reshaped_desc.get(),
                         GetBasePtr(d_y),
                         transformed_desc.get(),
                         GetBasePtr(&transformed_d_y));
      MLUCnnl::Transpose(ctx,
                         perm,
                         transformed_dim_size,
                         org_reshaped_desc.get(),
                         GetBasePtr(x),
                         transformed_desc.get(),
                         GetBasePtr(&transformed_x));
266 267 268 269 270 271 272 273 274
    } else {
      transformed_d_y = *d_y;
      transformed_x = *x;
      transformed_d_x = *d_x;
    }

    if (use_global_stats) {
      const auto *running_mean = ctx.Input<Tensor>("Mean");
      const auto *running_variance = ctx.Input<Tensor>("Variance");
275
      MLUCnnl::FusedBatchNormGrad(ctx,
276
                                  false /*is_training*/,
277 278 279 280 281 282 283 284 285 286 287 288 289
                                  transformed_desc.get(),
                                  GetBasePtr(&transformed_d_y),
                                  transformed_desc.get(),
                                  GetBasePtr(&transformed_x),
                                  others_input_desc.get(),
                                  GetBasePtr(scale),
                                  GetBasePtr(running_mean),
                                  GetBasePtr(running_variance),
                                  epsilon,
                                  transformed_desc.get(),
                                  GetBasePtr(&transformed_d_x),
                                  GetBasePtr(d_scale),
                                  GetBasePtr(d_bias));
290
    } else {
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
      MLUCnnl::FusedBatchNormGrad(ctx,
                                  true /*is_training*/,
                                  transformed_desc.get(),
                                  GetBasePtr(&transformed_d_y),
                                  transformed_desc.get(),
                                  GetBasePtr(&transformed_x),
                                  others_input_desc.get(),
                                  GetBasePtr(scale),
                                  GetBasePtr(saved_mean),
                                  GetBasePtr(saved_inv_variance),
                                  epsilon,
                                  transformed_desc.get(),
                                  GetBasePtr(&transformed_d_x),
                                  GetBasePtr(d_scale),
                                  GetBasePtr(d_bias));
306 307 308 309
    }

    if (need_transpose) {
      const int d_x_reshaped[] = {N, C, sample_size, 1};
310 311
      MLUCnnlTensorDesc d_x_reshaped_desc(
          transformed_dim_size, d_x_reshaped, ToCnnlDataType<T>());
312
      const std::vector<int> perm = {0, 3, 1, 2};
313 314 315 316 317 318 319
      MLUCnnl::Transpose(ctx,
                         perm,
                         transformed_dim_size,
                         transformed_desc.get(),
                         GetBasePtr(&transformed_d_x),
                         d_x_reshaped_desc.get(),
                         GetBasePtr(d_x));
320 321 322 323 324 325 326 327 328
    }
  }
};
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
namespace plat = paddle::platform;

329 330
REGISTER_OP_MLU_KERNEL(batch_norm,
                       ops::MLUBatchNormOpKernel<float>,
331
                       ops::MLUBatchNormOpKernel<plat::float16>);
332 333
REGISTER_OP_MLU_KERNEL(batch_norm_grad,
                       ops::MLUBatchNormGradOpKernel<float>,
334
                       ops::MLUBatchNormGradOpKernel<plat::float16>);