activation_op.h 14.4 KB
Newer Older
1
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
2

L
Luo Tao 已提交
3 4 5 6 7 8 9 10 11
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. */
Q
qijun 已提交
12 13

#pragma once
D
dzhwinter 已提交
14
#include <glog/logging.h>
15

Y
Yihua Xu 已提交
16
#include <algorithm>
17
#include <cmath>
18
#include <memory>
D
dzhwinter 已提交
19 20
#include <string>
#include <unordered_set>
21 22
#include <utility>
#include <vector>
C
Clementine 已提交
23 24 25 26
#ifndef _USE_MATH_DEFINES
#define _USE_MATH_DEFINES
#endif

27
#include <type_traits>
28

Y
Yi Wang 已提交
29 30
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
31
#include "paddle/fluid/framework/tensor_util.h"
32
#include "paddle/fluid/platform/enforce.h"
33
#include "paddle/fluid/platform/float16.h"
34
#include "paddle/phi/kernels/funcs/blas/blas.h"
35

36 37
#include "paddle/phi/kernels/funcs/activation_functor.h"

Q
qijun 已提交
38 39 40
namespace paddle {
namespace operators {

41 42
using framework::To32BitIndex;

43
using ActBwdOpFwdDeps = phi::funcs::ActBwdOpFwdDeps;
44

C
chengduo 已提交
45 46 47 48 49 50
/* The following operator can be used to process SelectedRows, because the
 * output of those operator for zero is zero too.
 */
static std::unordered_set<std::string> CanBeUsedBySelectedRows = {
    "abs", "abs_grad", "square", "square_grad", "sqrt", "sqrt_grad"};

51
inline void ExtractActivationTensor(const framework::ExecutionContext& context,
52 53
                                    const phi::DenseTensor** X,
                                    phi::DenseTensor** Out) {
54 55
  auto x_var = context.InputVar("X");
  auto out_var = context.OutputVar("Out");
56 57 58 59 60
  PADDLE_ENFORCE_NOT_NULL(x_var,
                          platform::errors::NotFound(
                              "Cannot get input Variable X, variable name = %s",
                              context.InputName("X")));
  PADDLE_ENFORCE_NOT_NULL(
61 62 63 64
      out_var,
      platform::errors::NotFound(
          "Cannot get output Variable Out, variable name = %s",
          context.OutputName("Out")));
H
hong 已提交
65
  if (CanBeUsedBySelectedRows.count(context.Type())) {
66 67 68 69
    *X = paddle::framework::GetLoDTensorOrSelectedRowsValueFromVar(*x_var);
    *Out = paddle::framework::GetMutableLoDTensorOrSelectedRowsValueFromVar(
        out_var);
  } else {
70 71
    *X = context.Input<phi::DenseTensor>("X");
    *Out = context.Output<phi::DenseTensor>("Out");
72 73
  }

74 75 76 77 78
  PADDLE_ENFORCE_NOT_NULL(
      *Out,
      platform::errors::NotFound("Cannot get the tensor from the Variable "
                                 "Output(Out), variable name = %s",
                                 context.OutputName("Out")));
79 80
}

81
template <ActBwdOpFwdDeps kDepValue>
82
inline void ExtractActivationGradTensor(
83
    const framework::ExecutionContext& context,
84 85 86 87
    const phi::DenseTensor** X,
    const phi::DenseTensor** Out,
    const phi::DenseTensor** dOut,
    phi::DenseTensor** dX) {
88 89
  auto out_grad_var = context.InputVar(framework::GradVarName("Out"));
  auto x_grad_var = context.OutputVar(framework::GradVarName("X"));
90 91
  const framework::Variable* out_var = nullptr;

92 93
  if (static_cast<int>(kDepValue) &
      static_cast<int>(ActBwdOpFwdDeps::kDepOut)) {
94
    out_var = context.InputVar("Out");
95
    PADDLE_ENFORCE_NOT_NULL(
96 97 98 99
        out_var,
        platform::errors::NotFound(
            "Cannot get input Variable Out, variable name = %s",
            context.InputName("Out")));
100 101 102
  }

  PADDLE_ENFORCE_NOT_NULL(
103 104 105 106 107
      out_grad_var,
      platform::errors::NotFound(
          "Cannot get input Variable %s, variable name = %s",
          framework::GradVarName("Out"),
          context.InputName(framework::GradVarName("Out"))));
108
  PADDLE_ENFORCE_NOT_NULL(
109 110 111 112 113
      x_grad_var,
      platform::errors::NotFound(
          "Cannot get output Variable %s, variable name = %s",
          framework::GradVarName("X"),
          context.OutputName(framework::GradVarName("X"))));
114

H
hong 已提交
115
  if (CanBeUsedBySelectedRows.count(context.Type())) {
116 117 118 119
    *dOut = paddle::framework::GetLoDTensorOrSelectedRowsValueFromVar(
        *out_grad_var);
    *dX = paddle::framework::GetMutableLoDTensorOrSelectedRowsValueFromVar(
        x_grad_var);
120 121 122 123 124 125 126 127

    if (out_var) {
      *Out =
          paddle::framework::GetLoDTensorOrSelectedRowsValueFromVar(*out_var);
    } else {
      *Out = *dOut;  // fake out
    }

128
  } else {
129 130 131
    *Out = context.Input<phi::DenseTensor>("Out");
    *dOut = context.Input<phi::DenseTensor>(framework::GradVarName("Out"));
    *dX = context.Output<phi::DenseTensor>(framework::GradVarName("X"));
132 133

    if (out_var) {
134
      *Out = &(out_var->Get<phi::DenseTensor>());
135 136 137
    } else {
      *Out = *dOut;  // fake out
    }
138
  }
139

140 141 142 143 144
  PADDLE_ENFORCE_NOT_NULL(*dX,
                          platform::errors::NotFound(
                              "Cannot get the tensor from the Variable "
                              "Output(Out), variable name = %s",
                              context.OutputName(framework::GradVarName("X"))));
145

146
  if (static_cast<int>(kDepValue) & static_cast<int>(ActBwdOpFwdDeps::kDepX)) {
C
chengduo 已提交
147
    auto x_var = context.InputVar("X");
148 149 150 151 152
    PADDLE_ENFORCE_NOT_NULL(
        x_var,
        platform::errors::NotFound("Cannot get the tensor from the "
                                   "Variable Input(X), variable name = %s",
                                   context.InputName("X")));
H
hong 已提交
153
    if (CanBeUsedBySelectedRows.count(context.Type())) {
154
      *X = paddle::framework::GetLoDTensorOrSelectedRowsValueFromVar(*x_var);
C
chengduo 已提交
155
    } else {
156
      *X = context.Input<phi::DenseTensor>("X");
C
chengduo 已提交
157
    }
158
  } else {
H
hong 已提交
159
    VLOG(10) << " Inplace activation of Op : " << context.Type();
160 161 162
    *X = *dX;
  }
}
C
chengduo 已提交
163

164 165 166 167 168
template <typename DeviceContext, typename Functor>
class ActivationKernel
    : public framework::OpKernel<typename Functor::ELEMENT_TYPE> {
 public:
  using T = typename Functor::ELEMENT_TYPE;
C
chengduo 已提交
169

170
  void Compute(const framework::ExecutionContext& context) const override {
171 172
    const phi::DenseTensor* X = nullptr;
    phi::DenseTensor* Out = nullptr;
173
    ExtractActivationTensor(context, &X, &Out);
C
chengduo 已提交
174
    Out->mutable_data<T>(context.GetPlace());
175

176 177 178 179
    auto x = framework::EigenVector<T>::Flatten(
        GET_DATA_SAFELY(X, "Input", "X", "Activation"));
    auto out = framework::EigenVector<T>::Flatten(
        GET_DATA_SAFELY(Out, "Output", "Out", "Activation"));
Q
QI JUN 已提交
180 181
    auto* place =
        context.template device_context<DeviceContext>().eigen_device();
Q
qijun 已提交
182
    Functor functor;
183 184 185 186 187

    auto attrs = functor.GetAttrs();
    for (auto& attr : attrs) {
      *attr.second = context.Attr<float>(attr.first);
    }
188 189 190 191 192 193 194 195
    // use 32bit index to speed up computation
    bool use_32bit_index = out.size() < Eigen::NumTraits<int>::highest();
    bool is_gpu_place = platform::is_gpu_place(context.GetPlace());
    if (use_32bit_index && is_gpu_place) {
      functor(*place, To32BitIndex(x), To32BitIndex(out));
    } else {
      functor(*place, x, out);
    }
Q
qijun 已提交
196 197 198
  }
};

Q
QI JUN 已提交
199
template <typename DeviceContext, typename Functor>
200 201
class ActivationGradKernel
    : public framework::OpKernel<typename Functor::ELEMENT_TYPE> {
Q
qijun 已提交
202
 public:
203
  using T = typename Functor::ELEMENT_TYPE;
Q
qijun 已提交
204
  void Compute(const framework::ExecutionContext& context) const override {
205 206
    const phi::DenseTensor *X, *Out, *dOut;
    phi::DenseTensor* dX = nullptr;
207
    X = Out = dOut = nullptr;
208 209
    ExtractActivationGradTensor<Functor::FwdDeps()>(
        context, &X, &Out, &dOut, &dX);
Q
qijun 已提交
210
    dX->mutable_data<T>(context.GetPlace());
211 212 213 214 215 216 217 218
    auto dout = framework::EigenVector<T>::Flatten(
        GET_DATA_SAFELY(dOut, "Input", "Out@GRAD", "ActivationGrad"));
    auto out = framework::EigenVector<T>::Flatten(
        GET_DATA_SAFELY(Out, "Input", "Out", "ActivationGrad"));
    auto dx = framework::EigenVector<T>::Flatten(
        GET_DATA_SAFELY(dX, "Input", "X@GRAD", "ActivationGrad"));
    auto x = framework::EigenVector<T>::Flatten(
        GET_DATA_SAFELY(X, "Input", "X", "ActivationGrad"));
Q
QI JUN 已提交
219 220
    auto* place =
        context.template device_context<DeviceContext>().eigen_device();
Q
qijun 已提交
221
    Functor functor;
222 223 224 225
    auto attrs = functor.GetAttrs();
    for (auto& attr : attrs) {
      *attr.second = context.Attr<float>(attr.first);
    }
226 227 228 229
    // use 32bit index to speed up computation
    bool use_32bit_index = out.size() < Eigen::NumTraits<int>::highest();
    bool is_gpu_place = platform::is_gpu_place(context.GetPlace());
    if (use_32bit_index && is_gpu_place) {
230 231 232 233
      functor(*place,
              To32BitIndex(x),
              To32BitIndex(out),
              To32BitIndex(dout),
234 235 236 237
              To32BitIndex(dx));
    } else {
      functor(*place, x, out, dout, dx);
    }
Q
qijun 已提交
238 239 240
  }
};

241 242 243 244 245 246 247 248 249
template <typename T>
struct BaseActivationFunctor {
  using ELEMENT_TYPE = T;

