activation_op.cc 47.5 KB
Newer Older
1
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
Q
qijun 已提交
2

L
Luo Tao 已提交
3 4 5
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
Q
qijun 已提交
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
Q
qijun 已提交
8

L
Luo Tao 已提交
9 10 11 12 13
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 已提交
14

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/activation_op.h"
16

T
tink2123 已提交
17
#include <memory>
D
dzhwinter 已提交
18
#include <string>
19
#include <type_traits>
T
tink2123 已提交
20
#include <unordered_map>
21
#include <vector>
22

23
#include "paddle/fluid/framework/op_version_registry.h"
24
#include "paddle/fluid/operators/common_infer_shape_functions.h"
25
#include "paddle/fluid/operators/mkldnn/mkldnn_activation_op.h"
26
#include "paddle/phi/backends/dynload/port.h"
Q
qijun 已提交
27

A
Adam 已提交
28 29
DECLARE_bool(use_mkldnn);

Q
qijun 已提交
30 31 32
namespace paddle {
namespace operators {

33 34
template <typename GradFunctor>
static constexpr bool CanInplaceAct() {
35 36
  return GradFunctor::FwdDeps() == ActBwdOpFwdDeps::kDepOut ||
         GradFunctor::FwdDeps() == ActBwdOpFwdDeps::kNoDeps;
37 38
}

39 40 41 42 43 44 45 46 47 48 49 50 51 52
#define REGISTER_ACTIVATION_OP_MAKER(OP_NAME, OP_COMMENT)           \
  class OP_NAME##OpMaker                                            \
      : public ::paddle::framework::OpProtoAndCheckerMaker {        \
   public:                                                          \
    void Make() override {                                          \
      AddInput("X",                                                 \
               "Input of " #OP_NAME                                 \
               " operator, an N-D Tensor, with data type float32, " \
               "float64 or float16.");                              \
      AddOutput("Out",                                              \
                "Output of " #OP_NAME                               \
                " operator, a Tensor with shape same as input.");   \
      AddComment(OP_COMMENT);                                       \
    }                                                               \
D
dzhwinter 已提交
53
  }
D
dzhwinter 已提交
54

H
hong 已提交
55 56
template <ActBwdOpFwdDeps kDepValue, typename T>
class ActivationGradOpMaker : public framework::SingleGradOpMaker<T> {
57
 public:
H
hong 已提交
58
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
59 60

 protected:
61
  void Apply(GradOpPtr<T> op) const override {
H
hong 已提交
62 63 64 65
    op->SetType(this->ForwardOpType() + "_grad");
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetAttrMap(this->Attrs());
66

A
Adam 已提交
67 68
    if ((static_cast<int>(kDepValue) &
         static_cast<int>(ActBwdOpFwdDeps::kDepX)) ||
69 70
        FLAGS_use_mkldnn ||
        (op->HasAttr("use_mkldnn") &&
R
Ruibiao Chen 已提交
71
         PADDLE_GET_CONST(bool, op->GetAttr("use_mkldnn")))) {
72
      op->SetInput("X", this->Input("X"));  // x
73 74 75 76
    }

    if (static_cast<int>(kDepValue) &
        static_cast<int>(ActBwdOpFwdDeps::kDepOut)) {
77
      op->SetInput("Out", this->Output("Out"));  // out
78
    }
D
dzhwinter 已提交
79
  }
80
};
D
dzhwinter 已提交
81

82 83 84
framework::OpKernelType GetKernelType(const framework::ExecutionContext& ctx,
                                      const framework::OperatorWithKernel& oper,
                                      const std::string& name) {
85
  auto data_type = oper.IndicateVarDataType(ctx, name);
86 87 88 89 90 91 92 93 94 95 96
  // FIXME(liuwei1031) temporarily disable the code to unblock users
  // TODO(liuwei1031) figure out the reason behind
  // https://github.com/PaddlePaddle/Paddle/issues/16096
  // and re-enable this in the future
  // #ifdef PADDLE_WITH_CUDA
  //   auto it1 = oper.Attrs().find("use_cudnn");
  //   if (it1 != oper.Attrs().end() && platform::CanCUDNNBeUsed(ctx)) {
  //     library = framework::LibraryType::kCUDNN;
  //   }
  // #endif
  return framework::OpKernelType(data_type, ctx.GetPlace());
97 98
}

Q
qijun 已提交
99 100 101 102
class ActivationOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

103
  void InferShape(framework::InferShapeContext* ctx) const override {
104
    ctx->ShareDim("X", /*->*/ "Out");
F
fengjiayi 已提交
105
    ctx->ShareLoD("X", /*->*/ "Out");
Q
qijun 已提交
106
  }
107

108
 protected:
109 110 111 112
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return GetKernelType(ctx, *this, "X");
  }
Q
qijun 已提交
113 114
};

C
chengduo 已提交
115 116 117
class ActivationOpInferVarType
    : public framework::PassInDtypeAndVarTypeToOutput {
 protected:
118
  std::unordered_map<std::string, std::string>& GetInputOutputWithSameType()
C
chengduo 已提交
119
      const override {
120 121
    static std::unordered_map<std::string, std::string> m{{"X", /*->*/ "Out"}};
    return m;
122 123 124
  }
};

Q
qijun 已提交
125 126 127 128
class ActivationOpGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

129
  void InferShape(framework::InferShapeContext* ctx) const override {
130 131 132
    auto out_grad_name = framework::GradVarName("Out");
    ctx->ShareDim(out_grad_name, framework::GradVarName("X"));
    ctx->ShareLoD(out_grad_name, framework::GradVarName("X"));
Q
qijun 已提交
133
  }
134

135
 protected:
136 137
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
138
    return GetKernelType(ctx, *this, framework::GradVarName("Out"));
139
  }
Q
qijun 已提交
140 141
};

D
dzhwinter 已提交
142
UNUSED constexpr char SigmoidDoc[] = R"DOC(
143
Sigmoid Activation
K
Kexin Zhao 已提交
144

145
$$out = \frac{1}{1 + e^{-x}}$$
K
Kexin Zhao 已提交
146

D
dzhwinter 已提交
147
)DOC";
Q
qijun 已提交
148

D
dzhwinter 已提交
149
UNUSED constexpr char ReluDoc[] = R"DOC(
K
kexinzhao 已提交
150
Relu Activation Operator.
K
Kexin Zhao 已提交
151

152
$$out = \max(x, 0)$$
K
Kexin Zhao 已提交
153

D
dzhwinter 已提交
154
)DOC";
K
Kexin Zhao 已提交
155

D
dzhwinter 已提交
156
UNUSED constexpr char TanhDoc[] = R"DOC(
K
kexinzhao 已提交
157
Tanh Activation Operator.
K
Kexin Zhao 已提交
158

Q
update  
qiaolongfei 已提交
159
$$out = \\frac{e^{x} - e^{-x}}{e^{x} + e^{-x}}$$
K
Kexin Zhao 已提交
160

D
dzhwinter 已提交
161
)DOC";
162

D
dzhwinter 已提交
163
UNUSED constexpr char TanhShrinkDoc[] = R"DOC(
K
kexinzhao 已提交
164
TanhShrink Activation Operator.
K
Kexin Zhao 已提交
165

Y
Yan Chunwei 已提交
166
$$out = x - \\frac{e^{x} - e^{-x}}{e^{x} + e^{-x}}$$
K
Kexin Zhao 已提交
167

D
dzhwinter 已提交
168
)DOC";
K
Kexin Zhao 已提交
169

D
dzhwinter 已提交
170
UNUSED constexpr char SqrtDoc[] = R"DOC(
K
kexinzhao 已提交
171
Sqrt Activation Operator.
K
Kexin Zhao 已提交
172

N
Noel 已提交
173
$$out=\\sqrt{x}=x^{1/2}$$
174

