activation_mkldnn_op.cc 11.2 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/platform/mkldnn_reuse.h"
17

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

27 28 29
namespace paddle {
namespace operators {

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

39 40 41 42 43 44
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");
45 46 47 48 49 50
    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"));
51 52 53 54 55

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

57 58 59 60 61 62
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"));
63
    PADDLE_ENFORCE_EQ(diff_y->layout(), DataLayout::kMKLDNN,
64 65
                      platform::errors::InvalidArgument(
                          "Wrong layout set for Input OutGrad tensor"));
A
Adam 已提交
66
    PADDLE_ENFORCE_NE(diff_y->format(), MKLDNNMemoryFormat::undef,
67 68
                      platform::errors::InvalidArgument(
                          "Wrong format set for Input OutGrad tensor"));
69 70 71 72 73 74 75 76

    Functor functor;
    functor(ctx);
  }
};

template <typename T>
void eltwise_forward(const framework::ExecutionContext &ctx,
A
Adam 已提交
77
                     mkldnn::algorithm algorithm) {
78 79 80
  PADDLE_ENFORCE_EQ(platform::is_cpu_place(ctx.GetPlace()), true,
                    paddle::platform::errors::PreconditionNotMet(
                        "Operator DNNL eletwise_forward must use CPUPlace"));
81 82
  auto &dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();

83 84
  const auto *x = ctx.Input<Tensor>("X");
  auto *y = ctx.Output<Tensor>("Out");
85

86 87
  float alpha = ctx.HasAttr("alpha") ? ctx.Attr<float>("alpha") : 0;
  float beta = ctx.HasAttr("beta") ? ctx.Attr<float>("beta") : 0;
88 89 90 91

  // paddle uses beta but mkldnn uses alpha for swish
  if (algorithm == mkldnn::algorithm::eltwise_swish) {
    std::swap(alpha, beta);
A
Adam 已提交
92
  } else if (algorithm == dnnl::algorithm::eltwise_bounded_relu) {
93
    alpha = ctx.Attr<float>("threshold");
94
  }
A
Adam 已提交
95

Y
Yihua Xu 已提交
96
  PADDLE_ENFORCE(
97 98 99 100
      x->dims().size() >= 1 || x->dims().size() <= 6,
      platform::errors::Unimplemented("Input dimension size can be 1, 2, 3, 4, "
                                      "5, or 6, but now the dimension size is",
                                      x->dims().size()));
Y
Yihua Xu 已提交
101

102
  bool is_inplaced = x->IsSharedBufferWith(*y);
A
Adam 已提交
103
  auto src_tz = framework::vectorize<int64_t>(x->dims());
104

105
  auto src_format = src_tz.size() == 2 ? MKLDNNMemoryFormat::nc : x->format();
106

107
  platform::ActivationMKLDNNHandler<T> handler(
108
      src_tz, algorithm, alpha, beta, src_format, dev_ctx, ctx.GetPlace(),
109
      ctx.InputName("X"), is_inplaced);
110

111
  auto src_memory_p = handler.AcquireSrcMemory(x);
112
  auto dst_memory_p = is_inplaced ? src_memory_p : handler.AcquireDstMemory(y);
A
Adam 已提交
113
  auto activation_p = handler.AcquireForwardPrimitive();
114

115
  auto &astream = paddle::platform::MKLDNNDeviceContext::tls().get_stream();
A
Adam 已提交
116 117 118
  activation_p->execute(astream, {{MKLDNN_ARG_FROM, *src_memory_p},
                                  {MKLDNN_ARG_TO, *dst_memory_p}});
  astream.wait();
119

120
  y->set_layout(DataLayout::kMKLDNN);
121
  y->set_format(GetMKLDNNFormat(*dst_memory_p));
122 123
}

124 125
template <typename T>
void eltwise_grad(const framework::ExecutionContext &ctx,
A
Adam 已提交
126
                  mkldnn::algorithm algorithm) {
127 128
  auto &dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();

129
  const auto *x = ctx.Input<Tensor>("X");
130 131
  const auto *diff_y = ctx.Input<Tensor>(framework::GradVarName("Out"));
  auto *diff_x = ctx.Output<Tensor>(framework::GradVarName("X"));
132

133 134
  float alpha = ctx.HasAttr("alpha") ? ctx.Attr<float>("alpha") : 0;
  float beta = ctx.HasAttr("beta") ? ctx.Attr<float>("beta") : 0;
135 136 137 138

  // paddle uses beta but mkldnn uses alpha for swish
  if (algorithm == mkldnn::algorithm::eltwise_swish) {
    std::swap(alpha, beta);
A
Adam 已提交
139
  } else if (algorithm == dnnl::algorithm::eltwise_bounded_relu) {
140
    alpha = ctx.Attr<float>("threshold");
141
  }
A
Adam 已提交
142

A
Adam 已提交
143
  auto diff_dst_tz = framework::vectorize<int64_t>(diff_y->dims());
K
Krzysztof Binias 已提交
144

145 146
  // diff_dst and src dims should be the same
  auto src_format =
147
      diff_dst_tz.size() == 2 ? MKLDNNMemoryFormat::nc : x->format();
148

149
  auto diff_y_format =
150
      diff_dst_tz.size() == 2 ? MKLDNNMemoryFormat::nc : diff_y->format();
151

152 153
  platform::ActivationMKLDNNHandler<T> handler(
      diff_dst_tz, algorithm, alpha, beta, src_format, diff_y_format, dev_ctx,
H
hong 已提交
154
      ctx.GetPlace(), ctx.InputName("X"));
155

156 157 158
  auto src_memory_p = handler.AcquireBackwardSrcMemory(x);
  auto diff_dst_memory_p = handler.AcquireDiffDstMemory(diff_y);
  auto diff_src_memory_p = handler.AcquireDiffSrcMemory(diff_x);
A
Adam 已提交
159 160
  auto activation_backward_p = handler.AcquireBackwardPrimitive();

161
  auto &astream = paddle::platform::MKLDNNDeviceContext::tls().get_stream();
A
Adam 已提交
162 163 164 165 166
  activation_backward_p->execute(astream,
                                 {{MKLDNN_ARG_SRC, *src_memory_p},
                                  {MKLDNN_ARG_DIFF_DST, *diff_dst_memory_p},
                                  {MKLDNN_ARG_DIFF_SRC, *diff_src_memory_p}});
  astream.wait();
167

168
  diff_x->set_layout(DataLayout::kMKLDNN);
169
  diff_x->set_format(GetMKLDNNFormat(*diff_src_memory_p));
170 171 172 173
}

