activation_mkldnn_op.cc 10.0 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 18 19 20

namespace paddle {
namespace operators {

21 22 23 24 25 26 27 28
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;
29

30 31 32 33 34 35
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");
36 37 38 39 40 41
    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"));
42 43 44 45 46

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

48 49 50 51 52 53
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"));
54
    PADDLE_ENFORCE_EQ(diff_y->layout(), DataLayout::kMKLDNN,
55 56
                      platform::errors::InvalidArgument(
                          "Wrong layout set for Input OutGrad tensor"));
A
Adam 已提交
57
    PADDLE_ENFORCE_NE(diff_y->format(), MKLDNNMemoryFormat::undef,
58 59
                      platform::errors::InvalidArgument(
                          "Wrong format set for Input OutGrad tensor"));
60 61 62 63 64 65 66 67

    Functor functor;
    functor(ctx);
  }
};

template <typename T>
void eltwise_forward(const framework::ExecutionContext &ctx,
A
Adam 已提交
68
                     mkldnn::algorithm algorithm) {
69 70 71
  PADDLE_ENFORCE_EQ(platform::is_cpu_place(ctx.GetPlace()), true,
                    paddle::platform::errors::PreconditionNotMet(
                        "Operator DNNL eletwise_forward must use CPUPlace"));
72 73
  auto &dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();

74 75
  const auto *x = ctx.Input<Tensor>("X");
  auto *y = ctx.Output<Tensor>("Out");
76

77 78 79 80 81 82
  T alpha = ctx.HasAttr("alpha") ? ctx.Attr<T>("alpha") : 0;
  T beta = ctx.HasAttr("beta") ? ctx.Attr<T>("beta") : 0;

  // paddle uses beta but mkldnn uses alpha for swish
  if (algorithm == mkldnn::algorithm::eltwise_swish) {
    std::swap(alpha, beta);
A
Adam 已提交
83 84
  } else if (algorithm == dnnl::algorithm::eltwise_bounded_relu) {
    alpha = ctx.Attr<T>("threshold");
85
  }
A
Adam 已提交
86

Y
Yihua Xu 已提交
87 88
  PADDLE_ENFORCE(
      x->dims().size() == 2 || x->dims().size() == 3 || x->dims().size() == 4,
89
      platform::errors::Unimplemented("Input dim must be with 2, 3 or 4"));
Y
Yihua Xu 已提交
90

A
Adam 已提交
91
  auto src_tz = framework::vectorize<int64_t>(x->dims());
92

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

95
  platform::ActivationMKLDNNHandler<T> handler(
96 97
      src_tz, algorithm, alpha, beta, src_format, dev_ctx, ctx.GetPlace(),
      ctx.InputName("X"));
98

99
  auto src_memory_p = handler.AcquireSrcMemory(x);
100 101
  auto dst_memory_p =
      x->IsSharedBufferWith(*y) ? src_memory_p : handler.AcquireDstMemory(y);
A
Adam 已提交
102
  auto activation_p = handler.AcquireForwardPrimitive();
103

A
Adam 已提交
104 105 106 107
  mkldnn::stream astream(dev_ctx.GetEngine());
  activation_p->execute(astream, {{MKLDNN_ARG_FROM, *src_memory_p},
                                  {MKLDNN_ARG_TO, *dst_memory_p}});
  astream.wait();
108

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

113 114
template <typename T>
void eltwise_grad(const framework::ExecutionContext &ctx,
A
Adam 已提交
115
                  mkldnn::algorithm algorithm) {
116 117
  auto &dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();

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

122 123 124 125 126 127
  T alpha = ctx.HasAttr("alpha") ? ctx.Attr<T>("alpha") : 0;
  T beta = ctx.HasAttr("beta") ? ctx.Attr<T>("beta") : 0;

  // paddle uses beta but mkldnn uses alpha for swish
  if (algorithm == mkldnn::algorithm::eltwise_swish) {
    std::swap(alpha, beta);
A
Adam 已提交
128 129
  } else if (algorithm == dnnl::algorithm::eltwise_bounded_relu) {
    alpha = ctx.Attr<T>("threshold");
130
  }
A
Adam 已提交
131

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

134 135
  // diff_dst and src dims should be the same
  auto src_format =
136
      diff_dst_tz.size() == 2 ? MKLDNNMemoryFormat::nc : x->format();
137

138
  auto diff_y_format =
139
      diff_dst_tz.size() == 2 ? MKLDNNMemoryFormat::nc : diff_y->format();
140

141 142
  platform::ActivationMKLDNNHandler<T> handler(
      diff_dst_tz, algorithm, alpha, beta, src_format, diff_y_format, dev_ctx,
H
hong 已提交
143
      ctx.GetPlace(), ctx.InputName("X"));
144

145 146 147
  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 已提交
148 149 150 151 152 153 154 155
  auto activation_backward_p = handler.AcquireBackwardPrimitive();

  mkldnn::stream astream(dev_ctx.GetEngine());
  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();
156

157
  diff_x->set_layout(DataLayout::kMKLDNN);
158
  diff_x->set_format(GetMKLDNNFormat(*diff_src_memory_p));
159 160 161 162
}

template <typename T, mkldnn::algorithm algorithm>
struct MKLDNNActivationFunc : public BaseActivationFunctor<T> {
163
  void operator()(const framework::ExecutionContext &ctx) const {
164 165 166 167 168 169
    eltwise_forward<T>(ctx, algorithm);
  }
};

template <typename T, mkldnn::algorithm algorithm>
struct MKLDNNActivationGradFunc : public BaseActivationFunctor<T> {
170
  void operator()(const framework::ExecutionContext &ctx) const {
171 172 173 174
    eltwise_grad<T>(ctx, algorithm);
  }
};

A
Adam 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
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);
    }
  }
};

