activation_mkldnn_op.cc 12.4 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

19
namespace phi {
20
class DenseTensor;
21
}  // namespace phi
22

W
wanghuancoder 已提交
23
namespace paddle {
24
namespace framework {}  // namespace framework
W
wanghuancoder 已提交
25 26 27 28 29
namespace platform {
class MKLDNNDeviceContext;
}  // namespace platform
}  // namespace paddle

30 31 32
namespace paddle {
namespace operators {

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

42 43 44 45 46 47 48 49 50
template <typename Functor>
class MKLDNNActivationKernel
    : public framework::OpKernel<typename Functor::ELEMENT_TYPE> {
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
    Functor functor;
    functor(ctx);
  }
};
K
Krzysztof Binias 已提交
51

52 53 54 55 56 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 {
    Functor functor;
    functor(ctx);
  }
};

template <typename T>
void eltwise_forward(const framework::ExecutionContext &ctx,
64
                     dnnl::algorithm algorithm) {
65 66 67
  PADDLE_ENFORCE_EQ(platform::is_cpu_place(ctx.GetPlace()), true,
                    paddle::platform::errors::PreconditionNotMet(
                        "Operator DNNL eletwise_forward must use CPUPlace"));
68
  auto &dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();
69
  const auto &mkldnn_engine = dev_ctx.GetEngine();
70

71
  const auto *x = ctx.Input<Tensor>("X");
72
  auto *out = ctx.Output<Tensor>("Out");
73

74
  bool is_inplaced = x->IsSharedBufferWith(*out);
75

76 77
  platform::ActivationMKLDNNHandler<T> handler(algorithm, ctx, mkldnn_engine,
                                               ctx.GetPlace(), x);
78

79
  auto src_memory_p = handler.AcquireSrcMemory(x);
80 81 82
  std::shared_ptr<dnnl::memory> dst_memory_p = nullptr;
  if (is_inplaced) {
    dst_memory_p = src_memory_p;
83
    out->mutable_data<T>(ctx.GetPlace());
84
  } else {
85
    dst_memory_p = handler.AcquireDstMemory(out);
86
  }
A
Adam 已提交
87
  auto activation_p = handler.AcquireForwardPrimitive();
88

89
  auto &astream = paddle::platform::MKLDNNDeviceContext::tls().get_stream();
90 91
  activation_p->execute(
      astream, {{DNNL_ARG_FROM, *src_memory_p}, {DNNL_ARG_TO, *dst_memory_p}});
A
Adam 已提交
92
  astream.wait();
93

94
  out->set_mem_desc(dst_memory_p->get_desc());
95 96
}

97 98
template <typename T>
void eltwise_grad(const framework::ExecutionContext &ctx,
99
                  dnnl::algorithm algorithm) {
100
  auto &dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();
101
  const auto &mkldnn_engine = dev_ctx.GetEngine();
102

103
  const auto *x = ctx.Input<Tensor>("X");
104 105
  const auto *dout = ctx.Input<Tensor>(framework::GradVarName("Out"));
  auto *dx = ctx.Output<Tensor>(framework::GradVarName("X"));
106

107
  platform::ActivationMKLDNNHandler<T> handler(algorithm, ctx, mkldnn_engine,
108
                                               ctx.GetPlace(), x, dout);
109

110
  auto src_memory_p = handler.AcquireBackwardSrcMemory(x);
111 112
  auto diff_dst_memory_p = handler.AcquireDiffDstMemory(dout);
  auto diff_src_memory_p = handler.AcquireDiffSrcMemory(dx);
A
Adam 已提交
113 114
  auto activation_backward_p = handler.AcquireBackwardPrimitive();

115
  auto &astream = paddle::platform::MKLDNNDeviceContext::tls().get_stream();
A
Adam 已提交
116
  activation_backward_p->execute(astream,
117 118 119
                                 {{DNNL_ARG_SRC, *src_memory_p},
                                  {DNNL_ARG_DIFF_DST, *diff_dst_memory_p},
                                  {DNNL_ARG_DIFF_SRC, *diff_src_memory_p}});
A
Adam 已提交
120
  astream.wait();
121

122
  dx->set_mem_desc(diff_src_memory_p->get_desc());
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
}

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

150
  dx->set_mem_desc(diff_src_memory_p->get_desc());
151 152
}

153
template <typename T, dnnl::algorithm algorithm>
154
struct MKLDNNActivationFunc : public BaseActivationFunctor<T> {
155
  void operator()(const framework::ExecutionContext &ctx) const {
156 157 158 159
    eltwise_forward<T>(ctx, algorithm);
  }
};