175 176
**Note**:
  input value must be greater than or equal to zero.
K
Kexin Zhao 已提交
177

D
dzhwinter 已提交
178
)DOC";
179

Z
zhoukunsheng 已提交
180 181 182 183 184
UNUSED constexpr char RsqrtDoc[] = R"DOC(
Rsqrt Activation Operator.

Please make sure input is legal in case of numeric errors.

185
$$out = \\frac{1}{\\sqrt{x}}$$
Z
zhoukunsheng 已提交
186 187 188

)DOC";

D
dzhwinter 已提交
189
UNUSED constexpr char LogDoc[] = R"DOC(
K
kexinzhao 已提交
190
Log Activation Operator.
K
Kexin Zhao 已提交
191

192
$$out = \ln(x)$$
K
Kexin Zhao 已提交
193 194 195

Natural logarithm of x.

D
dzhwinter 已提交
196 197
)DOC";

D
dzhwinter 已提交
198
UNUSED constexpr char SquareDoc[] = R"DOC(
199
The OP square each elements of the inputs.
D
dzhwinter 已提交
200

201
$$out = x^2$$
202

D
dzhwinter 已提交
203 204
)DOC";

D
dzhwinter 已提交
205
UNUSED constexpr char SoftsignDoc[] = R"DOC(
D
dzhwinter 已提交
206 207
Softsign Activation Operator.

208
$$out = \\frac{x}{1 + \|x\|}$$
D
dzhwinter 已提交
209 210 211 212

)DOC";

class LeakyReluOpMaker : public framework::OpProtoAndCheckerMaker {
213
 public:
Y
Yu Yang 已提交
214
  void Make() override {
W
Wilber 已提交
215 216 217 218 219 220 221 222
    AddInput("X",
             "A LoDTensor or Tensor representing preactivation values. Must be "
             "one of the following types: float32, float64.");
    AddOutput(
        "Out",
        "A LoDTensor or Tensor with the same type and size as that of x.");
    AddAttr<float>("alpha", "Slope of the activation function at x < 0.")
        .SetDefault(0.02f);
K
Kexin Zhao 已提交
223
    AddComment(R"DOC(
D
dzhwinter 已提交
224
LeakyRelu Activation Operator.
K
Kexin Zhao 已提交
225

W
Wilber 已提交
226
$$out = \max(x, \alpha * x)$$
K
Kexin Zhao 已提交
227 228

)DOC");
229 230 231
  }
};

232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
class SoftplusOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X",
             "Input of Softplus operator, an N-D Tensor, with data type "
             "float32, float64 or float16.");
    AddOutput(
        "Out",
        "Output of Softplus operator, a Tensor with shape same as input.");
    AddAttr<float>("beta", "The value of beta for Softplus.").SetDefault(1.0f);
    AddAttr<float>("threshold", "The value of threshold for Softplus.")
        .SetDefault(20.0f);
    AddComment(R"DOC(
:strong:`Softplus Activation Operator`

..  math::
    out = \frac{1}{\beta} * \log(1 + \exp(\beta * x)) \\
    \text{For numerical stability, the implementation reverts to the linear function when :}\,x \times \beta > threshold.

)DOC");
  }
};

D
dzhwinter 已提交
255
class SoftShrinkOpMaker : public framework::OpProtoAndCheckerMaker {
K
kexinzhao 已提交
256
 public:
Y
Yu Yang 已提交
257
  void Make() override {
D
dzhwinter 已提交
258 259 260
    AddInput("X", "Input of Softshrink operator");
    AddOutput("Out", "Output of Softshrink operator");
    AddAttr<float>("lambda", "non-negative offset").SetDefault(0.5f);
K
Kexin Zhao 已提交
261
    AddComment(R"DOC(
262 263 264
:strong:`Softshrink Activation Operator`

..  math::
265
    out = \begin{cases}
266 267 268 269
         x - \lambda, \text{if } x > \lambda \\
         x + \lambda, \text{if } x < -\lambda \\
         0,  \text{otherwise}
         \end{cases}
K
Kexin Zhao 已提交
270 271

)DOC");
K
kexinzhao 已提交
272 273 274
  }
};

275 276
class BReluOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
277
  void Make() override {
278 279 280 281 282 283
    AddInput("X",
             "The input is a multi-dimensional Tensor. The data type is "
             "float32, float64.");
    AddOutput("Out",
              "The output is a multi-dimensional Tensor which has same "
              "dimension and data type as the ``X``.");
284 285 286 287
    AddAttr<float>("t_min", "The min marginal value of BRelu")
        .SetDefault(static_cast<float>(0));
    AddAttr<float>("t_max", "The max marginal value of BRelu")
        .SetDefault(static_cast<float>(24));
K
Kexin Zhao 已提交
288
    AddComment(R"DOC(
K
kexinzhao 已提交
289
BRelu Activation Operator.
K
Kexin Zhao 已提交
290

291
$$out = \min(\max(x, t_{min}), t_{max})$$
K
Kexin Zhao 已提交
292 293

)DOC");
294 295 296 297 298
  }
};

class SoftReluOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
299
  void Make() override {
300
    AddInput("X", "Input of SoftRelu operator");
F
fengjiayi 已提交
301
    AddOutput("Out", "Output of SoftRelu operator");
302 303
    AddAttr<float>("threshold", "The threshold value of SoftRelu")
        .SetDefault(40.0f);
K
Kexin Zhao 已提交
304
    AddComment(R"DOC(
K
kexinzhao 已提交
305
SoftRelu Activation Operator.
K
Kexin Zhao 已提交
306

307
$$out = \ln(1 + \exp(\max(\min(x, threshold), -threshold)))$$
K
Kexin Zhao 已提交
308 309

)DOC");
310 311 312
  }
};

313 314
class ELUOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
315
  void Make() override {
316 317 318 319 320 321
    AddInput("X",
             "The input is a multi-dimensional Tensor. The data type is "
             "float32 or float64.");
    AddOutput("Out",
              "The output is a multi-dimensional Tensor which has same "
              "dimension and data type as the ``x``.");
322
    AddAttr<float>("alpha", "The alpha value of ELU").SetDefault(1.0f);
323
    AddComment(R"DOC(
K
kexinzhao 已提交
324
ELU Activation Operator.
K
Kexin Zhao 已提交
325 326 327 328

Applies the following element-wise computation on the input according to
https://arxiv.org/abs/1511.07289.

329
$$out = \max(0, x) + \min(0, \alpha * (e^x - 1))$$
K
Kexin Zhao 已提交
330 331

)DOC");
332 333 334
  }
};

Z
zhupengyang 已提交
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
template <typename T>
class ELUGradOpMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
  void Apply(GradOpPtr<T> op) const override {
    op->SetType("elu_grad");
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetInput("Out", this->Output("Out"));
    op->SetInput("X", this->Input("X"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetAttrMap(this->Attrs());
  }
};

351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
class CELUOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X",
             "The input is a multi-dimensional Tensor. The data type is "
             "float32 or float64.");
    AddOutput("Out",
              "The output is a multi-dimensional Tensor which has same "
              "dimension and data type as the ``x``.");
    AddAttr<float>("alpha", "The alpha value of CELU").SetDefault(1.0f);
    AddComment(R"DOC(
CELU Activation Operator.

Applies the following element-wise computation on the input according to
https://arxiv.org/abs/1704.07483.

$$out = \max(0, x) + \min(0, \alpha * (e^(x/\alpha) - 1))$$

)DOC");
  }
};

