activation_mkldnn_op.cc 13.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.

   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/activation_op.h"
16
#include "paddle/fluid/operators/mkldnn/softplus_mkldnn_op.h"
17
#include "paddle/fluid/platform/mkldnn_reuse.h"
18

W
wanghuancoder 已提交
19 20 21 22 23 24 25 26 27
namespace paddle {
namespace framework {
class Tensor;
}  // namespace framework
namespace platform {
class MKLDNNDeviceContext;
}  // namespace platform
}  // namespace paddle

28 29 30
namespace paddle {
namespace operators {

31 32
using framework::DataLayout;
using framework::Tensor;
33 34 35
using dnnl::memory;
using dnnl::primitive;
using dnnl::stream;
36 37 38
using platform::GetMKLDNNFormat;
using platform::MKLDNNDeviceContext;
using platform::to_void_cast;
39

40 41 42 43 44 45
template <typename Functor>
class MKLDNNActivationKernel
    : public framework::OpKernel<typename Functor::ELEMENT_TYPE> {
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
    const auto *x = ctx.Input<Tensor>("X");
46 47 48 49 50 51
    PADDLE_ENFORCE_EQ(
        x->layout(), DataLayout::kMKLDNN,
        platform::errors::InvalidArgument("Wrong layout set for X tensor"));
    PADDLE_ENFORCE_NE(
        x->format(), MKLDNNMemoryFormat::undef,
        platform::errors::InvalidArgument("Wrong format set for X tensor"));
52 53 54 55 56

    Functor functor;
    functor(ctx);
  }
};
K
Krzysztof Binias 已提交
57

58 59 60 61 62 63
template <typename Functor>
class MKLDNNActivationGradKernel
    : public framework::OpKernel<typename Functor::ELEMENT_TYPE> {
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
    const auto *diff_y = ctx.Input<Tensor>(framework::GradVarName("Out"));
64
    PADDLE_ENFORCE_EQ(diff_y->layout(), DataLayout::kMKLDNN,
65 66
                      platform::errors::InvalidArgument(
                          "Wrong layout set for Input OutGrad tensor"));
A
Adam 已提交
67
    PADDLE_ENFORCE_NE(diff_y->format(), MKLDNNMemoryFormat::undef,
68 69
                      platform::errors::InvalidArgument(
                          "Wrong format set for Input OutGrad tensor"));
70 71 72 73 74 75 76 77

    Functor functor;
    functor(ctx);
  }
};

template <typename T>
void eltwise_forward(const framework::ExecutionContext &ctx,
78
                     dnnl::algorithm algorithm) {
79 80 81
  PADDLE_ENFORCE_EQ(platform::is_cpu_place(ctx.GetPlace()), true,
                    paddle::platform::errors::PreconditionNotMet(
                        "Operator DNNL eletwise_forward must use CPUPlace"));
82
  auto &dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();
83
  const auto &mkldnn_engine = dev_ctx.GetEngine();
84

85
  const auto *x = ctx.Input<Tensor>("X");
86
  auto *out = ctx.Output<Tensor>("Out");
87

88
  bool is_inplaced = x->IsSharedBufferWith(*out);
89

90 91
  platform::ActivationMKLDNNHandler<T> handler(algorithm, ctx, mkldnn_engine,
                                               ctx.GetPlace(), x);
92

93
  auto src_memory_p = handler.AcquireSrcMemory(x);
94 95 96
  std::shared_ptr<dnnl::memory> dst_memory_p = nullptr;
  if (is_inplaced) {
    dst_memory_p = src_memory_p;
97
    out->mutable_data<T>(ctx.GetPlace());
98
  } else {
99
    dst_memory_p = handler.AcquireDstMemory(out);
100
  }
A
Adam 已提交
101
  auto activation_p = handler.AcquireForwardPrimitive();
102

103
  auto &astream = paddle::platform::MKLDNNDeviceContext::tls().get_stream();
104 105
  activation_p->execute(
      astream, {{DNNL_ARG_FROM, *src_memory_p}, {DNNL_ARG_TO, *dst_memory_p}});
A
Adam 已提交
106
  astream.wait();
107

108 109
  out->set_layout(DataLayout::kMKLDNN);
  out->set_format(GetMKLDNNFormat(*dst_memory_p));
110 111
}