199
template <typename T>
T
tensor-tang 已提交
200
using ReluMKLDNNFunctor =
201 202
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_relu>;

A
Adam 已提交
203 204 205 206
template <typename T>
using Relu6MKLDNNFunctor =
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_bounded_relu>;

207 208 209 210
template <typename T>
using SwishMKLDNNFunctor =
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_swish>;

211 212 213 214
template <typename T>
using SigmoidMKLDNNFunctor =
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_logistic>;

215
template <typename T>
T
tensor-tang 已提交
216
using TanhMKLDNNFunctor =
217 218 219
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_tanh>;

template <typename T>
T
tensor-tang 已提交
220
using SqrtMKLDNNFunctor =
221 222 223
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_sqrt>;

template <typename T>
T
tensor-tang 已提交
224
using AbsMKLDNNFunctor =
225 226 227
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_abs>;

template <typename T>
T
tensor-tang 已提交
228
using ReluMKLDNNGradFunctor =
229 230
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_relu>;

A
Adam 已提交
231 232 233 234
template <typename T>
using Relu6MKLDNNGradFunctor =
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_bounded_relu>;

235 236 237 238
template <typename T>
using SwishMKLDNNGradFunctor =
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_swish>;

239 240 241 242
template <typename T>
using SigmoidMKLDNNGradFunctor =
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_logistic>;

243
template <typename T>
T
tensor-tang 已提交
244
using TanhMKLDNNGradFunctor =
245 246 247
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_tanh>;

template <typename T>
T
tensor-tang 已提交
248
using SqrtMKLDNNGradFunctor =
249 250 251
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_sqrt>;

template <typename T>
T
tensor-tang 已提交
252
using AbsMKLDNNGradFunctor =
253 254 255 256 257 258 259 260 261 262 263 264 265
    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>>);

266 267
#define FOR_EACH_MKLDNN_KERNEL_FUNCTOR(__macro)                     \
  __macro(relu, ReluMKLDNNFunctor, ReluMKLDNNGradFunctor);          \
A
Adam 已提交
268
  __macro(relu6, Relu6MKLDNNFunctor, Relu6MKLDNNGradFunctor);       \
269 270 271 272 273 274
  __macro(leaky_relu, ReluMKLDNNFunctor, ReluMKLDNNGradFunctor);    \
  __macro(gelu, GeluMKLDNNFunctor, GeluMKLDNNGradFunctor);          \
  __macro(swish, SwishMKLDNNFunctor, SwishMKLDNNGradFunctor);       \
  __macro(sigmoid, SigmoidMKLDNNFunctor, SigmoidMKLDNNGradFunctor); \
  __macro(tanh, TanhMKLDNNFunctor, TanhMKLDNNGradFunctor);          \
  __macro(sqrt, SqrtMKLDNNFunctor, SqrtMKLDNNGradFunctor);          \
T
tensor-tang 已提交
275
  __macro(abs, AbsMKLDNNFunctor, AbsMKLDNNGradFunctor);
276 277

FOR_EACH_MKLDNN_KERNEL_FUNCTOR(REGISTER_ACTIVATION_MKLDNN_KERNEL);