373 374
class Relu6OpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
375
  void Make() override {
Z
zhupengyang 已提交
376 377 378 379 380 381 382 383
    AddInput("X",
             "Input of relu6 operator, an N-D Tensor, "
             "with data type float32, float64.");
    AddOutput(
        "Out",
        "Output of relu6 operator, a Tensor with the same shape as input.");
    AddAttr<float>("threshold",
                   "The threshold value of Relu6. Default is 6.0. ")
384
        .SetDefault(6.0f);
K
Kexin Zhao 已提交
385
    AddComment(R"DOC(
K
kexinzhao 已提交
386
Relu6 Activation Operator.
K
Kexin Zhao 已提交
387

388
$$out = \min(\max(0, x), threshold)$$
K
Kexin Zhao 已提交
389 390

)DOC");
391 392 393
  }
};

394 395
class PowOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
396
  void Make() override {
397
    AddInput("X", "Input of Pow operator");
398 399 400 401 402
    AddInput("FactorTensor",
             "(Tensor<float>, optional). If provided, pow will use this"
             "The shape of FactorTensor MUST BE [1]."
             "it has higher priority than attr(factor).")
        .AsDispensable();
F
fengjiayi 已提交
403
    AddOutput("Out", "Output of Pow operator");
404
    AddAttr<float>("factor", "The exponential factor of Pow").SetDefault(1.0f);
K
Kexin Zhao 已提交
405
    AddComment(R"DOC(
K
kexinzhao 已提交
406
Pow Activation Operator.
K
Kexin Zhao 已提交
407

408
$$out = x^{factor}$$
K
Kexin Zhao 已提交
409 410

)DOC");
411 412 413 414 415
  }
};

class STanhOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
416
  void Make() override {
417 418
    AddInput("X",
             "Input of STanh operator."
N
Noel 已提交
419
             " A Tensor with type float32, float64.");
420 421 422
    AddOutput("Out", "Output of STanh operator. A Tensor with type float32.");
    AddAttr<float>("scale_a", "The scale parameter of a for the input. ")
        .SetDefault(0.67f);
423 424
    AddAttr<float>("scale_b", "The scale parameter of b for the input")
        .SetDefault(1.7159f);
K
Kexin Zhao 已提交
425
    AddComment(R"DOC(
K
kexinzhao 已提交
426
STanh Activation Operator.
K
Kexin Zhao 已提交
427

Y
Yan Chunwei 已提交
428
$$out = b * \\frac{e^{a * x} - e^{-a * x}}{e^{a * x} + e^{-a * x}}$$
K
Kexin Zhao 已提交
429 430

)DOC");
Q
qijun 已提交
431 432 433
  }
};

434 435
class ThresholdedReluOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
436
  void Make() override {
437
    AddInput("X", "Input of ThresholdedRelu operator");
F
fengjiayi 已提交
438
    AddOutput("Out", "Output of ThresholdedRelu operator");
Y
yuyang18 已提交
439 440
    AddAttr<float>("threshold",
                   "The threshold location of activation. [default 1.0].")
441
        .SetDefault(1.0f);
K
Kexin Zhao 已提交
442
    AddComment(R"DOC(
Y
yuyang18 已提交
443
:strong:`ThresholdedRelu activation operator`
K
Kexin Zhao 已提交
444

Y
yuyang18 已提交
445
..  math::
K
Kexin Zhao 已提交
446

Y
yuyang18 已提交
447
    out = \begin{cases}
Y
yuyang18 已提交
448
             x,  \text{if } x > threshold \\
Y
yuyang18 已提交
449 450
             0,  \text{otherwise}
          \end{cases}
K
Kexin Zhao 已提交
451
)DOC");
452 453 454
  }
};

A
Abhinav Arora 已提交
455 456
class SwishOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
457
  void Make() override {
A
Abhinav Arora 已提交
458
    AddInput("X", "Input of Swish operator");
F
fengjiayi 已提交
459
    AddOutput("Out", "Output of Swish operator");
A
Abhinav Arora 已提交
460 461 462 463
    AddAttr<float>("beta", "Constant beta of swish operator").SetDefault(1.0f);
    AddComment(R"DOC(
Swish Activation Operator.

464
$$out = \\frac{x}{1 + e^{- \beta \ x}}$$
A
Abhinav Arora 已提交
465 466 467 468 469

)DOC");
  }
};

470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
class MishOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X", "Input of Mish operator");
    AddOutput("Out", "Output of Mish operator");
    AddAttr<float>(
        "threshold",
        "Constant threshold of softplus in Mish operator. Approximate value "
        "of softplus will be used if absolute value of input is greater than "
        ":attr:`threshold`")
        .SetDefault(20.f);
    AddComment(R"DOC(
Mish Activation Operator.

..  math::
    softplus(x) = \begin{cases}
            x, \text{if } x > \text{threshold} \\
            \ln(1 + e^{x}),  \text{otherwise}
          \end{cases}

    out = x * \tanh(softplus(x))

)DOC");
  }
};

H
huangjun12 已提交
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
class HardSwishOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X", "Input of HardSwish operator");
    AddOutput("Out", "Output of HardSwish operator");
    AddAttr<float>("threshold", "The threshold parameter of HardSwish operator")
        .SetDefault(6.0f);
    AddAttr<float>("scale", "The scale parameter of HardSwish operator")
        .SetDefault(6.0f);
    AddAttr<float>("offset", "The offset parameter of HardSwish operator")
        .SetDefault(3.0f);
    AddComment(R"DOC(
HardSwish Activation Operator.

The hard version of swish(https://arxiv.org/pdf/1905.02244.pdf).

512
$$out = \frac{x * (min(max(0, x+offset), threshold))}{scale}$$
H
huangjun12 已提交
513 514 515 516 517 518 519 520 521

The threshold and scale should be positive. The offset can be either positive or negative.
The default parameters are set according to the above reference.
It is recommended to use the defaults for this activation.

)DOC");
  }
};

D
dzhwinter 已提交
522 523 524 525 526
REGISTER_ACTIVATION_OP_MAKER(Sigmoid, SigmoidDoc);
REGISTER_ACTIVATION_OP_MAKER(Relu, ReluDoc);
REGISTER_ACTIVATION_OP_MAKER(Tanh, TanhDoc);
REGISTER_ACTIVATION_OP_MAKER(TanhShrink, TanhShrinkDoc);
REGISTER_ACTIVATION_OP_MAKER(Sqrt, SqrtDoc);
Z
zhoukunsheng 已提交
527
REGISTER_ACTIVATION_OP_MAKER(Rsqrt, RsqrtDoc);
D
dzhwinter 已提交
528 529 530 531
REGISTER_ACTIVATION_OP_MAKER(Log, LogDoc);
REGISTER_ACTIVATION_OP_MAKER(Square, SquareDoc);
REGISTER_ACTIVATION_OP_MAKER(Softsign, SoftsignDoc);

532
template <ActBwdOpFwdDeps kDepValue>
533 534 535 536 537
class ActivationOpDoubleGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
538 539
    if (static_cast<int>(kDepValue) &
        static_cast<int>(ActBwdOpFwdDeps::kDepX)) {
540
      if (ctx->HasOutput("DX")) {
541 542 543
        ctx->ShareDim("X", "DX");
        ctx->ShareLoD("X", "DX");
      }
544
      if (ctx->HasOutput("DDOut")) {
545 546 547
        ctx->ShareDim("X", "DDOut");
        ctx->ShareLoD("X", "DDOut");
      }
548
    }
549 550
    if (static_cast<int>(kDepValue) &
        static_cast<int>(ActBwdOpFwdDeps::kDepOut)) {
551
      if (ctx->HasOutput("DOut")) {
552 553 554
        ctx->ShareDim("Out", "DOut");
        ctx->ShareLoD("Out", "DOut");
      }
555 556 557 558
      if (ctx->HasOutput("DDOut")) {
        ctx->ShareDim("Out", "DDOut");
        ctx->ShareLoD("Out", "DDOut");
      }
559 560 561 562
      if (ctx->HasOutput("DOutNew")) {
        ctx->ShareDim("Out", "DOutNew");
        ctx->ShareLoD("Out", "DOutNew");
      }
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
    }
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return GetKernelType(ctx, *this, "DDX");
  }
};

