inplace_abn_op.cc 14.0 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

K
Kaipeng Deng 已提交
17 18 19
#include <memory>
#include <string>
#include <vector>
20

K
Kaipeng Deng 已提交
21
#include "paddle/fluid/operators/batch_norm_op.h"
H
hong 已提交
22 23
#include "paddle/phi/kernels/batch_norm_grad_kernel.h"
#include "paddle/phi/kernels/batch_norm_kernel.h"
K
Kaipeng Deng 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

namespace paddle {
namespace operators {

class InplaceABNOp : public paddle::operators::BatchNormOp {
 public:
  using paddle::operators::BatchNormOp::BatchNormOp;

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    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;
    }
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
    PADDLE_ENFORCE_EQ(
        bn_param_type,
        framework::TransToProtoVarType(ctx.Input<Tensor>("Scale")->dtype()),
        platform::errors::InvalidArgument(
            "Scale input should be of float type"));
    PADDLE_ENFORCE_EQ(
        bn_param_type,
        framework::TransToProtoVarType(ctx.Input<Tensor>("Bias")->dtype()),
        platform::errors::InvalidArgument(
            "Bias input should be of float type"));
    PADDLE_ENFORCE_EQ(
        bn_param_type,
        framework::TransToProtoVarType(ctx.Input<Tensor>("Mean")->dtype()),
        platform::errors::InvalidArgument(
            "Mean input should be of float type"));
58 59 60 61 62
    PADDLE_ENFORCE_EQ(
        bn_param_type,
        framework::TransToProtoVarType(ctx.Input<Tensor>("Variance")->dtype()),
        platform::errors::InvalidArgument(
            "Variance input should be of float type"));
K
Kaipeng Deng 已提交
63 64 65 66

    framework::LibraryType library = framework::LibraryType::kPlain;
    framework::DataLayout layout = framework::DataLayout::kAnyLayout;

67 68
    return framework::OpKernelType(
        input_data_type, ctx.GetPlace(), layout, library);
K
Kaipeng Deng 已提交
69 70 71 72 73 74 75
  }
};

class InplaceABNGradOp : public paddle::operators::BatchNormGradOp {
 public:
  using paddle::operators::BatchNormGradOp::BatchNormGradOp;

76 77 78
  void InferShape(framework::InferShapeContext* ctx) const {
    // check input
    OP_INOUT_CHECK(ctx->HasInput("Scale"), "Input", "Scale", "InplaceABNGrad");
79 80 81
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Y")),
                   "Input",
                   "Y@GRAD",
82
                   "InplaceABNGrad");
83 84 85 86 87
    OP_INOUT_CHECK(
        ctx->HasInput("SavedMean"), "Input", "SavedMean", "InplaceABNGrad");
    OP_INOUT_CHECK(ctx->HasInput("SavedVariance"),
                   "Input",
                   "SavedVariance",
88 89 90
                   "InplaceABNGrad");

    // check output
91 92 93 94
    OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("X")),
                   "Output",
                   "X@GRAD",
                   "InplaceABNGrad");
95 96 97 98 99

    const bool has_scale_grad = ctx->HasOutput(framework::GradVarName("Scale"));
    const bool has_bias_grad = ctx->HasOutput(framework::GradVarName("Bias"));

    PADDLE_ENFORCE_EQ(
100 101
        has_scale_grad,
        has_bias_grad,
102 103 104 105
        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]",
106 107
            has_scale_grad,
            has_bias_grad));
108 109 110 111

    const bool use_global_stats = ctx->Attrs().Get<bool>("use_global_stats");
    if (use_global_stats) {
      PADDLE_ENFORCE_EQ(
112 113
          !ctx->Attrs().Get<bool>("use_mkldnn"),
          true,
114 115 116 117 118 119 120 121 122 123
          platform::errors::InvalidArgument(
              "Using global stats during training is not supported "
              "in gradient op kernel of batch_norm_mkldnn_op now."));
    }

    OP_INOUT_CHECK(ctx->HasInput("Y"), "Input", "Y", "InplaceABNGrad");
    const auto y_dims = ctx->GetInputDim("Y");
    const DataLayout data_layout = framework::StringToDataLayout(
        ctx->Attrs().Get<std::string>("data_layout"));

124 125 126 127
    const int C = ((ctx->IsRunMKLDNNKernel() == true) ||
                           (data_layout == DataLayout::kNCHW)
                       ? y_dims[1]
                       : y_dims[y_dims.size() - 1]);
128 129 130 131 132 133 134 135 136

    ctx->SetOutputDim(framework::GradVarName("X"), y_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});
    }
  }

K
Kaipeng Deng 已提交
137 138 139 140
 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    const auto* var = ctx.InputVar(framework::GradVarName("Y"));
141 142
    auto input_data_type =
        framework::TransToProtoVarType(ctx.Input<Tensor>("Y")->dtype());
K
Kaipeng Deng 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
    if (var == nullptr) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "can't find gradient variable of Y"));
    }
    const Tensor* t = nullptr;
    if (var->IsType<Tensor>()) {
      t = &var->Get<Tensor>();
    } else if (var->IsType<LoDTensor>()) {
      t = &var->Get<LoDTensor>();
    }
    if (t == nullptr) {
      PADDLE_THROW(
          platform::errors::InvalidArgument("gradient variable of Y is empty"));
    }
    framework::LibraryType library = framework::LibraryType::kPlain;
    framework::DataLayout layout = framework::DataLayout::kAnyLayout;

160 161
    return framework::OpKernelType(
        input_data_type, ctx.GetPlace(), layout, library);
K
Kaipeng Deng 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
  }
};