template <typename T, mkldnn::algorithm algorithm>
struct MKLDNNActivationFunc : public BaseActivationFunctor<T> {
174
  void operator()(const framework::ExecutionContext &ctx) const {
175 176 177 178 179 180
    eltwise_forward<T>(ctx, algorithm);
  }
};

template <typename T, mkldnn::algorithm algorithm>
struct MKLDNNActivationGradFunc : public BaseActivationFunctor<T> {
181
  void operator()(const framework::ExecutionContext &ctx) const {
182 183 184 185
    eltwise_grad<T>(ctx, algorithm);
  }
};

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

template <typename T>
struct GeluMKLDNNGradFunctor : public BaseActivationFunctor<T> {
  void operator()(const framework::ExecutionContext &ctx) const {
    const bool approximate = ctx.Attr<bool>("approximate");
    if (approximate) {
      eltwise_grad<T>(ctx, mkldnn::algorithm::eltwise_gelu_tanh);
    } else {
      eltwise_grad<T>(ctx, mkldnn::algorithm::eltwise_gelu_erf);
    }
  }
};

210
template <typename T>
T
tensor-tang 已提交
211
using ReluMKLDNNFunctor =
212 213
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_relu>;

A
Adam 已提交
214 215 216 217
template <typename T>
using Relu6MKLDNNFunctor =
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_bounded_relu>;

218 219 220 221
template <typename T>
using SwishMKLDNNFunctor =
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_swish>;

222 223 224 225
template <typename T>
using SigmoidMKLDNNFunctor =
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_logistic>;

226
template <typename T>
T
tensor-tang 已提交
227
using TanhMKLDNNFunctor =
228 229 230
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_tanh>;

template <typename T>
T
tensor-tang 已提交
231
using SqrtMKLDNNFunctor =
232 233 234
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_sqrt>;

template <typename T>
T
tensor-tang 已提交
235
using AbsMKLDNNFunctor =
236 237 238
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_abs>;

template <typename T>
T
tensor-tang 已提交
239
using ReluMKLDNNGradFunctor =
240 241
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_relu>;

A
Adam 已提交
242 243 244 245
template <typename T>
using Relu6MKLDNNGradFunctor =
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_bounded_relu>;

246 247 248 249
template <typename T>
using SwishMKLDNNGradFunctor =
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_swish>;

250 251 252 253
template <typename T>
using SigmoidMKLDNNGradFunctor =
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_logistic>;

254
template <typename T>
T
tensor-tang 已提交
255
using TanhMKLDNNGradFunctor =
256 257 258
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_tanh>;

template <typename T>
T
tensor-tang 已提交
259
using SqrtMKLDNNGradFunctor =
260 261 262
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_sqrt>;

template <typename T>
T
tensor-tang 已提交
263
using AbsMKLDNNGradFunctor =
264 265 266 267 268 269 270 271 272 273 274 275 276
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_abs>;
}  // 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>>);

277 278 279 280 281 282 283 284 285 286
#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,                  \
      ops::MKLDNNActivationGradKernel<ops::grad_functor<float>>);

287 288
#define FOR_EACH_MKLDNN_KERNEL_FUNCTOR(__macro)                     \
  __macro(relu, ReluMKLDNNFunctor, ReluMKLDNNGradFunctor);          \
A
Adam 已提交
289
  __macro(relu6, Relu6MKLDNNFunctor, Relu6MKLDNNGradFunctor);       \
290 291 292 293 294
  __macro(leaky_relu, ReluMKLDNNFunctor, ReluMKLDNNGradFunctor);    \
  __macro(swish, SwishMKLDNNFunctor, SwishMKLDNNGradFunctor);       \
  __macro(sigmoid, SigmoidMKLDNNFunctor, SigmoidMKLDNNGradFunctor); \
  __macro(tanh, TanhMKLDNNFunctor, TanhMKLDNNGradFunctor);          \
  __macro(sqrt, SqrtMKLDNNFunctor, SqrtMKLDNNGradFunctor);          \
T
tensor-tang 已提交
295
  __macro(abs, AbsMKLDNNFunctor, AbsMKLDNNGradFunctor);
296 297

FOR_EACH_MKLDNN_KERNEL_FUNCTOR(REGISTER_ACTIVATION_MKLDNN_KERNEL);
298 299
REGISTER_ACTIVATION_MKLDNN_BF16_KERNEL(gelu, GeluMKLDNNFunctor,
                                       GeluMKLDNNGradFunctor);