template <ActBwdOpFwdDeps kDepValue>
class ActivationOpDoubleGrad2 : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
579 580
    if (static_cast<int>(kDepValue) &
        static_cast<int>(ActBwdOpFwdDeps::kDepX)) {
581 582 583 584 585
      if (ctx->HasOutput("DDOut")) {
        ctx->ShareDim("X", "DDOut");
        ctx->ShareLoD("X", "DDOut");
      }
    }
586 587
    if (static_cast<int>(kDepValue) &
        static_cast<int>(ActBwdOpFwdDeps::kDepOut)) {
588
      if (ctx->HasOutput("DDOut")) {
589 590 591
        ctx->ShareDim("Out", "DDOut");
        ctx->ShareLoD("Out", "DDOut");
      }
592 593 594 595 596 597 598 599 600 601
    }
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return GetKernelType(ctx, *this, "DDX");
  }
};

602 603 604 605 606 607
template <ActBwdOpFwdDeps kDepValue>
class ActivationOpTripleGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
608 609
    if (static_cast<int>(kDepValue) &
        static_cast<int>(ActBwdOpFwdDeps::kDepX)) {
610 611 612 613 614 615 616 617 618
      if (ctx->HasOutput("DX")) {
        ctx->ShareDim("X", "DX");
        ctx->ShareLoD("X", "DX");
      }
      if (ctx->HasOutput("DDOut")) {
        ctx->ShareDim("X", "DDOut");
        ctx->ShareLoD("X", "DDOut");
      }
    }
619 620
    if (static_cast<int>(kDepValue) &
        static_cast<int>(ActBwdOpFwdDeps::kDepOut)) {
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
      if (ctx->HasOutput("D_DOut")) {
        ctx->ShareDim("Out", "D_DOut");
        ctx->ShareLoD("Out", "D_DOut");
      }
      if (ctx->HasOutput("D_OutNew")) {
        ctx->ShareDim("Out", "D_OutNew");
        ctx->ShareLoD("Out", "D_OutNew");
      }
      if (ctx->HasOutput("D_DDx")) {
        ctx->ShareDim("DDX", "D_DDx");
        ctx->ShareLoD("DDX", "D_DDx");
      }
    }
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return GetKernelType(ctx, *this, "DDX");
  }
};

643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
template <typename T>
class SigmoidDoubleGradMaker
    : public ::paddle::framework::SingleGradOpMaker<T> {
 public:
  using ::paddle::framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
  void Apply(GradOpPtr<T> op) const override {
    op->SetType("sigmoid_grad_grad");
    // input1: Out
    op->SetInput("Out", this->Input("Out"));
    // input2: ddx
    op->SetInput("DDX", this->OutputGrad(framework::GradVarName("X")));
    op->SetInput("DOut", this->Input(framework::GradVarName("Out")));
    op->SetAttrMap(this->Attrs());
    // output: ddy
    op->SetOutput("DOutNew", this->InputGrad("Out"));
    op->SetOutput("DDOut", this->InputGrad(framework::GradVarName("Out")));
  }
};

664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
template <typename T>
class SigmoidTripleGradMaker
    : public ::paddle::framework::SingleGradOpMaker<T> {
 public:
  using ::paddle::framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
  void Apply(GradOpPtr<T> op) const override {
    op->SetType("sigmoid_triple_grad");
    // Out, DDX, DOut, D_DDOut, D_DOut_New   // input
    // D_OutNew, D_DOut, D_DDx               // output
    // input1: Out
    op->SetInput("Out", this->Input("Out"));
    // input2: ddx
    op->SetInput("DDX", this->Input("DDX"));
    // input3: dout
    op->SetInput("DOut", this->Input("DOut"));
    // input4: d_ddout
    op->SetInput("D_DDOut", this->OutputGrad("DDOut"));
    // input5: d_dout_new
    op->SetInput("D_DOut_New", this->OutputGrad("DOutNew"));
    op->SetAttrMap(this->Attrs());

    // output: d_dOut, d_OutNew, d_ddx
    op->SetOutput("D_OutNew", this->InputGrad("Out"));
    op->SetOutput("D_DOut", this->InputGrad("DOut"));
    op->SetOutput("D_DDx", this->InputGrad("DDX"));
  }
};

694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
template <typename T>
class TanhDoubleGradMaker : public ::paddle::framework::SingleGradOpMaker<T> {
 public:
  using ::paddle::framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
  void Apply(GradOpPtr<T> op) const override {
    op->SetType("tanh_grad_grad");
    // input1: Out
    op->SetInput("Out", this->Input("Out"));
    // input2: ddx
    op->SetInput("DDX", this->OutputGrad(framework::GradVarName("X")));
    op->SetInput("DOut", this->Input(framework::GradVarName("Out")));
    op->SetAttrMap(this->Attrs());
    // output: ddy
    op->SetOutput("DOutNew", this->InputGrad("Out"));
    op->SetOutput("DDOut", this->InputGrad(framework::GradVarName("Out")));
  }
};

714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
template <typename T>
class TanhTripleGradMaker : public ::paddle::framework::SingleGradOpMaker<T> {
 public:
  using ::paddle::framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
  void Apply(GradOpPtr<T> op) const override {
    op->SetType("tanh_triple_grad");
    // Out, DDX, DOut, D_DDOut, D_DOut_New   // input
    // D_OutNew, D_DOut, D_DDx               // output
    // input1: Out
    op->SetInput("Out", this->Input("Out"));
    // input2: ddx
    op->SetInput("DDX", this->Input("DDX"));
    // input3: dout
    op->SetInput("DOut", this->Input("DOut"));
    // input4: d_ddout
    op->SetInput("D_DDOut", this->OutputGrad("DDOut"));
    // input5: d_dout_new
    op->SetInput("D_DOut_New", this->OutputGrad("DOutNew"));
    op->SetAttrMap(this->Attrs());

    // output: d_dOut, d_OutNew, d_ddx
    op->SetOutput("D_OutNew", this->InputGrad("Out"));
    op->SetOutput("D_DOut", this->InputGrad("DOut"));
    op->SetOutput("D_DDx", this->InputGrad("DDX"));
  }
};
742 743
// ReluGrad: dx = dy if y >= 0 else 0
// ReluGradGrad: ddy = ddx if y >= 0 else 0
H
hong 已提交
744 745
template <typename T>
class ReluDoubleGradMaker : public ::paddle::framework::SingleGradOpMaker<T> {
746
 public:
H
hong 已提交
747
  using ::paddle::framework::SingleGradOpMaker<T>::SingleGradOpMaker;
748 749

 protected:
750
  void Apply(GradOpPtr<T> op) const override {
751 752
    op->SetType("relu_grad_grad");
    // input1: Out
H
hong 已提交
753
    op->SetInput("Out", this->Input("Out"));
Q
qingqing01 已提交
754
    // input2: ddx
H
hong 已提交
755 756
    op->SetInput("DDX", this->OutputGrad(framework::GradVarName("X")));
    op->SetAttrMap(this->Attrs());
757
    // output: ddy
H
hong 已提交
758
    op->SetOutput("DDOut", this->InputGrad(framework::GradVarName("Out")));
759 760 761
  }
};