  using AttrPair = std::vector<std::pair<const char*, float*>>;

  AttrPair GetAttrs() { return AttrPair(); }
};

250 251 252 253 254 255
#define USE_PHI_FUNCTOR(name)                         \
  template <typename T>                               \
  using name##Functor = phi::funcs::name##Functor<T>; \
  template <typename T>                               \
  using name##GradFunctor = phi::funcs::name##GradFunctor<T>;

256 257 258 259 260 261 262 263
#define USE_PHI_DOUBLE_GRAD_FUNCTOR(name) \
  template <typename T>                   \
  using name##GradGradFunctor = phi::funcs::name##GradGradFunctor<T>;

#define USE_PHI_TRIPLE_GRAD_FUNCTOR(name) \
  template <typename T>                   \
  using name##TripleGradFunctor = phi::funcs::name##TripleGradFunctor<T>;

264 265 266 267 268
template <typename T>
using BReluFunctor = phi::funcs::HardTanhFunctor<T>;
template <typename T>
using BReluGradFunctor = phi::funcs::HardTanhGradFunctor<T>;

269
USE_PHI_FUNCTOR(Tanh)
270
USE_PHI_FUNCTOR(Relu6)
271 272
USE_PHI_FUNCTOR(LeakyRelu)
USE_PHI_DOUBLE_GRAD_FUNCTOR(LeakyRelu)
Y
YuanRisheng 已提交
273 274
USE_PHI_FUNCTOR(HardShrink)
USE_PHI_FUNCTOR(ELU)
Y
YuanRisheng 已提交
275 276
USE_PHI_FUNCTOR(Sigmoid)
USE_PHI_FUNCTOR(HardSigmoid)
Y
YuanRisheng 已提交
277 278 279
USE_PHI_FUNCTOR(Swish)
USE_PHI_FUNCTOR(HardSwish)
USE_PHI_FUNCTOR(Pow)
280 281
USE_PHI_FUNCTOR(Mish)
USE_PHI_FUNCTOR(STanh)
Y
YuanRisheng 已提交
282 283 284

template <typename T>
using ELUGradNegativeAlphaFunctor = phi::funcs::ELUGradNegativeAlphaFunctor<T>;
285

Y
YuanRisheng 已提交
286 287 288 289 290 291 292 293 294 295 296 297
template <typename T>
using RoundFunctor = phi::funcs::RoundFunctor<T>;

template <typename T>
using FloorFunctor = phi::funcs::FloorFunctor<T>;

template <typename T>
using CeilFunctor = phi::funcs::CeilFunctor<T>;

template <typename T>
using ZeroGradFunctor = phi::funcs::ZeroGradFunctor<T>;

298
template <typename T>
299
using ELUGradNegativeAlphaFunctor = phi::funcs::ELUGradNegativeAlphaFunctor<T>;
R
ronnywang 已提交
300

Q
qijun 已提交
301
// relu(x) = max(x, 0)
302 303

template <typename T>
304 305 306
using ReluCPUFunctor = phi::funcs::ReluCPUFunctor<T>;
template <typename T>
using ReluGradFunctor = phi::funcs::ReluGradFunctor<T>;
Q
qijun 已提交
307

Q
qijun 已提交
308
template <typename T>
309
using ReluGradGradFunctor = phi::funcs::ReluGradGradFunctor<T>;
310

311 312
template <typename T>
using ReluCUDAFunctor = phi::funcs::ReluCUDAFunctor<T>;
Q
qijun 已提交
313

314 315 316 317 318 319
template <typename T>
struct SoftReluFunctor : public BaseActivationFunctor<T> {
  float threshold;
  typename BaseActivationFunctor<T>::AttrPair GetAttrs() {
    return {{"threshold", &threshold}};
  }
320

F
fengjiayi 已提交
321 322
  template <typename Device, typename X, typename Out>
  void operator()(Device d, X x, Out out) const {
Y
Yu Yang 已提交
323 324
    auto tmp = static_cast<T>(threshold);
    auto temp = x.cwiseMax(-tmp).cwiseMin(tmp);
F
fengjiayi 已提交
325
    out.device(d) = (static_cast<T>(1) + temp.exp()).log();
326 327 328
  }
};

329 330 331 332 333 334
template <typename T>
struct SoftReluGradFunctor : public BaseActivationFunctor<T> {
  float threshold;
  typename BaseActivationFunctor<T>::AttrPair GetAttrs() {
    return {{"threshold", &threshold}};
  }
335 336 337 338
  template <typename Device,
            typename X,
            typename Out,
            typename dOut,
F
fengjiayi 已提交
339 340
            typename dX>
  void operator()(Device d, X x, Out out, dOut dout, dX dx) const {
Y
Yu Yang 已提交
341
    auto tmp = static_cast<T>(threshold);
Z
Zeng Jinle 已提交
342
    auto temp = ((out > -tmp) * (out < tmp)).template cast<T>();
F
fengjiayi 已提交
343
    dx.device(d) = dout * (static_cast<T>(1) - (-out).exp()) * temp;
344
  }
345

346 347 348
  static constexpr ActBwdOpFwdDeps FwdDeps() {
    return ActBwdOpFwdDeps::kDepOut;
  }
349 350
};

Z
Zhong Hui 已提交
351 352 353
template <typename T>
struct AbsGradGradFunctor : public BaseActivationFunctor<T> {
  template <typename Device>
354
  void operator()(const Device& dev,
355 356 357 358 359 360
                  const phi::DenseTensor* X,
                  const phi::DenseTensor* Out,
                  const phi::DenseTensor* ddX,
                  phi::DenseTensor* ddOut,
                  phi::DenseTensor* dOut,
                  phi::DenseTensor* dX) const {
Z
Zhong Hui 已提交
361 362 363 364 365 366 367 368 369 370 371
    auto* d = dev.eigen_device();
    auto ddx = framework::EigenVector<T>::Flatten(
        GET_DATA_SAFELY(ddX, "Input", "DDX", "AbsGradGrad"));
    auto x = framework::EigenVector<T>::Flatten(
        GET_DATA_SAFELY(X, "Input", "X", "AbsGradGrad"));
    if (ddOut) {
      auto ddout = framework::EigenVector<T>::Flatten(
          GET_DATA_SAFELY(ddOut, "Output", "DDOut", "AbsGradGrad"));
      ddout.device(*d) = ddx * x.sign();
    }
  }
372
  static constexpr ActBwdOpFwdDeps FwdDeps() { return ActBwdOpFwdDeps::kDepX; }
373 374
};

375 376
// TODO(dengkaipeng): double gradient calculation for Square/Sqrt need
// DOut(dy) as input(not output), tensor extraction is different from
377
// others. Impliment extraction kernel separately here.
378
inline void ExtractDoubleGradTensorWithInputDOut(
379
    const framework::ExecutionContext& ctx,
380 381 382 383 384
    const phi::DenseTensor** X,
    const phi::DenseTensor** ddX,
    phi::DenseTensor** dX,
    const phi::DenseTensor** dOut,
    phi::DenseTensor** ddOut) {
385 386 387
  // extract ddX(output), ddOut(input)
  auto ddx_var = ctx.InputVar("DDX");
  auto ddo_var = ctx.OutputVar("DDOut");
388
  PADDLE_ENFORCE_NOT_NULL(
389 390 391 392
      ddx_var,
      platform::errors::NotFound(
          "Cannot get input Variable Out, variable name = %s",
          ctx.InputName("DDX")));
393
  *ddX = ctx.Input<phi::DenseTensor>("DDX");
394
  if (ddo_var) {
395
    *ddOut = ctx.Output<phi::DenseTensor>("DDOut");
396
  }
397 398 399 400 401
  PADDLE_ENFORCE_NOT_NULL(
      ddX,
      platform::errors::NotFound(
          "Cannot get the tensor from the Variable DDX, variable name = %s",
          ctx.OutputName("DDX")));
402 403 404

  // extract x(input), dx(output)
  auto x_var = ctx.InputVar("X");
405
  PADDLE_ENFORCE_NOT_NULL(
406 407 408 409
      x_var,
      platform::errors::NotFound(
          "Cannot get input Variable Out, variable name = %s",
          ctx.InputName("X")));
410
  auto dx_var = ctx.OutputVar("DX");
411
  *X = ctx.Input<phi::DenseTensor>("X");
412
  if (dx_var) {
413
    *dX = ctx.Output<phi::DenseTensor>("DX");
414 415 416 417 418
  }

  // extract dOut(input)
  auto dout_var = ctx.InputVar("DOut");
  if (dout_var) {
419
    *dOut = ctx.Input<phi::DenseTensor>("DOut");
420 421 422
  }
}

Q
qijun 已提交
423 424
}  // namespace operators
}  // namespace paddle
425

426 427
#define FOR_EACH_ACTIVATION_OP(__macro) \
  __macro(soft_relu, SoftRelu, SoftReluFunctor, SoftReluGradFunctor);