activation_mkldnn_op.cc 12.8 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 35
using dnnl::memory;
using dnnl::primitive;
using dnnl::stream;
36 37
using framework::DataLayout;
using framework::Tensor;
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
  PADDLE_ENFORCE_EQ(platform::is_cpu_place(ctx.GetPlace()),
                    true,
67 68
                    paddle::platform::errors::PreconditionNotMet(
                        "Operator DNNL eletwise_forward must use CPUPlace"));
69
  auto &dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();
70
  const auto &mkldnn_engine = dev_ctx.GetEngine();
71

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

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

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

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

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

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

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

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

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

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

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

123
  dx->set_mem_desc(diff_src_memory_p->get_desc());
124 125 126 127 128 129 130 131 132 133 134 135
}

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

136 137
  platform::ActivationMKLDNNHandler<T> handler(
      algorithm, ctx, mkldnn_engine, ctx.GetPlace(), out, dout);
138 139 140 141 142 143 144 145 146 147 148 149 150

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

276
template <typename T>
277
using TanhMKLDNNGradUseOutFunctor = MKLDNNActivationGradUseOutFunc<
278 279
    T,
    dnnl::algorithm::eltwise_tanh_use_dst_for_bwd>;
280 281

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

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

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

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

300 301 302 303 304
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

305
#define REGISTER_ACTIVATION_MKLDNN_KERNEL(act_type, functor, grad_functor)    \
306
  REGISTER_OP_KERNEL(                                                         \
307 308 309
      act_type,                                                               \
      MKLDNN,                                                                 \
      ::paddle::platform::CPUPlace,                                           \
310 311 312
      ops::MKLDNNActivationKernel<ops::functor<float>>,                       \
      ops::MKLDNNActivationKernel<ops::functor<paddle::platform::bfloat16>>); \
  REGISTER_OP_KERNEL(                                                         \
313 314 315
      act_type##_grad,                                                        \
      MKLDNN,                                                                 \
      ::paddle::platform::CPUPlace,                                           \
316 317 318
      ops::MKLDNNActivationGradKernel<ops::grad_functor<float>>,              \
      ops::MKLDNNActivationGradKernel<                                        \
          ops::grad_functor<paddle::platform::bfloat16>>);
319

320
#define REGISTER_ACTIVATION_MKLDNN_KERNEL_FWD_ONLY(act_type, functor) \
321 322 323
  REGISTER_OP_KERNEL(act_type,                                        \
                     MKLDNN,                                          \
                     ::paddle::platform::CPUPlace,                    \
324 325
                     ops::MKLDNNActivationKernel<ops::functor<float>>);

J
jakpiase 已提交
326 327
#define FOR_EACH_MKLDNN_KERNEL_FUNCTOR(__macro)                            \
  __macro(abs, AbsMKLDNNFunctor, AbsMKLDNNGradFunctor);                    \
328
  __macro(elu, EluMKLDNNFunctor, EluMKLDNNGradUseOutFunctor);              \
329 330 331 332 333 334 335 336 337 338 339
  __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);
340 341

FOR_EACH_MKLDNN_KERNEL_FUNCTOR(REGISTER_ACTIVATION_MKLDNN_KERNEL);
342

343
// round eltwise primitive doesn't support BF16, nor does it support grad
344
REGISTER_ACTIVATION_MKLDNN_KERNEL_FWD_ONLY(round, RoundMKLDNNFunctor);
345 346 347

namespace ops = paddle::operators;
REGISTER_OP_KERNEL(
348 349 350
    softplus,
    MKLDNN,
    paddle::platform::CPUPlace,
351 352 353
    ops::MKLDNNActivationKernel<ops::SoftplusMKLDNNFunctor<float>>,
    ops::MKLDNNActivationKernel<
        ops::SoftplusMKLDNNFunctor<paddle::platform::bfloat16>>);