762 763
// leaky_relu Grad: dx=dy if x>=0 else alpha * dy
// leaky_relu GradGrad: ddy=ddx if x>=0 else alpha * ddx
H
hong 已提交
764
template <typename T>
765
class LeakyReluDoubleGradMaker
H
hong 已提交
766
    : public ::paddle::framework::SingleGradOpMaker<T> {
767
 public:
H
hong 已提交
768
  using ::paddle::framework::SingleGradOpMaker<T>::SingleGradOpMaker;
769 770

 protected:
771
  void Apply(GradOpPtr<T> op) const override {
772
    op->SetType("leaky_relu_grad_grad");
773 774
    // input1: X
    op->SetInput("X", this->Input("X"));
775
    // X@GRAD@GRAD: ddx
H
hong 已提交
776 777
    op->SetInput("DDX", this->OutputGrad(framework::GradVarName("X")));
    op->SetAttrMap(this->Attrs());
778
    // Out@GRAD@GRAD: ddy
H
hong 已提交
779
    op->SetOutput("DDOut", this->InputGrad(framework::GradVarName("Out")));
780 781 782
  }
};

D
Double_V 已提交
783 784 785 786 787 788 789 790
// elu grad: dx=dy if y>0 else alpha*dy*x.exp()
// elu gradgrad: ddx=ddy if y>0 else alpha*ddy*x.exp()
template <typename T>
class ELUDoubleGradMaker : public ::paddle::framework::SingleGradOpMaker<T> {
 public:
  using ::paddle::framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
791
  void Apply(GradOpPtr<T> op) const override {
D
Double_V 已提交
792 793 794 795 796 797 798 799 800 801 802 803 804 805
    op->SetType("elu_grad_grad");

    op->SetInput("X", this->Input("X"));
    op->SetInput("DOut", this->Input(framework::GradVarName("Out")));
    // X@GRAD@GRAD: ddx
    op->SetInput("DDX", this->OutputGrad(framework::GradVarName("X")));
    op->SetAttrMap(this->Attrs());

    // Out@GRAD@GRAD: ddy
    op->SetOutput("DX", this->InputGrad("X"));
    op->SetOutput("DDOut", this->InputGrad(framework::GradVarName("Out")));
  }
};

806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
// celu grad: dx=dy if y>0 else dy*(x/alpha).exp()
// celu gradgrad: ddx=ddy if y>0 else ddy*(x/alpha).exp()/alpha
template <typename T>
class CELUDoubleGradMaker : public ::paddle::framework::SingleGradOpMaker<T> {
 public:
  using ::paddle::framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
  void Apply(GradOpPtr<T> op) const override {
    op->SetType("celu_grad_grad");

    op->SetInput("X", this->Input("X"));
    op->SetInput("DOut", this->Input(framework::GradVarName("Out")));
    // X@GRAD@GRAD: ddx
    op->SetInput("DDX", this->OutputGrad(framework::GradVarName("X")));
    op->SetAttrMap(this->Attrs());

    // Out@GRAD@GRAD: ddy
    op->SetOutput("DX", this->InputGrad("X"));
    op->SetOutput("DDOut", this->InputGrad(framework::GradVarName("Out")));
  }
};

L
lvmengsi 已提交
829 830
// sqrt Grad: dx = 0.5 * dy / y
// sqrt GradGrad: ddy = 0.5 * ddx / y, dy = -1 * dx * ddx
H
hong 已提交
831 832
template <typename T>
class SqrtDoubleGradMaker : public ::paddle::framework::SingleGradOpMaker<T> {
L
lvmengsi 已提交
833
 public:
H
hong 已提交
834
  using ::paddle::framework::SingleGradOpMaker<T>::SingleGradOpMaker;
L
lvmengsi 已提交
835 836

 protected:
837
  void Apply(GradOpPtr<T> op) const override {
L
lvmengsi 已提交
838
    op->SetType("sqrt_grad_grad");
H
hong 已提交
839 840 841 842 843 844
    op->SetInput("Out", this->Input("Out"));
    op->SetInput("DX", this->Output(framework::GradVarName("X")));
    op->SetInput("DDX", this->OutputGrad(framework::GradVarName("X")));
    op->SetAttrMap(this->Attrs());
    op->SetOutput("DOut", this->InputGrad("Out"));
    op->SetOutput("DDOut", this->InputGrad(framework::GradVarName("Out")));
L
lvmengsi 已提交
845 846 847
  }
};

W
whs 已提交
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
// rsqrt Grad: dx = -0.5 * dy * y * y * y
// rsqrt GradGrad: ddy = -0.5 * ddx * y * y * y, dy = (3/y) * ddx
template <typename T>
class RsqrtDoubleGradMaker : public ::paddle::framework::SingleGradOpMaker<T> {
 public:
  using ::paddle::framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
  void Apply(GradOpPtr<T> op) const override {
    op->SetType("rsqrt_grad_grad");
    op->SetInput("Out", this->Input("Out"));
    op->SetInput("DX", this->Output(framework::GradVarName("X")));
    op->SetInput("DDX", this->OutputGrad(framework::GradVarName("X")));
    op->SetAttrMap(this->Attrs());
    op->SetOutput("DOut", this->InputGrad("Out"));
    op->SetOutput("DDOut", this->InputGrad(framework::GradVarName("Out")));
  }
};

867 868
// square Grad: dx=2x*dy
// square GradGrad: ddy=2x*ddx, dx=2dy*ddx
H
hong 已提交
869 870
template <typename T>
class SquareDoubleGradMaker : public ::paddle::framework::SingleGradOpMaker<T> {
871
 public:
H
hong 已提交
872
  using ::paddle::framework::SingleGradOpMaker<T>::SingleGradOpMaker;
873 874

 protected:
875
  void Apply(GradOpPtr<T> op) const override {
876
    op->SetType("square_grad_grad");
H
hong 已提交
877
    op->SetInput("X", this->Input("X"));
878
    // Out@GRAD: dy
H
hong 已提交
879
    op->SetInput("DOut", this->Input(framework::GradVarName("Out")));
880
    // X@GRAD@GRAD: ddx
H
hong 已提交
881
    op->SetInput("DDX", this->OutputGrad(framework::GradVarName("X")));
882

H
hong 已提交
883
    op->SetAttrMap(this->Attrs());
884 885

    // X@GRAD: dx
H
hong 已提交
886
    op->SetOutput("DX", this->InputGrad("X"));
887
    // Out@GRAD@GRAD: ddy
H
hong 已提交
888
    op->SetOutput("DDOut", this->InputGrad(framework::GradVarName("Out")));
889 890 891
  }
};

892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
// log Grad: dx = dout / x
// log Grad Grad: ddout = ddx / x; dx = -(dout / x) * (ddx / x)
template <typename T>
class LogDoubleGradMaker : public ::paddle::framework::SingleGradOpMaker<T> {
 public:
  using ::paddle::framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
  void Apply(GradOpPtr<T> op) const override {
    op->SetType("log_grad_grad");
    op->SetInput("X", this->Input("X"));
    // X@GRAD@GRAD: ddx
    op->SetInput("DDX", this->OutputGrad(framework::GradVarName("X")));
    op->SetInput("DOut", this->Input(framework::GradVarName("Out")));
    op->SetAttrMap(this->Attrs());
    // X@GRAD: dx
    op->SetOutput("DX", this->InputGrad("X"));
    // Out@GRAD@GRAD: ddy
    op->SetOutput("DDOut", this->InputGrad(framework::GradVarName("Out")));
  }
};

914
DECLARE_INPLACE_OP_INFERER(ActivationGradOpInplaceInferer,
915 916
                           {framework::GradVarName("Out"),  // dout
                            framework::GradVarName("X")});  // dx
917
DECLARE_INPLACE_OP_INFERER(ActivationDoubleGradOpInplaceInferer,
918
                           {"DDX", "DDOut"});
919 920
DECLARE_INPLACE_OP_INFERER(ActivationTripleGradOpInplaceInferer,
                           {"DDX", "D_DOut"});
921