112 113
template <typename T>
void eltwise_grad(const framework::ExecutionContext &ctx,
114
                  dnnl::algorithm algorithm) {
115
  auto &dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();
116
  const auto &mkldnn_engine = dev_ctx.GetEngine();
117

118
  const auto *x = ctx.Input<Tensor>("X");
119 120
  const auto *dout = ctx.Input<Tensor>(framework::GradVarName("Out"));
  auto *dx = ctx.Output<Tensor>(framework::GradVarName("X"));
121

122
  platform::ActivationMKLDNNHandler<T> handler(algorithm, ctx, mkldnn_engine,
123
                                               ctx.GetPlace(), x, dout);
124

125
  auto src_memory_p = handler.AcquireBackwardSrcMemory(x);
126 127
  auto diff_dst_memory_p = handler.AcquireDiffDstMemory(dout);
  auto diff_src_memory_p = handler.AcquireDiffSrcMemory(dx);
A
Adam 已提交
128 129
  auto activation_backward_p = handler.AcquireBackwardPrimitive();

130
  auto &astream = paddle::platform::MKLDNNDeviceContext::tls().get_stream();
A
Adam 已提交
131
  activation_backward_p->execute(astream,
132 133 134
                                 {{DNNL_ARG_SRC, *src_memory_p},
                                  {DNNL_ARG_DIFF_DST, *diff_dst_memory_p},
                                  {DNNL_ARG_DIFF_SRC, *diff_src_memory_p}});
A
Adam 已提交
135
  astream.wait();
136

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
  dx->set_layout(DataLayout::kMKLDNN);
  dx->set_format(GetMKLDNNFormat(*diff_src_memory_p));
}

template <typename T>
void eltwise_grad_use_out(const framework::ExecutionContext &ctx,
                          dnnl::algorithm algorithm) {
  auto &dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();
  const auto &mkldnn_engine = dev_ctx.GetEngine();

  const auto *out = ctx.Input<Tensor>("Out");
  const auto *dout = ctx.Input<Tensor>(framework::GradVarName("Out"));
  auto *dx = ctx.Output<Tensor>(framework::GradVarName("X"));

  platform::ActivationMKLDNNHandler<T> handler(algorithm, ctx, mkldnn_engine,
                                               ctx.GetPlace(), out, dout);

  auto dst_memory_p = handler.AcquireBackwardSrcMemory(out);
  auto diff_dst_memory_p = handler.AcquireDiffDstMemory(dout);
  auto diff_src_memory_p = handler.AcquireDiffSrcMemory(dx);
  auto activation_backward_p = handler.AcquireBackwardPrimitive();

  auto &astream = paddle::platform::MKLDNNDeviceContext::tls().get_stream();
  activation_backward_p->execute(astream,
                                 {{DNNL_ARG_DST, *dst_memory_p},
                                  {DNNL_ARG_DIFF_DST, *diff_dst_memory_p},
                                  {DNNL_ARG_DIFF_SRC, *diff_src_memory_p}});
  astream.wait();

  dx->set_layout(DataLayout::kMKLDNN);
  dx->set_format(GetMKLDNNFormat(*diff_src_memory_p));
168 169
}

170
template <typename T, dnnl::algorithm algorithm>
171
struct MKLDNNActivationFunc : public BaseActivationFunctor<T> {
172
  void operator()(const framework::ExecutionContext &ctx) const {
173 174 175 176
    eltwise_forward<T>(ctx, algorithm);
  }
};

177
template <typename T, dnnl::algorithm algorithm>
178
struct MKLDNNActivationGradFunc : public BaseActivationFunctor<T> {
179
  void operator()(const framework::ExecutionContext &ctx) const {
180 181 182 183
    eltwise_grad<T>(ctx, algorithm);
  }
};

184 185 186 187 188 189 190
template <typename T, dnnl::algorithm algorithm>
struct MKLDNNActivationGradUseOutFunc : public BaseActivationFunctor<T> {
  void operator()(const framework::ExecutionContext &ctx) const {
    eltwise_grad_use_out<T>(ctx, algorithm);
  }
};

A
Adam 已提交
191 192 193 194 195
template <typename T>
struct GeluMKLDNNFunctor : public BaseActivationFunctor<T> {
  void operator()(const framework::ExecutionContext &ctx) const {
    const bool approximate = ctx.Attr<bool>("approximate");
    if (approximate) {
196
      eltwise_forward<T>(ctx, dnnl::algorithm::eltwise_gelu_tanh);
A
Adam 已提交
197
    } else {
198
      eltwise_forward<T>(ctx, dnnl::algorithm::eltwise_gelu_erf);
A
Adam 已提交
199 200 201 202 203 204 205 206 207
    }
  }
};