class InplaceABNOpMaker : public paddle::operators::BatchNormOpMaker {
 public:
  void Make() override {
    BatchNormOpMaker::Make();
    AddAttr<std::string>(
        "activation",
        "(enum string, default identity, can be identity|elu|leaky-relu) "
        "The activation type used for output candidate {h}_t.")
        .SetDefault("");
    AddAttr<float>("alpha",
                   "(float, default 1.0) Only used in inplace-abn kernel,"
                   "the activation type(identity|elu|leakyrelu) would be fused "
                   "with batch_norm, "
                   "this is the alpha value for elu|leakyrelu.")
        .SetDefault(0.1f);
    AddAttr<bool>("use_sync_bn",
                  "(bool, default false) Whether use synchronize batch "
                  "normalization.")
        .SetDefault(false);
  }
};

template <typename T>
class InplaceABNOpGradMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
  void Apply(GradOpPtr<T> op) const override {
    op->SetType(this->ForwardOpType() + "_grad");
    op->SetInput("Y", this->Output("Y"));
    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"));
202 203 204
    if (this->HasOutput("ReserveSpace")) {
      op->SetInput("ReserveSpace", this->Output("ReserveSpace"));
    }
K
Kaipeng Deng 已提交
205 206

    // used when setting use_global_stats True during training
207
    if (BOOST_GET_CONST(bool, this->GetAttr("use_global_stats"))) {
K
Kaipeng Deng 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220
      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"));
  }
};

template <typename DeviceContext, typename T>
H
hong 已提交
221
class InplaceABNKernel : public framework::OpKernel<T> {
K
Kaipeng Deng 已提交
222 223 224 225
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* x = ctx.Input<Tensor>("X");
    auto* y = ctx.Output<Tensor>("Y");
226 227
    PADDLE_ENFORCE_EQ(x,
                      y,
228 229
                      platform::errors::InvalidArgument(
                          "X and Y not inplaced in inplace mode"));
K
Kaipeng Deng 已提交
230 231 232
    auto activation =
        GetInplaceABNActivationType(ctx.Attr<std::string>("activation"));
    auto& place = *ctx.template device_context<DeviceContext>().eigen_device();
H
hong 已提交
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256

    auto* scale = ctx.Input<Tensor>("Scale");
    auto* bias = ctx.Input<Tensor>("Bias");
    auto* mean = ctx.Input<Tensor>("Mean");
    auto* variance = ctx.Input<Tensor>("Variance");

    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");

    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");
    auto* reserve_space = ctx.Output<Tensor>("ReserveSpace");

    auto& dev_ctx = ctx.device_context<DeviceContext>();
    phi::BatchNormKernel<T>(
        static_cast<const typename framework::ConvertToPhiContext<
            DeviceContext>::TYPE&>(dev_ctx),
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
        *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 已提交
275 276 277 278 279 280 281 282

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

template <typename DeviceContext, typename T>
H
hong 已提交
283
class InplaceABNGradKernel : public framework::OpKernel<T> {
K
Kaipeng Deng 已提交
284 285 286 287 288
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* y = ctx.Input<Tensor>("Y");
    auto* d_y = ctx.Input<Tensor>(framework::GradVarName("Y"));
    auto* d_x = ctx.Output<Tensor>(framework::GradVarName("X"));
289 290
    PADDLE_ENFORCE_EQ(d_x,
                      d_y,
K
Kaipeng Deng 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304
                      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);

H
hong 已提交
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
    // BatchNormGradKernel<DeviceContext, T>::Compute(ctx);

    auto* scale = ctx.Input<Tensor>("Scale");
    auto* bias = ctx.Input<Tensor>("Bias");
    auto* saved_mean = ctx.Input<Tensor>("SavedMean");
    auto* saved_variance = ctx.Input<Tensor>("SavedVariance");

    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");

    auto* scale_grad = ctx.Output<Tensor>(framework::GradVarName("Scale"));
    auto* bias_grad = ctx.Output<Tensor>(framework::GradVarName("Bias"));

    auto* reserve_space = ctx.Input<Tensor>("ReserveSpace");
    auto* mean = ctx.Input<Tensor>("ReserveSpace");
    auto* variance = ctx.Input<Tensor>("ReserveSpace");

327 328 329
    paddle::optional<Tensor> space_opt;
    paddle::optional<Tensor> mean_opt;
    paddle::optional<Tensor> variance_opt;
H
hong 已提交
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346

    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),
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
        *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 已提交
367 368 369 370 371 372 373
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
H
hong 已提交
374

375
DECLARE_INPLACE_OP_INFERER(InplaceAbnOpInplaceInferer, {"X", "Y"});
376 377 378
REGISTER_OPERATOR(inplace_abn,
                  ops::InplaceABNOp,
                  ops::InplaceABNOpMaker,
K
Kaipeng Deng 已提交
379 380
                  ops::BatchNormOpInferVarType,
                  ops::InplaceABNOpGradMaker<paddle::framework::OpDesc>,
381 382
                  ops::InplaceABNOpGradMaker<paddle::imperative::OpBase>,
                  InplaceAbnOpInplaceInferer)
K
Kaipeng Deng 已提交
383 384
REGISTER_OPERATOR(inplace_abn_grad, ops::InplaceABNGradOp)

L
Leo Chen 已提交
385 386 387 388 389 390
REGISTER_OP_CPU_KERNEL(inplace_abn,
                       ops::InplaceABNKernel<phi::CPUContext, float>,
                       ops::InplaceABNKernel<phi::CPUContext, double>);
REGISTER_OP_CPU_KERNEL(inplace_abn_grad,
                       ops::InplaceABNGradKernel<phi::CPUContext, float>,
                       ops::InplaceABNGradKernel<phi::CPUContext, double>);