H
hong 已提交
922 923
template <typename T>
class PowGradOpMaker : public framework::SingleGradOpMaker<T> {
924
 public:
H
hong 已提交
925
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
926 927

 protected:
928
  void Apply(GradOpPtr<T> op) const override {
929
    op->SetType("pow_grad");
H
hong 已提交
930 931 932 933 934
    op->SetInput("X", this->Input("X"));
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetInput("FactorTensor", this->Input("FactorTensor"));
    op->SetAttrMap(this->Attrs());
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
  }
};
class PowOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
    ctx->ShareDim("X", /*->*/ "Out");
    ctx->ShareLoD("X", /*->*/ "Out");
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return GetKernelType(ctx, *this, "X");
  }

  framework::OpKernelType GetKernelTypeForVar(
953
      const std::string& var_name,
954
      const phi::DenseTensor& tensor,
955 956 957 958
      const framework::OpKernelType& expected_kernel_type) const override {
    if (var_name == "FactorTensor") {
      return expected_kernel_type;
    }
959 960
    return framework::OpKernelType(
        expected_kernel_type.data_type_, tensor.place(), tensor.layout());
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
  }
};

class PowOpGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
    auto out_grad_name = framework::GradVarName("Out");
    ctx->ShareDim(out_grad_name, framework::GradVarName("X"));
    ctx->ShareLoD(out_grad_name, framework::GradVarName("X"));
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return GetKernelType(ctx, *this, framework::GradVarName("Out"));
  }

  framework::OpKernelType GetKernelTypeForVar(
981
      const std::string& var_name,
982
      const phi::DenseTensor& tensor,
983 984 985 986
      const framework::OpKernelType& expected_kernel_type) const override {
    if (var_name == "FactorTensor") {
      return expected_kernel_type;
    }
987 988
    return framework::OpKernelType(
        expected_kernel_type.data_type_, tensor.place(), tensor.layout());
989 990
  }
};
991
DECLARE_INPLACE_OP_INFERER(ActFwdInplaceInferer, {"X", "Out"});
Q
qijun 已提交
992 993 994 995
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
996
namespace plat = paddle::platform;
997

998 999
#define REGISTER_ACTIVATION_OP(KERNEL_TYPE, OP_NAME, functor, grad_functor) \
  REGISTER_OPERATOR(                                                        \
1000 1001 1002
      KERNEL_TYPE,                                                          \
      ops::ActivationOp,                                                    \
      ops::OP_NAME##OpMaker,                                                \
1003
      ops::ActivationOpInferVarType,                                        \
H
hong 已提交
1004 1005 1006 1007
      ops::ActivationGradOpMaker<ops::grad_functor<float>::FwdDeps(),       \
                                 paddle::framework::OpDesc>,                \
      ops::ActivationGradOpMaker<ops::grad_functor<float>::FwdDeps(),       \
                                 paddle::imperative::OpBase>,               \
1008
      std::conditional<ops::CanInplaceAct<ops::grad_functor<float>>(),      \
1009 1010 1011 1012
                       ops::ActFwdInplaceInferer,                           \
                       void>::type);                                        \
  REGISTER_OPERATOR(KERNEL_TYPE##_grad,                                     \
                    ops::ActivationOpGrad,                                  \
1013
                    ops::ActivationGradOpInplaceInferer);
1014

L
Leo Chen 已提交
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
#define REGISTER_ACTIVATION_CPU_KERNEL(                                     \
    act_type, op_name, functor, grad_functor)                               \
  REGISTER_OP_CPU_KERNEL(                                                   \
      act_type,                                                             \
      ops::ActivationKernel<phi::CPUContext, ops::functor<float>>,          \
      ops::ActivationKernel<phi::CPUContext, ops::functor<double>>);        \
  REGISTER_OP_CPU_KERNEL(                                                   \
      act_type##_grad,                                                      \
      ops::ActivationGradKernel<phi::CPUContext, ops::grad_functor<float>>, \
      ops::ActivationGradKernel<phi::CPUContext, ops::grad_functor<double>>);
1025

1026 1027
FOR_EACH_ACTIVATION_OP(REGISTER_ACTIVATION_OP);
FOR_EACH_ACTIVATION_OP(REGISTER_ACTIVATION_CPU_KERNEL);
1028

1029
REGISTER_ACTIVATION_OP(brelu, BRelu, BReluFunctor, BReluGradFunctor);
1030 1031 1032 1033
REGISTER_ACTIVATION_OP(thresholded_relu,
                       ThresholdedRelu,
                       ThresholdedReluFunctor,
                       ThresholdedReluGradFunctor);
1034
REGISTER_ACTIVATION_OP(relu6, Relu6, Relu6Functor, Relu6GradFunctor);
1035 1036 1037
REGISTER_ACTIVATION_OP(softshrink,
                       SoftShrink,
                       SoftShrinkFunctor,
Y
YuanRisheng 已提交
1038
                       SoftShrinkGradFunctor);
1039 1040 1041
REGISTER_ACTIVATION_OP(tanh_shrink,
                       TanhShrink,
                       TanhShrinkFunctor,
Y
YuanRisheng 已提交
1042
                       TanhShrinkGradFunctor);
1043 1044 1045 1046
REGISTER_ACTIVATION_OP(softsign,
                       Softsign,
                       SoftsignFunctor,
                       SoftsignGradFunctor);
1047 1048 1049
REGISTER_ACTIVATION_OP(softplus,
                       Softplus,
                       SoftplusFunctor,
1050 1051 1052
                       SoftplusGradFunctor);
REGISTER_ACTIVATION_OP(mish, Mish, MishFunctor, MishGradFunctor);
REGISTER_ACTIVATION_OP(stanh, STanh, STanhFunctor, STanhGradFunctor);
1053 1054 1055
REGISTER_ACTIVATION_OP(hard_swish,
                       HardSwish,
                       HardSwishFunctor,
Y
YuanRisheng 已提交
1056 1057
                       HardSwishGradFunctor);
REGISTER_ACTIVATION_OP(swish, Swish, SwishFunctor, SwishGradFunctor);
1058

1059 1060 1061 1062
/* ==========================    sigmoid register  =============================
 */
// 1. Register Sigmoid Operator
REGISTER_OPERATOR(
1063 1064 1065
    sigmoid,
    ops::ActivationOp,
    ops::SigmoidOpMaker,
1066 1067 1068 1069 1070 1071
    ops::ActivationOpInferVarType,
    ops::ActivationGradOpMaker<ops::SigmoidGradFunctor<float>::FwdDeps(),
                               paddle::framework::OpDesc>,
    ops::ActivationGradOpMaker<ops::SigmoidGradFunctor<float>::FwdDeps(),
                               paddle::imperative::OpBase>,
    std::conditional<ops::CanInplaceAct<ops::SigmoidGradFunctor<float>>(),
1072 1073
                     ops::ActFwdInplaceInferer,
                     void>::type);
1074 1075

// 2. Register Sigmoid Grad Operator
1076 1077
REGISTER_OPERATOR(sigmoid_grad,
                  ops::ActivationOpGrad,
1078 1079
                  ops::ActivationGradOpInplaceInferer,
                  ops::SigmoidDoubleGradMaker<paddle::framework::OpDesc>,
1080
                  ops::SigmoidDoubleGradMaker<paddle::imperative::OpBase>);
1081 1082 1083 1084

// 3. Register Sigmoid DoubleGrad Operator
REGISTER_OPERATOR(
    sigmoid_grad_grad,
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
    ops::ActivationOpDoubleGrad<ops::SigmoidGradGradFunctor<float>::FwdDeps()>,
    ops::ActivationDoubleGradOpInplaceInferer,
    ops::SigmoidTripleGradMaker<paddle::framework::OpDesc>,
    ops::SigmoidTripleGradMaker<paddle::imperative::OpBase>);