template <typename T>
struct GeluMKLDNNGradFunctor : public BaseActivationFunctor<T> {
  void operator()(const framework::ExecutionContext &ctx) const {
    const bool approximate = ctx.Attr<bool>("approximate");
    if (approximate) {
208
      eltwise_grad<T>(ctx, dnnl::algorithm::eltwise_gelu_tanh);
A
Adam 已提交
209
    } else {
210
      eltwise_grad<T>(ctx, dnnl::algorithm::eltwise_gelu_erf);
A
Adam 已提交
211 212 213 214
    }
  }
};

215 216 217 218 219 220 221
template <typename T>
struct SoftplusMKLDNNFunctor : public BaseActivationFunctor<T> {
  void operator()(const framework::ExecutionContext &ctx) const {
    custom_softplus_eltwise_forward<T>(ctx);
  }
};

222
template <typename T>
T
tensor-tang 已提交
223
using ReluMKLDNNFunctor =
224
    MKLDNNActivationFunc<T, dnnl::algorithm::eltwise_relu>;
225

A
Adam 已提交
226 227
template <typename T>
using Relu6MKLDNNFunctor =
228
    MKLDNNActivationFunc<T, dnnl::algorithm::eltwise_bounded_relu>;
A
Adam 已提交
229

230 231
template <typename T>
using SwishMKLDNNFunctor =
232
    MKLDNNActivationFunc<T, dnnl::algorithm::eltwise_swish>;
233

J
jakpiase 已提交
234 235
template <typename T>
using HardSwishMKLDNNFunctor =
236
    MKLDNNActivationFunc<T, dnnl::algorithm::eltwise_hardswish>;
J
jakpiase 已提交
237

238 239
template <typename T>
using SigmoidMKLDNNFunctor =
240
    MKLDNNActivationFunc<T, dnnl::algorithm::eltwise_logistic>;
241

242
template <typename T>
T
tensor-tang 已提交
243
using TanhMKLDNNFunctor =
244
    MKLDNNActivationFunc<T, dnnl::algorithm::eltwise_tanh>;
245 246

template <typename T>
T
tensor-tang 已提交
247
using SqrtMKLDNNFunctor =
248
    MKLDNNActivationFunc<T, dnnl::algorithm::eltwise_sqrt>;
249 250

template <typename T>
251
using AbsMKLDNNFunctor = MKLDNNActivationFunc<T, dnnl::algorithm::eltwise_abs>;
252

J
jakpiase 已提交
253
template <typename T>
254
using EluMKLDNNFunctor = MKLDNNActivationFunc<T, dnnl::algorithm::eltwise_elu>;
J
jakpiase 已提交
255

256 257 258
template <typename T>
using ExpMKLDNNFunctor = MKLDNNActivationFunc<T, dnnl::algorithm::eltwise_exp>;

259
template <typename T>
T
tensor-tang 已提交
260
using ReluMKLDNNGradFunctor =
261
    MKLDNNActivationGradFunc<T, dnnl::algorithm::eltwise_relu>;
262

A
Adam 已提交
263 264
template <typename T>
using Relu6MKLDNNGradFunctor =
265
    MKLDNNActivationGradFunc<T, dnnl::algorithm::eltwise_bounded_relu>;
A
Adam 已提交
266

267 268
template <typename T>
using SwishMKLDNNGradFunctor =
269
    MKLDNNActivationGradFunc<T, dnnl::algorithm::eltwise_swish>;
270

J
jakpiase 已提交
271 272
template <typename T>
using HardSwishMKLDNNGradFunctor =
273
    MKLDNNActivationGradFunc<T, dnnl::algorithm::eltwise_hardswish>;
J
jakpiase 已提交
274

275
template <typename T>
276 277
using SigmoidMKLDNNGradUseOutFunctor = MKLDNNActivationGradUseOutFunc<
    T, dnnl::algorithm::eltwise_logistic_use_dst_for_bwd>;
278

279
template <typename T>
280 281
using TanhMKLDNNGradUseOutFunctor = MKLDNNActivationGradUseOutFunc<
    T, dnnl::algorithm::eltwise_tanh_use_dst_for_bwd>;
282 283

template <typename T>
284 285
using SqrtMKLDNNGradUseOutFunctor = MKLDNNActivationGradUseOutFunc<
    T, dnnl::algorithm::eltwise_sqrt_use_dst_for_bwd>;
286 287