160
template <typename T, dnnl::algorithm algorithm>
161
struct MKLDNNActivationGradFunc : public BaseActivationFunctor<T> {
162
  void operator()(const framework::ExecutionContext &ctx) const {
163 164 165 166
    eltwise_grad<T>(ctx, algorithm);
  }
};

167 168 169 170 171 172 173
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 已提交
174 175 176 177 178
template <typename T>
struct GeluMKLDNNFunctor : public BaseActivationFunctor<T> {
  void operator()(const framework::ExecutionContext &ctx) const {
    const bool approximate = ctx.Attr<bool>("approximate");
    if (approximate) {
179
      eltwise_forward<T>(ctx, dnnl::algorithm::eltwise_gelu_tanh);
A
Adam 已提交
180
    } else {
181
      eltwise_forward<T>(ctx, dnnl::algorithm::eltwise_gelu_erf);
A
Adam 已提交
182 183 184 185 186 187 188 189 190
    }
  }
};

template <typename T>
struct GeluMKLDNNGradFunctor : public BaseActivationFunctor<T> {
  void operator()(const framework::ExecutionContext &ctx) const {
    const bool approximate = ctx.Attr<bool>("approximate");
    if (approximate) {
191
      eltwise_grad<T>(ctx, dnnl::algorithm::eltwise_gelu_tanh);
A
Adam 已提交
192
    } else {
193
      eltwise_grad<T>(ctx, dnnl::algorithm::eltwise_gelu_erf);
A
Adam 已提交
194 195 196 197
    }
  }
};

198 199 200 201 202 203 204
template <typename T>
struct SoftplusMKLDNNFunctor : public BaseActivationFunctor<T> {
  void operator()(const framework::ExecutionContext &ctx) const {
    custom_softplus_eltwise_forward<T>(ctx);
  }
};

205
template <typename T>
T
tensor-tang 已提交
206
using ReluMKLDNNFunctor =
207
    MKLDNNActivationFunc<T, dnnl::algorithm::eltwise_relu>;
208

A
Adam 已提交
209 210
template <typename T>
using Relu6MKLDNNFunctor =
211
    MKLDNNActivationFunc<T, dnnl::algorithm::eltwise_bounded_relu>;
A
Adam 已提交
212

213 214
template <typename T>
using SwishMKLDNNFunctor =
215
    MKLDNNActivationFunc<T, dnnl::algorithm::eltwise_swish>;
216

J
jakpiase 已提交
217 218
template <typename T>
using HardSwishMKLDNNFunctor =
219
    MKLDNNActivationFunc<T, dnnl::algorithm::eltwise_hardswish>;
J
jakpiase 已提交
220

221 222 223 224
template <typename T>
using MishMKLDNNFunctor =
    MKLDNNActivationFunc<T, dnnl::algorithm::eltwise_mish>;

225 226
template <typename T>
using SigmoidMKLDNNFunctor =
227
    MKLDNNActivationFunc<T, dnnl::algorithm::eltwise_logistic>;
228

229
template <typename T>
T
tensor-tang 已提交
230
using TanhMKLDNNFunctor =
231
    MKLDNNActivationFunc<T, dnnl::algorithm::eltwise_tanh>;
232 233

template <typename T>
T
tensor-tang 已提交
234
using SqrtMKLDNNFunctor =
235
    MKLDNNActivationFunc<T, dnnl::algorithm::eltwise_sqrt>;
236 237

template <typename T>
238
using AbsMKLDNNFunctor = MKLDNNActivationFunc<T, dnnl::algorithm::eltwise_abs>;
239

J
jakpiase 已提交
240
template <typename T>
241
using EluMKLDNNFunctor = MKLDNNActivationFunc<T, dnnl::algorithm::eltwise_elu>;
J
jakpiase 已提交
242

243 244 245
template <typename T>
using ExpMKLDNNFunctor = MKLDNNActivationFunc<T, dnnl::algorithm::eltwise_exp>;

246 247 248 249
template <typename T>
using RoundMKLDNNFunctor =
    MKLDNNActivationFunc<T, dnnl::algorithm::eltwise_round>;

250
template <typename T>
T
tensor-tang 已提交
251
using ReluMKLDNNGradFunctor =
252
    MKLDNNActivationGradFunc<T, dnnl::algorithm::eltwise_relu>;
253

A
Adam 已提交
254 255
template <typename T>
using Relu6MKLDNNGradFunctor =
256
    MKLDNNActivationGradFunc<T, dnnl::algorithm::eltwise_bounded_relu>;