// 4. Register Sigmoid TripleGrad Operator
REGISTER_OPERATOR(sigmoid_triple_grad,
                  ops::ActivationOpTripleGrad<
                      ops::SigmoidTripleGradFunctor<float>::FwdDeps()>,
                  ops::ActivationTripleGradOpInplaceInferer);
1095 1096 1097

/* ========================================================================== */

1098 1099
/* ==========================    tanh register  ============================= */
REGISTER_OPERATOR(
1100 1101 1102 1103
    tanh,
    ops::ActivationOp,
    ops::TanhOpMaker,
    ops::ActivationOpInferVarType,
1104 1105 1106 1107 1108
    ops::ActivationGradOpMaker<ops::TanhGradFunctor<float>::FwdDeps(),
                               paddle::framework::OpDesc>,
    ops::ActivationGradOpMaker<ops::TanhGradFunctor<float>::FwdDeps(),
                               paddle::imperative::OpBase>,
    std::conditional<ops::CanInplaceAct<ops::TanhGradFunctor<float>>(),
1109 1110 1111 1112
                     ops::ActFwdInplaceInferer,
                     void>::type);
REGISTER_OPERATOR(tanh_grad,
                  ops::ActivationOpGrad,
1113 1114 1115 1116 1117 1118
                  ops::ActivationGradOpInplaceInferer,
                  ops::TanhDoubleGradMaker<paddle::framework::OpDesc>,
                  ops::TanhDoubleGradMaker<paddle::imperative::OpBase>)
REGISTER_OPERATOR(
    tanh_grad_grad,
    ops::ActivationOpDoubleGrad<ops::TanhGradFunctor<float>::FwdDeps()>,
1119 1120 1121 1122 1123 1124 1125 1126
    ops::ActivationDoubleGradOpInplaceInferer,
    ops::TanhTripleGradMaker<paddle::framework::OpDesc>,
    ops::TanhTripleGradMaker<paddle::imperative::OpBase>);

REGISTER_OPERATOR(
    tanh_triple_grad,
    ops::ActivationOpTripleGrad<ops::TanhTripleGradFunctor<float>::FwdDeps()>,
    ops::ActivationTripleGradOpInplaceInferer);
1127 1128 1129

/* ========================================================================== */

1130
/* ==========================    relu register  ============================= */
1131
REGISTER_OPERATOR(
1132 1133 1134 1135
    relu,
    ops::ActivationOp,
    ops::ReluOpMaker,
    ops::ActivationOpInferVarType,
H
hong 已提交
1136 1137 1138 1139
    ops::ActivationGradOpMaker<ops::ReluGradFunctor<float>::FwdDeps(),
                               paddle::framework::OpDesc>,
    ops::ActivationGradOpMaker<ops::ReluGradFunctor<float>::FwdDeps(),
                               paddle::imperative::OpBase>,
1140
    ops::ActFwdInplaceInferer);
1141 1142
REGISTER_OPERATOR(relu_grad,
                  ops::ActivationOpGrad,
1143
                  ops::ActivationGradOpInplaceInferer,
H
hong 已提交
1144 1145
                  ops::ReluDoubleGradMaker<paddle::framework::OpDesc>,
                  ops::ReluDoubleGradMaker<paddle::imperative::OpBase>);
1146 1147
REGISTER_OPERATOR(
    relu_grad_grad,
1148
    ops::ActivationOpDoubleGrad2<ops::ReluGradFunctor<float>::FwdDeps()>,
1149
    ops::ActivationDoubleGradOpInplaceInferer);
1150

1151
/* ========================================================================== */
1152

1153
/* ======================== leaky relu register  ============================ */
1154
REGISTER_OPERATOR(
1155 1156 1157
    leaky_relu,
    ops::ActivationOp,
    ops::LeakyReluOpMaker,
1158
    ops::ActivationOpInferVarType,
H
hong 已提交
1159 1160 1161 1162
    ops::ActivationGradOpMaker<ops::LeakyReluGradFunctor<float>::FwdDeps(),
                               paddle::framework::OpDesc>,
    ops::ActivationGradOpMaker<ops::LeakyReluGradFunctor<float>::FwdDeps(),
                               paddle::imperative::OpBase>,
1163
    ops::ActFwdInplaceInferer);
1164 1165
REGISTER_OPERATOR(leaky_relu_grad,
                  ops::ActivationOpGrad,
1166
                  ops::ActivationGradOpInplaceInferer,
H
hong 已提交
1167 1168
                  ops::LeakyReluDoubleGradMaker<paddle::framework::OpDesc>,
                  ops::LeakyReluDoubleGradMaker<paddle::imperative::OpBase>);
1169 1170
REGISTER_OPERATOR(
    leaky_relu_grad_grad,
1171
    ops::ActivationOpDoubleGrad2<ops::LeakyReluGradFunctor<float>::FwdDeps()>,
1172
    ops::ActivationDoubleGradOpInplaceInferer);
1173 1174 1175

/* ========================================================================== */

D
Double_V 已提交
1176
/* ========================    elu  register     ============================ */
1177 1178 1179
REGISTER_OPERATOR(elu,
                  ops::ActivationOp,
                  ops::ELUOpMaker,
Z
zhupengyang 已提交
1180 1181 1182 1183
                  ops::ActivationOpInferVarType,
                  ops::ELUGradOpMaker<paddle::framework::OpDesc>,
                  ops::ELUGradOpMaker<paddle::imperative::OpBase>,
                  ops::ActFwdInplaceInferer);
1184 1185
REGISTER_OPERATOR(elu_grad,
                  ops::ActivationOpGrad,
1186
                  ops::ActivationGradOpInplaceInferer,
D
Double_V 已提交
1187 1188 1189 1190 1191
                  ops::ELUDoubleGradMaker<paddle::framework::OpDesc>,
                  ops::ELUDoubleGradMaker<paddle::imperative::OpBase>);
REGISTER_OPERATOR(
    elu_grad_grad,
    ops::ActivationOpDoubleGrad<ops::ELUGradFunctor<float>::FwdDeps()>,
1192
    ops::ActivationDoubleGradOpInplaceInferer);
D
Double_V 已提交
1193 1194 1195

/* ========================================================================== */

1196 1197 1198
/* ========================    celu  register     ============================
 */
REGISTER_OPERATOR(
1199 1200 1201 1202
    celu,
    ops::ActivationOp,
    ops::CELUOpMaker,
    ops::ActivationOpInferVarType,
1203 1204 1205 1206 1207
    ops::ActivationGradOpMaker<ops::CELUGradFunctor<float>::FwdDeps(),
                               paddle::framework::OpDesc>,
    ops::ActivationGradOpMaker<ops::CELUGradFunctor<float>::FwdDeps(),
                               paddle::imperative::OpBase>,
    ops::ActFwdInplaceInferer);
1208 1209
REGISTER_OPERATOR(celu_grad,
                  ops::ActivationOpGrad,
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
                  ops::ActivationGradOpInplaceInferer,
                  ops::CELUDoubleGradMaker<paddle::framework::OpDesc>,
                  ops::CELUDoubleGradMaker<paddle::imperative::OpBase>);
REGISTER_OPERATOR(
    celu_grad_grad,
    ops::ActivationOpDoubleGrad<ops::CELUGradFunctor<float>::FwdDeps()>,
    ops::ActivationDoubleGradOpInplaceInferer);

/* ========================================================================== */

L
lvmengsi 已提交
1220 1221
/* ===========================   sqrt register  ============================= */
REGISTER_OPERATOR(
1222 1223 1224 1225
    sqrt,
    ops::ActivationOp,
    ops::SqrtOpMaker,
    ops::ActivationOpInferVarType,
H
hong 已提交
1226 1227 1228 1229
    ops::ActivationGradOpMaker<ops::SqrtGradFunctor<float>::FwdDeps(),
                               paddle::framework::OpDesc>,
    ops::ActivationGradOpMaker<ops::SqrtGradFunctor<float>::FwdDeps(),
                               paddle::imperative::OpBase>,
1230
    ops::ActFwdInplaceInferer);