template <typename T>
T
tensor-tang 已提交
288
using AbsMKLDNNGradFunctor =
289
    MKLDNNActivationGradFunc<T, dnnl::algorithm::eltwise_abs>;
J
jakpiase 已提交
290 291

template <typename T>
292 293 294 295 296 297 298
using EluMKLDNNGradUseOutFunctor = MKLDNNActivationGradUseOutFunc<
    T, dnnl::algorithm::eltwise_elu_use_dst_for_bwd>;

template <typename T>
using ExpMKLDNNGradUseOutFunctor = MKLDNNActivationGradUseOutFunc<
    T, dnnl::algorithm::eltwise_exp_use_dst_for_bwd>;

299 300 301 302 303 304 305 306 307 308 309 310
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

#define REGISTER_ACTIVATION_MKLDNN_KERNEL(act_type, functor, grad_functor) \
  REGISTER_OP_KERNEL(act_type, MKLDNN, ::paddle::platform::CPUPlace,       \
                     ops::MKLDNNActivationKernel<ops::functor<float>>);    \
  REGISTER_OP_KERNEL(                                                      \
      act_type##_grad, MKLDNN, ::paddle::platform::CPUPlace,               \
      ops::MKLDNNActivationGradKernel<ops::grad_functor<float>>);

311 312 313 314 315 316 317 318
#define REGISTER_ACTIVATION_MKLDNN_BF16_KERNEL(act_type, functor,             \
                                               grad_functor)                  \
  REGISTER_OP_KERNEL(                                                         \
      act_type, MKLDNN, ::paddle::platform::CPUPlace,                         \
      ops::MKLDNNActivationKernel<ops::functor<float>>,                       \
      ops::MKLDNNActivationKernel<ops::functor<paddle::platform::bfloat16>>); \
  REGISTER_OP_KERNEL(                                                         \
      act_type##_grad, MKLDNN, ::paddle::platform::CPUPlace,                  \
319 320 321
      ops::MKLDNNActivationGradKernel<ops::grad_functor<float>>,              \
      ops::MKLDNNActivationGradKernel<                                        \
          ops::grad_functor<paddle::platform::bfloat16>>);
322

J
jakpiase 已提交
323 324 325 326 327
#define FOR_EACH_MKLDNN_KERNEL_FUNCTOR(__macro)                            \
  __macro(relu6, Relu6MKLDNNFunctor, Relu6MKLDNNGradFunctor);              \
  __macro(leaky_relu, ReluMKLDNNFunctor, ReluMKLDNNGradFunctor);           \
  __macro(swish, SwishMKLDNNFunctor, SwishMKLDNNGradFunctor);              \
  __macro(hard_swish, HardSwishMKLDNNFunctor, HardSwishMKLDNNGradFunctor); \
328
  __macro(tanh, TanhMKLDNNFunctor, TanhMKLDNNGradUseOutFunctor);           \
J
jakpiase 已提交
329
  __macro(abs, AbsMKLDNNFunctor, AbsMKLDNNGradFunctor);                    \
330 331
  __macro(elu, EluMKLDNNFunctor, EluMKLDNNGradUseOutFunctor);              \
  __macro(exp, ExpMKLDNNFunctor, ExpMKLDNNGradUseOutFunctor);
332 333

FOR_EACH_MKLDNN_KERNEL_FUNCTOR(REGISTER_ACTIVATION_MKLDNN_KERNEL);
A
arlesniak 已提交
334 335
REGISTER_ACTIVATION_MKLDNN_BF16_KERNEL(relu, ReluMKLDNNFunctor,
                                       ReluMKLDNNGradFunctor);
336 337
REGISTER_ACTIVATION_MKLDNN_BF16_KERNEL(gelu, GeluMKLDNNFunctor,
                                       GeluMKLDNNGradFunctor);
338
REGISTER_ACTIVATION_MKLDNN_BF16_KERNEL(sigmoid, SigmoidMKLDNNFunctor,
339
                                       SigmoidMKLDNNGradUseOutFunctor);
J
jakpiase 已提交
340
REGISTER_ACTIVATION_MKLDNN_BF16_KERNEL(sqrt, SqrtMKLDNNFunctor,
341
                                       SqrtMKLDNNGradUseOutFunctor);
342 343 344 345 346

namespace ops = paddle::operators;
REGISTER_OP_KERNEL(
    softplus, MKLDNN, paddle::platform::CPUPlace,
    ops::MKLDNNActivationKernel<ops::SoftplusMKLDNNFunctor<float>>);