inplace_abn_op.cu 8.3 KB
Newer Older
K
Kaipeng Deng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "paddle/fluid/operators/inplace_abn_op.h"
16
#include "paddle/fluid/operators/batch_norm_op.h"
H
hong 已提交
17 18
#include "paddle/phi/kernels/batch_norm_grad_kernel.h"
#include "paddle/phi/kernels/batch_norm_kernel.h"
19 20 21
#include "paddle/phi/kernels/gpu/sync_batch_norm_utils.h"
#include "paddle/phi/kernels/sync_batch_norm_grad_kernel.h"
#include "paddle/phi/kernels/sync_batch_norm_kernel.h"
K
Kaipeng Deng 已提交
22 23 24 25 26

namespace paddle {
namespace operators {

template <typename DeviceContext, typename T>
27
class InplaceABNKernel : public framework::OpKernel<T> {
K
Kaipeng Deng 已提交
28 29
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
30 31
    auto* y = ctx.Output<phi::DenseTensor>("Y");
    auto* x = ctx.Input<phi::DenseTensor>("X");
32 33
    PADDLE_ENFORCE_EQ(x,
                      y,
34 35
                      platform::errors::InvalidArgument(
                          "X and Y not inplaced in inplace mode"));
K
Kaipeng Deng 已提交
36 37 38 39
    auto activation =
        GetInplaceABNActivationType(ctx.Attr<std::string>("activation"));
    auto& place = *ctx.template device_context<DeviceContext>().eigen_device();

40 41 42 43
    auto* scale = ctx.Input<phi::DenseTensor>("Scale");
    auto* bias = ctx.Input<phi::DenseTensor>("Bias");
    auto* mean = ctx.Input<phi::DenseTensor>("Mean");
    auto* variance = ctx.Input<phi::DenseTensor>("Variance");
44 45 46 47 48 49 50 51 52

    auto momentum = ctx.Attr<float>("momentum");
    auto epsilon = ctx.Attr<float>("epsilon");
    auto data_layout = ctx.Attr<std::string>("data_layout");
    auto is_test = ctx.Attr<bool>("is_test");
    auto use_global_stats = ctx.Attr<bool>("use_global_stats");
    auto trainable_statistics = ctx.Attr<bool>("trainable_statistics");
    auto fuse_with_relu = ctx.Attr<bool>("fuse_with_relu");

53 54 55 56 57
    auto* mean_out = ctx.Output<phi::DenseTensor>("MeanOut");
    auto* variance_out = ctx.Output<phi::DenseTensor>("VarianceOut");
    auto* saved_mean = ctx.Output<phi::DenseTensor>("SavedMean");
    auto* saved_variance = ctx.Output<phi::DenseTensor>("SavedVariance");
    auto* reserve_space = ctx.Output<phi::DenseTensor>("ReserveSpace");
58

K
Kaipeng Deng 已提交
59
    if (ctx.Attr<bool>("use_sync_bn")) {
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
      auto& dev_ctx = ctx.device_context<DeviceContext>();
      phi::SyncBatchNormKernel<T>(
          static_cast<const typename framework::ConvertToPhiContext<
              DeviceContext>::TYPE&>(dev_ctx),
          *x,
          *scale,
          *bias,
          *mean,
          *variance,
          momentum,
          epsilon,
          data_layout,
          is_test,
          use_global_stats,
          trainable_statistics,
          fuse_with_relu,
          y,
          mean_out,
          variance_out,
          saved_mean,
          saved_variance,
          reserve_space);
K
Kaipeng Deng 已提交
82
    } else {
H
hong 已提交
83 84 85 86
      auto& dev_ctx = ctx.device_context<DeviceContext>();
      phi::BatchNormKernel<T>(
          static_cast<const typename framework::ConvertToPhiContext<
              DeviceContext>::TYPE&>(dev_ctx),
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
          *x,
          *scale,
          *bias,
          *mean,
          *variance,
          momentum,
          epsilon,
          data_layout,
          is_test,
          use_global_stats,
          trainable_statistics,
          fuse_with_relu,
          y,
          mean_out,
          variance_out,
          saved_mean,
          saved_variance,
          reserve_space);
K
Kaipeng Deng 已提交
105 106 107 108 109 110 111 112 113 114 115
    }

    auto cur_y = EigenVector<T>::Flatten(*y);
    InplaceABNActivation<DeviceContext, T> functor;
    functor.Compute(ctx, activation, place, cur_y, cur_y);
  }
};

// Deriving the Gradient for the Backward Pass of Batch Normalization
// https://kevinzakka.github.io/2016/09/14/batch_normalization/
template <typename DeviceContext, typename T>
116
class InplaceABNGradKernel : public framework::OpKernel<T> {
K
Kaipeng Deng 已提交
117 118
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
119 120 121
    const auto* y = ctx.Input<phi::DenseTensor>("Y");
    auto* d_y = ctx.Input<phi::DenseTensor>(framework::GradVarName("Y"));
    auto* d_x = ctx.Output<phi::DenseTensor>(framework::GradVarName("X"));
122 123
    PADDLE_ENFORCE_EQ(d_x,
                      d_y,
K
Kaipeng Deng 已提交
124 125 126 127 128 129 130 131 132 133 134 135 136 137
                      platform::errors::InvalidArgument(
                          "X@GRAD and Y@GRAD not inplaced in inplace mode"));
    auto& place = *ctx.template device_context<DeviceContext>().eigen_device();
    auto activation =
        GetInplaceABNActivationType(ctx.Attr<std::string>("activation"));