1231 1232
REGISTER_OPERATOR(sqrt_grad,
                  ops::ActivationOpGrad,
1233
                  ops::ActivationGradOpInplaceInferer,
H
hong 已提交
1234 1235
                  ops::SqrtDoubleGradMaker<paddle::framework::OpDesc>,
                  ops::SqrtDoubleGradMaker<paddle::imperative::OpBase>);
L
lvmengsi 已提交
1236 1237
REGISTER_OPERATOR(
    sqrt_grad_grad,
1238
    ops::ActivationOpDoubleGrad<ops::SqrtGradGradFunctor<float>::FwdDeps()>,
1239
    ops::ActivationDoubleGradOpInplaceInferer);
1240

L
lvmengsi 已提交
1241 1242
/* ========================================================================== */

W
whs 已提交
1243 1244 1245
/* ===========================   rsqrt register  =============================
 */
REGISTER_OPERATOR(
1246 1247 1248 1249
    rsqrt,
    ops::ActivationOp,
    ops::RsqrtOpMaker,
    ops::ActivationOpInferVarType,
W
whs 已提交
1250 1251 1252 1253 1254
    ops::ActivationGradOpMaker<ops::RsqrtGradFunctor<float>::FwdDeps(),
                               paddle::framework::OpDesc>,
    ops::ActivationGradOpMaker<ops::RsqrtGradFunctor<float>::FwdDeps(),
                               paddle::imperative::OpBase>,
    ops::ActFwdInplaceInferer);
1255 1256
REGISTER_OPERATOR(rsqrt_grad,
                  ops::ActivationOpGrad,
W
whs 已提交
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
                  ops::ActivationGradOpInplaceInferer,
                  ops::RsqrtDoubleGradMaker<paddle::framework::OpDesc>,
                  ops::RsqrtDoubleGradMaker<paddle::imperative::OpBase>);
REGISTER_OPERATOR(
    rsqrt_grad_grad,
    ops::ActivationOpDoubleGrad<ops::RsqrtGradGradFunctor<float>::FwdDeps()>,
    ops::ActivationDoubleGradOpInplaceInferer);

/* ========================================================================== */

1267 1268
/* ==========================   square register  ============================ */
REGISTER_OPERATOR(
1269 1270 1271
    square,
    ops::ActivationOp,
    ops::SquareOpMaker,
1272
    ops::ActivationOpInferVarType,
H
hong 已提交
1273 1274 1275 1276
    ops::ActivationGradOpMaker<ops::SquareGradFunctor<float>::FwdDeps(),
                               paddle::framework::OpDesc>,
    ops::ActivationGradOpMaker<ops::SquareGradFunctor<float>::FwdDeps(),
                               paddle::imperative::OpBase>,
1277
    ops::ActFwdInplaceInferer);
1278 1279
REGISTER_OPERATOR(square_grad,
                  ops::ActivationOpGrad,
1280
                  ops::ActivationGradOpInplaceInferer,
H
hong 已提交
1281 1282
                  ops::SquareDoubleGradMaker<paddle::framework::OpDesc>,
                  ops::SquareDoubleGradMaker<paddle::imperative::OpBase>);
1283 1284
REGISTER_OPERATOR(
    square_grad_grad,
1285
    ops::ActivationOpDoubleGrad<ops::SquareGradGradFunctor<float>::FwdDeps()>,
1286
    ops::ActivationDoubleGradOpInplaceInferer);
1287 1288

/* ========================================================================== */
1289 1290 1291 1292

/* ==========================   pow register  ============================ */

REGISTER_OPERATOR(
1293 1294 1295 1296
    pow,
    ops::PowOp,
    ops::PowOpMaker,
    ops::ActivationOpInferVarType,
H
hong 已提交
1297 1298
    ops::PowGradOpMaker<paddle::framework::OpDesc>,
    ops::PowGradOpMaker<paddle::imperative::OpBase>,
1299
    std::conditional<ops::CanInplaceAct<ops::PowGradFunctor<float>>(),
1300 1301 1302 1303
                     ops::ActFwdInplaceInferer,
                     void>::type);
REGISTER_OPERATOR(pow_grad,
                  ops::PowOpGrad,
1304
                  ops::ActivationGradOpInplaceInferer);
1305 1306
/* ========================================================================== */

1307 1308
/* ==========================  Log register ==================================*/
REGISTER_OPERATOR(
1309 1310 1311 1312
    log,
    ops::ActivationOp,
    ops::LogOpMaker,
    ops::ActivationOpInferVarType,
1313 1314 1315 1316 1317
    ops::ActivationGradOpMaker<ops::LogGradFunctor<float>::FwdDeps(),
                               paddle::framework::OpDesc>,
    ops::ActivationGradOpMaker<ops::LogGradFunctor<float>::FwdDeps(),
                               paddle::imperative::OpBase>,
    ops::ActFwdInplaceInferer);
1318 1319
REGISTER_OPERATOR(log_grad,
                  ops::ActivationOpGrad,
1320 1321 1322 1323 1324 1325 1326 1327 1328
                  ops::ActivationGradOpInplaceInferer,
                  ops::LogDoubleGradMaker<paddle::framework::OpDesc>,
                  ops::LogDoubleGradMaker<paddle::imperative::OpBase>);

REGISTER_OPERATOR(
    log_grad_grad,
    ops::ActivationOpDoubleGrad<ops::LogGradGradFunctor<float>::FwdDeps()>,
    ops::ActivationDoubleGradOpInplaceInferer);

1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
/* ==========================  register checkpoint ===========================*/
REGISTER_OP_VERSION(leaky_relu)
    .AddCheckpoint(
        R"ROC(fix leaky_relu, bahavior changed when alpha < 0 or alpha > 1)ROC",
        paddle::framework::compatible::OpVersionDesc()
            .BugfixWithBehaviorChanged(
                "leaky_relu calculate formula before checkponit: out = max(x, "
                "alpha * x); after checkpoint: out = x if x > 0 else alpha * "
                "x"));

REGISTER_OP_VERSION(hard_shrink)
    .AddCheckpoint(
        R"ROC(fix hard_shrink, bahavior changed when threshold<0)ROC",
        paddle::framework::compatible::OpVersionDesc()
            .BugfixWithBehaviorChanged(
                "hard_shrink calculate formula before checkponit: out = x * "
                "((x < -threshold) + (x > threshold)); after checkpoint: out = "
                "x * (((x < -threshold) + (x > threshold)) > 0)"));

1348 1349
REGISTER_OP_VERSION(softplus).AddCheckpoint(
    R"ROC(add new attributes [beta] and [threshold], and the formula is changed to "
1350 1351
         " softplus(x) = \\frac{1}{beta} * \\log(1 + e^{beta * x}) \\\\ \\text{For numerical"
         " stability, the implementation reverts to the linear function when: beta * x > threshold.})ROC",
1352 1353 1354 1355 1356 1357 1358
    paddle::framework::compatible::OpVersionDesc()
        .NewAttr("beta", "The beta value of the new formula", 1.0f)
        .NewAttr("threshold", "The threshold value of the new formula", 20.0f));

REGISTER_OP_VERSION(mish).AddCheckpoint(
    R"ROC(add new attributes [use_mkldnn], and when computing softplus the formula is changed as the new veriosn of softplus)ROC",
    paddle::framework::compatible::OpVersionDesc().NewAttr(
1359 1360
        "use_mkldnn",
        "(bool, default false) Only used in mkldnn kernel",
1361
        false));
1362

1363
/* ========================================================================== */