A
Adam 已提交
257

258 259
template <typename T>
using SwishMKLDNNGradFunctor =
260
    MKLDNNActivationGradFunc<T, dnnl::algorithm::eltwise_swish>;
261

J
jakpiase 已提交
262 263
template <typename T>
using HardSwishMKLDNNGradFunctor =
264
    MKLDNNActivationGradFunc<T, dnnl::algorithm::eltwise_hardswish>;
J
jakpiase 已提交
265

266 267 268 269
template <typename T>
using MishMKLDNNGradFunctor =
    MKLDNNActivationGradFunc<T, dnnl::algorithm::eltwise_mish>;

270
template <typename T>
271 272
using SigmoidMKLDNNGradUseOutFunctor = MKLDNNActivationGradUseOutFunc<
    T, dnnl::algorithm::eltwise_logistic_use_dst_for_bwd>;
273

274
template <typename T>
275 276
using TanhMKLDNNGradUseOutFunctor = MKLDNNActivationGradUseOutFunc<
    T, dnnl::algorithm::eltwise_tanh_use_dst_for_bwd>;
277 278

template <typename T>
279 280
using SqrtMKLDNNGradUseOutFunctor = MKLDNNActivationGradUseOutFunc<
    T, dnnl::algorithm::eltwise_sqrt_use_dst_for_bwd>;
281 282

template <typename T>
T
tensor-tang 已提交
283
using AbsMKLDNNGradFunctor =
284
    MKLDNNActivationGradFunc<T, dnnl::algorithm::eltwise_abs>;
J
jakpiase 已提交
285 286

template <typename T>
287 288 289 290 291 292 293
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>;

294 295 296 297 298
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

299
#define REGISTER_ACTIVATION_MKLDNN_KERNEL(act_type, functor, grad_functor)    \
300 301 302 303 304 305
  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,                  \
306 307 308
      ops::MKLDNNActivationGradKernel<ops::grad_functor<float>>,              \
      ops::MKLDNNActivationGradKernel<                                        \
          ops::grad_functor<paddle::platform::bfloat16>>);
309

310 311 312 313
#define REGISTER_ACTIVATION_MKLDNN_KERNEL_FWD_ONLY(act_type, functor) \
  REGISTER_OP_KERNEL(act_type, MKLDNN, ::paddle::platform::CPUPlace,  \
                     ops::MKLDNNActivationKernel<ops::functor<float>>);

J
jakpiase 已提交
314 315
#define FOR_EACH_MKLDNN_KERNEL_FUNCTOR(__macro)                            \
  __macro(abs, AbsMKLDNNFunctor, AbsMKLDNNGradFunctor);                    \
316
  __macro(elu, EluMKLDNNFunctor, EluMKLDNNGradUseOutFunctor);              \
317 318 319 320 321 322 323 324 325 326 327
  __macro(exp, ExpMKLDNNFunctor, ExpMKLDNNGradUseOutFunctor);              \
  __macro(gelu, GeluMKLDNNFunctor, GeluMKLDNNGradFunctor);                 \
  __macro(hard_swish, HardSwishMKLDNNFunctor, HardSwishMKLDNNGradFunctor); \
  __macro(leaky_relu, ReluMKLDNNFunctor, ReluMKLDNNGradFunctor);           \
  __macro(mish, MishMKLDNNFunctor, MishMKLDNNGradFunctor);                 \
  __macro(relu, ReluMKLDNNFunctor, ReluMKLDNNGradFunctor);                 \
  __macro(relu6, Relu6MKLDNNFunctor, Relu6MKLDNNGradFunctor);              \
  __macro(sigmoid, SigmoidMKLDNNFunctor, SigmoidMKLDNNGradUseOutFunctor);  \
  __macro(sqrt, SqrtMKLDNNFunctor, SqrtMKLDNNGradUseOutFunctor);           \
  __macro(swish, SwishMKLDNNFunctor, SwishMKLDNNGradFunctor);              \
  __macro(tanh, TanhMKLDNNFunctor, TanhMKLDNNGradUseOutFunctor);
328 329

FOR_EACH_MKLDNN_KERNEL_FUNCTOR(REGISTER_ACTIVATION_MKLDNN_KERNEL);
330

331
// round eltwise primitive doesn't support BF16, nor does it support grad
332
REGISTER_ACTIVATION_MKLDNN_KERNEL_FWD_ONLY(round, RoundMKLDNNFunctor);
333 334 335 336

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