    auto py = *y;
    auto pd_y = *d_y;
    auto cur_y = EigenVector<T>::Flatten(py);
    auto cur_dy = EigenVector<T>::Flatten(pd_y);

    InplaceABNActivation<DeviceContext, T> functor;
    functor.GradCompute(ctx, activation, place, cur_y, cur_y, cur_dy, cur_dy);

138 139 140 141
    auto* scale = ctx.Input<phi::DenseTensor>("Scale");
    auto* bias = ctx.Input<phi::DenseTensor>("Bias");
    auto* saved_mean = ctx.Input<phi::DenseTensor>("SavedMean");
    auto* saved_variance = ctx.Input<phi::DenseTensor>("SavedVariance");
142 143 144 145 146 147 148 149 150

    auto momentum = ctx.Attr<float>("momentum");
    auto epsilon = ctx.Attr<float>("epsilon");
    auto data_layout = ctx.Attr<std::string>("data_layout");
    auto is_test = ctx.Attr<bool>("is_test");
    auto use_global_stats = ctx.Attr<bool>("use_global_stats");
    auto trainable_statistics = ctx.Attr<bool>("trainable_statistics");
    auto fuse_with_relu = ctx.Attr<bool>("fuse_with_relu");

151 152 153 154
    auto* scale_grad =
        ctx.Output<phi::DenseTensor>(framework::GradVarName("Scale"));
    auto* bias_grad =
        ctx.Output<phi::DenseTensor>(framework::GradVarName("Bias"));
155

156 157 158
    auto* reserve_space = ctx.Input<phi::DenseTensor>("ReserveSpace");
    auto* mean = ctx.Input<phi::DenseTensor>("ReserveSpace");
    auto* variance = ctx.Input<phi::DenseTensor>("ReserveSpace");
159

K
Kaipeng Deng 已提交
160
    if (ctx.Attr<bool>("use_sync_bn")) {
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
      auto& dev_ctx = ctx.device_context<DeviceContext>();
      phi::SyncBatchNormGradFunctor<T>(
          static_cast<const typename framework::ConvertToPhiContext<
              DeviceContext>::TYPE&>(dev_ctx),
          nullptr,
          y,
          *scale,
          *bias,
          *saved_mean,
          *saved_variance,
          *d_y,
          epsilon,
          data_layout,
          d_x,
          scale_grad,
          bias_grad);
K
Kaipeng Deng 已提交
177
    } else {
178 179 180
      paddle::optional<Tensor> space_opt;
      paddle::optional<Tensor> mean_opt;
      paddle::optional<Tensor> variance_opt;
H
hong 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197

      if (reserve_space != nullptr) {
        space_opt = *reserve_space;
      }

      if (mean != nullptr) {
        mean_opt = *mean;
      }

      if (variance != nullptr) {
        variance_opt = *variance;
      }

      auto& dev_ctx = ctx.device_context<DeviceContext>();
      phi::BatchNormGradRawKernel<T>(
          static_cast<const typename framework::ConvertToPhiContext<
              DeviceContext>::TYPE&>(dev_ctx),
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
          *y,
          *scale,
          *bias,
          mean_opt,
          variance_opt,
          *saved_mean,
          *saved_variance,
          space_opt,
          *d_y,
          momentum,
          epsilon,
          data_layout,
          is_test,
          use_global_stats,
          trainable_statistics,
          fuse_with_relu,
          true,
          d_x,
          scale_grad,
          bias_grad);
K
Kaipeng Deng 已提交
218 219 220 221 222 223 224 225 226
    }
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
namespace plat = paddle::platform;
227 228 229
#ifdef PADDLE_WITH_HIP
// MIOPEN do not support double
REGISTER_OP_CUDA_KERNEL(inplace_abn,
L
Leo Chen 已提交
230 231 232
                        ops::InplaceABNKernel<phi::GPUContext, float>);
REGISTER_OP_CUDA_KERNEL(inplace_abn_grad,
                        ops::InplaceABNGradKernel<phi::GPUContext, float>);
233
#else
K
Kaipeng Deng 已提交
234
REGISTER_OP_CUDA_KERNEL(inplace_abn,
L
Leo Chen 已提交
235 236 237 238 239
                        ops::InplaceABNKernel<phi::GPUContext, float>,
                        ops::InplaceABNKernel<phi::GPUContext, double>);
REGISTER_OP_CUDA_KERNEL(inplace_abn_grad,
                        ops::InplaceABNGradKernel<phi::GPUContext, float>,
                        ops::InplaceABNGradKernel<phi::GPUContext, double>);
240
#endif