activation_op.cc 44.3 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 TanhShrinkDoc[] = R"DOC(
K
kexinzhao 已提交
157
TanhShrink Activation Operator.
K
Kexin Zhao 已提交
158

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

D
dzhwinter 已提交
161
)DOC";
K
Kexin Zhao 已提交
162

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

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

168 169
**Note**:
  input value must be greater than or equal to zero.
K
Kexin Zhao 已提交
170

D
dzhwinter 已提交
171
)DOC";
172

Z
zhoukunsheng 已提交
173 174 175 176 177
UNUSED constexpr char RsqrtDoc[] = R"DOC(
Rsqrt Activation Operator.

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

178
$$out = \\frac{1}{\\sqrt{x}}$$
Z
zhoukunsheng 已提交
179 180 181

)DOC";

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

185
$$out = \ln(x)$$
K
Kexin Zhao 已提交
186 187 188

Natural logarithm of x.

D
dzhwinter 已提交
189 190
)DOC";

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

194
$$out = x^2$$
195

D
dzhwinter 已提交
196 197
)DOC";

D
dzhwinter 已提交
198
UNUSED constexpr char SoftsignDoc[] = R"DOC(
D
dzhwinter 已提交
199 200
Softsign Activation Operator.

201
$$out = \\frac{x}{1 + \|x\|}$$
D
dzhwinter 已提交
202 203 204 205

)DOC";

class LeakyReluOpMaker : public framework::OpProtoAndCheckerMaker {
206
 public:
Y
Yu Yang 已提交
207
  void Make() override {
W
Wilber 已提交
208 209 210 211 212 213 214 215
    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 已提交
216
    AddComment(R"DOC(
D
dzhwinter 已提交
217
LeakyRelu Activation Operator.
K
Kexin Zhao 已提交
218

W
Wilber 已提交
219
$$out = \max(x, \alpha * x)$$
K
Kexin Zhao 已提交
220 221

)DOC");
222 223 224
  }
};

225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
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 已提交
248
class SoftShrinkOpMaker : public framework::OpProtoAndCheckerMaker {
K
kexinzhao 已提交
249
 public:
Y
Yu Yang 已提交
250
  void Make() override {
D
dzhwinter 已提交
251 252 253
    AddInput("X", "Input of Softshrink operator");
    AddOutput("Out", "Output of Softshrink operator");
    AddAttr<float>("lambda", "non-negative offset").SetDefault(0.5f);
K
Kexin Zhao 已提交
254
    AddComment(R"DOC(
255 256 257
:strong:`Softshrink Activation Operator`

..  math::
258
    out = \begin{cases}
259 260 261 262
         x - \lambda, \text{if } x > \lambda \\
         x + \lambda, \text{if } x < -\lambda \\
         0,  \text{otherwise}
         \end{cases}
K
Kexin Zhao 已提交
263 264

)DOC");
K
kexinzhao 已提交
265 266 267
  }
};

268 269
class BReluOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
270
  void Make() override {
271 272 273 274 275 276
    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``.");
277 278 279 280
    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 已提交
281
    AddComment(R"DOC(
K
kexinzhao 已提交
282
BRelu Activation Operator.
K
Kexin Zhao 已提交
283

284
$$out = \min(\max(x, t_{min}), t_{max})$$
K
Kexin Zhao 已提交
285 286

)DOC");
287 288 289 290 291
  }
};

class SoftReluOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
292
  void Make() override {
293
    AddInput("X", "Input of SoftRelu operator");
F
fengjiayi 已提交
294
    AddOutput("Out", "Output of SoftRelu operator");
295 296
    AddAttr<float>("threshold", "The threshold value of SoftRelu")
        .SetDefault(40.0f);
K
Kexin Zhao 已提交
297
    AddComment(R"DOC(
K
kexinzhao 已提交
298
SoftRelu Activation Operator.
K
Kexin Zhao 已提交
299

300
$$out = \ln(1 + \exp(\max(\min(x, threshold), -threshold)))$$
K
Kexin Zhao 已提交
301 302

)DOC");
303 304 305
  }
};

306 307
class ELUOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
308
  void Make() override {
309 310 311 312 313 314
    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``.");
315
    AddAttr<float>("alpha", "The alpha value of ELU").SetDefault(1.0f);
316
    AddComment(R"DOC(
K
kexinzhao 已提交
317
ELU Activation Operator.
K
Kexin Zhao 已提交
318 319 320 321

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

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

)DOC");
325 326 327
  }
};

Z
zhupengyang 已提交
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
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());
  }
};

344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
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");
  }
};

366 367
class Relu6OpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
368
  void Make() override {
Z
zhupengyang 已提交
369 370 371 372 373 374 375 376
    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. ")
377
        .SetDefault(6.0f);
K
Kexin Zhao 已提交
378
    AddComment(R"DOC(
K
kexinzhao 已提交
379
Relu6 Activation Operator.
K
Kexin Zhao 已提交
380

381
$$out = \min(\max(0, x), threshold)$$
K
Kexin Zhao 已提交
382 383

)DOC");
384 385 386
  }
};

387 388
class PowOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
389
  void Make() override {
390
    AddInput("X", "Input of Pow operator");
391 392 393 394 395
    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 已提交
396
    AddOutput("Out", "Output of Pow operator");
397
    AddAttr<float>("factor", "The exponential factor of Pow").SetDefault(1.0f);
K
Kexin Zhao 已提交
398
    AddComment(R"DOC(
K
kexinzhao 已提交
399
Pow Activation Operator.
K
Kexin Zhao 已提交
400

401
$$out = x^{factor}$$
K
Kexin Zhao 已提交
402 403

)DOC");
404 405 406 407 408
  }
};

class STanhOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
409
  void Make() override {
410 411
    AddInput("X",
             "Input of STanh operator."
N
Noel 已提交
412
             " A Tensor with type float32, float64.");
413 414 415
    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);
416 417
    AddAttr<float>("scale_b", "The scale parameter of b for the input")
        .SetDefault(1.7159f);
K
Kexin Zhao 已提交
418
    AddComment(R"DOC(
K
kexinzhao 已提交
419
STanh Activation Operator.
K
Kexin Zhao 已提交
420

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

)DOC");
Q
qijun 已提交
424 425 426
  }
};

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

Y
yuyang18 已提交
438
..  math::
K
Kexin Zhao 已提交
439

Y
yuyang18 已提交
440
    out = \begin{cases}
Y
yuyang18 已提交
441
             x,  \text{if } x > threshold \\
Y
yuyang18 已提交
442 443
             0,  \text{otherwise}
          \end{cases}
K
Kexin Zhao 已提交
444
)DOC");
445 446 447
  }
};

A
Abhinav Arora 已提交
448 449
class SwishOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
450
  void Make() override {
A
Abhinav Arora 已提交
451
    AddInput("X", "Input of Swish operator");
F
fengjiayi 已提交
452
    AddOutput("Out", "Output of Swish operator");
A
Abhinav Arora 已提交
453 454 455 456
    AddAttr<float>("beta", "Constant beta of swish operator").SetDefault(1.0f);
    AddComment(R"DOC(
Swish Activation Operator.

457
$$out = \\frac{x}{1 + e^{- \beta \ x}}$$
A
Abhinav Arora 已提交
458 459 460 461 462

)DOC");
  }
};

463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
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 已提交
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
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).

505
$$out = \frac{x * (min(max(0, x+offset), threshold))}{scale}$$
H
huangjun12 已提交
506 507 508 509 510 511 512 513 514

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 已提交
515 516 517 518
REGISTER_ACTIVATION_OP_MAKER(Sigmoid, SigmoidDoc);
REGISTER_ACTIVATION_OP_MAKER(Relu, ReluDoc);
REGISTER_ACTIVATION_OP_MAKER(TanhShrink, TanhShrinkDoc);
REGISTER_ACTIVATION_OP_MAKER(Sqrt, SqrtDoc);
Z
zhoukunsheng 已提交
519
REGISTER_ACTIVATION_OP_MAKER(Rsqrt, RsqrtDoc);
D
dzhwinter 已提交
520 521 522 523
REGISTER_ACTIVATION_OP_MAKER(Log, LogDoc);
REGISTER_ACTIVATION_OP_MAKER(Square, SquareDoc);
REGISTER_ACTIVATION_OP_MAKER(Softsign, SoftsignDoc);

524
template <ActBwdOpFwdDeps kDepValue>
525 526 527 528 529
class ActivationOpDoubleGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

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

 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 {
571 572
    if (static_cast<int>(kDepValue) &
        static_cast<int>(ActBwdOpFwdDeps::kDepX)) {
573 574 575 576 577
      if (ctx->HasOutput("DDOut")) {
        ctx->ShareDim("X", "DDOut");
        ctx->ShareLoD("X", "DDOut");
      }
    }
578 579
    if (static_cast<int>(kDepValue) &
        static_cast<int>(ActBwdOpFwdDeps::kDepOut)) {
580
      if (ctx->HasOutput("DDOut")) {
581 582 583
        ctx->ShareDim("Out", "DDOut");
        ctx->ShareLoD("Out", "DDOut");
      }
584 585 586 587 588 589 590 591 592 593
    }
  }

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

594 595 596 597 598 599
template <ActBwdOpFwdDeps kDepValue>
class ActivationOpTripleGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
600 601
    if (static_cast<int>(kDepValue) &
        static_cast<int>(ActBwdOpFwdDeps::kDepX)) {
602 603 604 605 606 607 608 609 610
      if (ctx->HasOutput("DX")) {
        ctx->ShareDim("X", "DX");
        ctx->ShareLoD("X", "DX");
      }
      if (ctx->HasOutput("DDOut")) {
        ctx->ShareDim("X", "DDOut");
        ctx->ShareLoD("X", "DDOut");
      }
    }
611 612
    if (static_cast<int>(kDepValue) &
        static_cast<int>(ActBwdOpFwdDeps::kDepOut)) {
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
      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");
  }
};

635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
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")));
  }
};

656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
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"));
  }
};

686 687
// ReluGrad: dx = dy if y >= 0 else 0
// ReluGradGrad: ddy = ddx if y >= 0 else 0
H
hong 已提交
688 689
template <typename T>
class ReluDoubleGradMaker : public ::paddle::framework::SingleGradOpMaker<T> {
690
 public:
H
hong 已提交
691
  using ::paddle::framework::SingleGradOpMaker<T>::SingleGradOpMaker;
692 693

 protected:
694
  void Apply(GradOpPtr<T> op) const override {
695 696
    op->SetType("relu_grad_grad");
    // input1: Out
H
hong 已提交
697
    op->SetInput("Out", this->Input("Out"));
Q
qingqing01 已提交
698
    // input2: ddx
H
hong 已提交
699 700
    op->SetInput("DDX", this->OutputGrad(framework::GradVarName("X")));
    op->SetAttrMap(this->Attrs());
701
    // output: ddy
H
hong 已提交
702
    op->SetOutput("DDOut", this->InputGrad(framework::GradVarName("Out")));
703 704 705
  }
};

706 707
// leaky_relu Grad: dx=dy if x>=0 else alpha * dy
// leaky_relu GradGrad: ddy=ddx if x>=0 else alpha * ddx
H
hong 已提交
708
template <typename T>
709
class LeakyReluDoubleGradMaker
H
hong 已提交
710
    : public ::paddle::framework::SingleGradOpMaker<T> {
711
 public:
H
hong 已提交
712
  using ::paddle::framework::SingleGradOpMaker<T>::SingleGradOpMaker;
713 714

 protected:
715
  void Apply(GradOpPtr<T> op) const override {
716
    op->SetType("leaky_relu_grad_grad");
717 718
    // input1: X
    op->SetInput("X", this->Input("X"));
719
    // X@GRAD@GRAD: ddx
H
hong 已提交
720 721
    op->SetInput("DDX", this->OutputGrad(framework::GradVarName("X")));
    op->SetAttrMap(this->Attrs());
722
    // Out@GRAD@GRAD: ddy
H
hong 已提交
723
    op->SetOutput("DDOut", this->InputGrad(framework::GradVarName("Out")));
724 725 726
  }
};

D
Double_V 已提交
727 728 729 730 731 732 733 734
// 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:
735
  void Apply(GradOpPtr<T> op) const override {
D
Double_V 已提交
736 737 738 739 740 741 742 743 744 745 746 747 748 749
    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")));
  }
};

750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
// 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 已提交
773 774
// sqrt Grad: dx = 0.5 * dy / y
// sqrt GradGrad: ddy = 0.5 * ddx / y, dy = -1 * dx * ddx
H
hong 已提交
775 776
template <typename T>
class SqrtDoubleGradMaker : public ::paddle::framework::SingleGradOpMaker<T> {
L
lvmengsi 已提交
777
 public:
H
hong 已提交
778
  using ::paddle::framework::SingleGradOpMaker<T>::SingleGradOpMaker;
L
lvmengsi 已提交
779 780

 protected:
781
  void Apply(GradOpPtr<T> op) const override {
L
lvmengsi 已提交
782
    op->SetType("sqrt_grad_grad");
H
hong 已提交
783 784 785 786 787 788
    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 已提交
789 790 791
  }
};

W
whs 已提交
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
// 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")));
  }
};

811 812
// square Grad: dx=2x*dy
// square GradGrad: ddy=2x*ddx, dx=2dy*ddx
H
hong 已提交
813 814
template <typename T>
class SquareDoubleGradMaker : public ::paddle::framework::SingleGradOpMaker<T> {
815
 public:
H
hong 已提交
816
  using ::paddle::framework::SingleGradOpMaker<T>::SingleGradOpMaker;
817 818

 protected:
819
  void Apply(GradOpPtr<T> op) const override {
820
    op->SetType("square_grad_grad");
H
hong 已提交
821
    op->SetInput("X", this->Input("X"));
822
    // Out@GRAD: dy
H
hong 已提交
823
    op->SetInput("DOut", this->Input(framework::GradVarName("Out")));
824
    // X@GRAD@GRAD: ddx
H
hong 已提交
825
    op->SetInput("DDX", this->OutputGrad(framework::GradVarName("X")));
826

H
hong 已提交
827
    op->SetAttrMap(this->Attrs());
828 829

    // X@GRAD: dx
H
hong 已提交
830
    op->SetOutput("DX", this->InputGrad("X"));
831
    // Out@GRAD@GRAD: ddy
H
hong 已提交
832
    op->SetOutput("DDOut", this->InputGrad(framework::GradVarName("Out")));
833 834 835
  }
};

836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
// 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")));
  }
};

858
DECLARE_INPLACE_OP_INFERER(ActivationGradOpInplaceInferer,
859 860
                           {framework::GradVarName("Out"),  // dout
                            framework::GradVarName("X")});  // dx
861
DECLARE_INPLACE_OP_INFERER(ActivationDoubleGradOpInplaceInferer,
862
                           {"DDX", "DDOut"});
863 864
DECLARE_INPLACE_OP_INFERER(ActivationTripleGradOpInplaceInferer,
                           {"DDX", "D_DOut"});
865

H
hong 已提交
866 867
template <typename T>
class PowGradOpMaker : public framework::SingleGradOpMaker<T> {
868
 public:
H
hong 已提交
869
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
870 871

 protected:
872
  void Apply(GradOpPtr<T> op) const override {
873
    op->SetType("pow_grad");
H
hong 已提交
874 875 876 877 878
    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());
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
  }
};
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(
897
      const std::string& var_name,
898
      const phi::DenseTensor& tensor,
899 900 901 902
      const framework::OpKernelType& expected_kernel_type) const override {
    if (var_name == "FactorTensor") {
      return expected_kernel_type;
    }
903 904
    return framework::OpKernelType(
        expected_kernel_type.data_type_, tensor.place(), tensor.layout());
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
  }
};

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(
925
      const std::string& var_name,
926
      const phi::DenseTensor& tensor,
927 928 929 930
      const framework::OpKernelType& expected_kernel_type) const override {
    if (var_name == "FactorTensor") {
      return expected_kernel_type;
    }
931 932
    return framework::OpKernelType(
        expected_kernel_type.data_type_, tensor.place(), tensor.layout());
933 934
  }
};
935
DECLARE_INPLACE_OP_INFERER(ActFwdInplaceInferer, {"X", "Out"});
Q
qijun 已提交
936 937 938 939
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
940
namespace plat = paddle::platform;
941

942 943
#define REGISTER_ACTIVATION_OP(KERNEL_TYPE, OP_NAME, functor, grad_functor) \
  REGISTER_OPERATOR(                                                        \
944 945 946
      KERNEL_TYPE,                                                          \
      ops::ActivationOp,                                                    \
      ops::OP_NAME##OpMaker,                                                \
947
      ops::ActivationOpInferVarType,                                        \
H
hong 已提交
948 949 950 951
      ops::ActivationGradOpMaker<ops::grad_functor<float>::FwdDeps(),       \
                                 paddle::framework::OpDesc>,                \
      ops::ActivationGradOpMaker<ops::grad_functor<float>::FwdDeps(),       \
                                 paddle::imperative::OpBase>,               \
952
      std::conditional<ops::CanInplaceAct<ops::grad_functor<float>>(),      \
953 954 955 956
                       ops::ActFwdInplaceInferer,                           \
                       void>::type);                                        \
  REGISTER_OPERATOR(KERNEL_TYPE##_grad,                                     \
                    ops::ActivationOpGrad,                                  \
957
                    ops::ActivationGradOpInplaceInferer);
958

L
Leo Chen 已提交
959 960 961 962 963 964 965 966 967 968
#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>>);
969

970 971
FOR_EACH_ACTIVATION_OP(REGISTER_ACTIVATION_OP);
FOR_EACH_ACTIVATION_OP(REGISTER_ACTIVATION_CPU_KERNEL);
972

973
REGISTER_ACTIVATION_OP(brelu, BRelu, BReluFunctor, BReluGradFunctor);
974 975 976 977
REGISTER_ACTIVATION_OP(thresholded_relu,
                       ThresholdedRelu,
                       ThresholdedReluFunctor,
                       ThresholdedReluGradFunctor);
978
REGISTER_ACTIVATION_OP(relu6, Relu6, Relu6Functor, Relu6GradFunctor);
979 980 981
REGISTER_ACTIVATION_OP(softshrink,
                       SoftShrink,
                       SoftShrinkFunctor,
Y
YuanRisheng 已提交
982
                       SoftShrinkGradFunctor);
983 984 985
REGISTER_ACTIVATION_OP(tanh_shrink,
                       TanhShrink,
                       TanhShrinkFunctor,
Y
YuanRisheng 已提交
986
                       TanhShrinkGradFunctor);
987 988 989 990
REGISTER_ACTIVATION_OP(softsign,
                       Softsign,
                       SoftsignFunctor,
                       SoftsignGradFunctor);
991 992 993
REGISTER_ACTIVATION_OP(softplus,
                       Softplus,
                       SoftplusFunctor,
994 995 996
                       SoftplusGradFunctor);
REGISTER_ACTIVATION_OP(mish, Mish, MishFunctor, MishGradFunctor);
REGISTER_ACTIVATION_OP(stanh, STanh, STanhFunctor, STanhGradFunctor);
997 998 999
REGISTER_ACTIVATION_OP(hard_swish,
                       HardSwish,
                       HardSwishFunctor,
Y
YuanRisheng 已提交
1000 1001
                       HardSwishGradFunctor);
REGISTER_ACTIVATION_OP(swish, Swish, SwishFunctor, SwishGradFunctor);
1002

1003 1004 1005 1006
/* ==========================    sigmoid register  =============================
 */
// 1. Register Sigmoid Operator
REGISTER_OPERATOR(
1007 1008 1009
    sigmoid,
    ops::ActivationOp,
    ops::SigmoidOpMaker,
1010 1011 1012 1013 1014 1015
    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>>(),
1016 1017
                     ops::ActFwdInplaceInferer,
                     void>::type);
1018 1019

// 2. Register Sigmoid Grad Operator
1020 1021
REGISTER_OPERATOR(sigmoid_grad,
                  ops::ActivationOpGrad,
1022 1023
                  ops::ActivationGradOpInplaceInferer,
                  ops::SigmoidDoubleGradMaker<paddle::framework::OpDesc>,
1024
                  ops::SigmoidDoubleGradMaker<paddle::imperative::OpBase>);
1025 1026 1027 1028

// 3. Register Sigmoid DoubleGrad Operator
REGISTER_OPERATOR(
    sigmoid_grad_grad,
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
    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);
1039 1040 1041

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

1042
/* ==========================    relu register  ============================= */
1043
REGISTER_OPERATOR(
1044 1045 1046 1047
    relu,
    ops::ActivationOp,
    ops::ReluOpMaker,
    ops::ActivationOpInferVarType,
H
hong 已提交
1048 1049 1050 1051
    ops::ActivationGradOpMaker<ops::ReluGradFunctor<float>::FwdDeps(),
                               paddle::framework::OpDesc>,
    ops::ActivationGradOpMaker<ops::ReluGradFunctor<float>::FwdDeps(),
                               paddle::imperative::OpBase>,
1052
    ops::ActFwdInplaceInferer);
1053 1054
REGISTER_OPERATOR(relu_grad,
                  ops::ActivationOpGrad,
1055
                  ops::ActivationGradOpInplaceInferer,
H
hong 已提交
1056 1057
                  ops::ReluDoubleGradMaker<paddle::framework::OpDesc>,
                  ops::ReluDoubleGradMaker<paddle::imperative::OpBase>);
1058 1059
REGISTER_OPERATOR(
    relu_grad_grad,
1060
    ops::ActivationOpDoubleGrad2<ops::ReluGradFunctor<float>::FwdDeps()>,
1061
    ops::ActivationDoubleGradOpInplaceInferer);
1062

1063
/* ========================================================================== */
1064

1065
/* ======================== leaky relu register  ============================ */
1066
REGISTER_OPERATOR(
1067 1068 1069
    leaky_relu,
    ops::ActivationOp,
    ops::LeakyReluOpMaker,
1070
    ops::ActivationOpInferVarType,
H
hong 已提交
1071 1072 1073 1074
    ops::ActivationGradOpMaker<ops::LeakyReluGradFunctor<float>::FwdDeps(),
                               paddle::framework::OpDesc>,
    ops::ActivationGradOpMaker<ops::LeakyReluGradFunctor<float>::FwdDeps(),
                               paddle::imperative::OpBase>,
1075
    ops::ActFwdInplaceInferer);
1076 1077
REGISTER_OPERATOR(leaky_relu_grad,
                  ops::ActivationOpGrad,
1078
                  ops::ActivationGradOpInplaceInferer,
H
hong 已提交
1079 1080
                  ops::LeakyReluDoubleGradMaker<paddle::framework::OpDesc>,
                  ops::LeakyReluDoubleGradMaker<paddle::imperative::OpBase>);
1081 1082
REGISTER_OPERATOR(
    leaky_relu_grad_grad,
1083
    ops::ActivationOpDoubleGrad2<ops::LeakyReluGradFunctor<float>::FwdDeps()>,
1084
    ops::ActivationDoubleGradOpInplaceInferer);
1085 1086 1087

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

D
Double_V 已提交
1088
/* ========================    elu  register     ============================ */
1089 1090 1091
REGISTER_OPERATOR(elu,
                  ops::ActivationOp,
                  ops::ELUOpMaker,
Z
zhupengyang 已提交
1092 1093 1094 1095
                  ops::ActivationOpInferVarType,
                  ops::ELUGradOpMaker<paddle::framework::OpDesc>,
                  ops::ELUGradOpMaker<paddle::imperative::OpBase>,
                  ops::ActFwdInplaceInferer);
1096 1097
REGISTER_OPERATOR(elu_grad,
                  ops::ActivationOpGrad,
1098
                  ops::ActivationGradOpInplaceInferer,
D
Double_V 已提交
1099 1100 1101 1102 1103
                  ops::ELUDoubleGradMaker<paddle::framework::OpDesc>,
                  ops::ELUDoubleGradMaker<paddle::imperative::OpBase>);
REGISTER_OPERATOR(
    elu_grad_grad,
    ops::ActivationOpDoubleGrad<ops::ELUGradFunctor<float>::FwdDeps()>,
1104
    ops::ActivationDoubleGradOpInplaceInferer);
D
Double_V 已提交
1105 1106 1107

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

1108 1109 1110
/* ========================    celu  register     ============================
 */
REGISTER_OPERATOR(
1111 1112 1113 1114
    celu,
    ops::ActivationOp,
    ops::CELUOpMaker,
    ops::ActivationOpInferVarType,
1115 1116 1117 1118 1119
    ops::ActivationGradOpMaker<ops::CELUGradFunctor<float>::FwdDeps(),
                               paddle::framework::OpDesc>,
    ops::ActivationGradOpMaker<ops::CELUGradFunctor<float>::FwdDeps(),
                               paddle::imperative::OpBase>,
    ops::ActFwdInplaceInferer);
1120 1121
REGISTER_OPERATOR(celu_grad,
                  ops::ActivationOpGrad,
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
                  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 已提交
1132 1133
/* ===========================   sqrt register  ============================= */
REGISTER_OPERATOR(
1134 1135 1136 1137
    sqrt,
    ops::ActivationOp,
    ops::SqrtOpMaker,
    ops::ActivationOpInferVarType,
H
hong 已提交
1138 1139 1140 1141
    ops::ActivationGradOpMaker<ops::SqrtGradFunctor<float>::FwdDeps(),
                               paddle::framework::OpDesc>,
    ops::ActivationGradOpMaker<ops::SqrtGradFunctor<float>::FwdDeps(),
                               paddle::imperative::OpBase>,
1142
    ops::ActFwdInplaceInferer);
1143 1144
REGISTER_OPERATOR(sqrt_grad,
                  ops::ActivationOpGrad,
1145
                  ops::ActivationGradOpInplaceInferer,
H
hong 已提交
1146 1147
                  ops::SqrtDoubleGradMaker<paddle::framework::OpDesc>,
                  ops::SqrtDoubleGradMaker<paddle::imperative::OpBase>);
L
lvmengsi 已提交
1148 1149
REGISTER_OPERATOR(
    sqrt_grad_grad,
1150
    ops::ActivationOpDoubleGrad<ops::SqrtGradGradFunctor<float>::FwdDeps()>,
1151
    ops::ActivationDoubleGradOpInplaceInferer);
1152

L
lvmengsi 已提交
1153 1154
/* ========================================================================== */

W
whs 已提交
1155 1156 1157
/* ===========================   rsqrt register  =============================
 */
REGISTER_OPERATOR(
1158 1159 1160 1161
    rsqrt,
    ops::ActivationOp,
    ops::RsqrtOpMaker,
    ops::ActivationOpInferVarType,
W
whs 已提交
1162 1163 1164 1165 1166
    ops::ActivationGradOpMaker<ops::RsqrtGradFunctor<float>::FwdDeps(),
                               paddle::framework::OpDesc>,
    ops::ActivationGradOpMaker<ops::RsqrtGradFunctor<float>::FwdDeps(),
                               paddle::imperative::OpBase>,
    ops::ActFwdInplaceInferer);
1167 1168
REGISTER_OPERATOR(rsqrt_grad,
                  ops::ActivationOpGrad,
W
whs 已提交
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
                  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);

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

1179 1180
/* ==========================   square register  ============================ */
REGISTER_OPERATOR(
1181 1182 1183
    square,
    ops::ActivationOp,
    ops::SquareOpMaker,
1184
    ops::ActivationOpInferVarType,
H
hong 已提交
1185 1186 1187 1188
    ops::ActivationGradOpMaker<ops::SquareGradFunctor<float>::FwdDeps(),
                               paddle::framework::OpDesc>,
    ops::ActivationGradOpMaker<ops::SquareGradFunctor<float>::FwdDeps(),
                               paddle::imperative::OpBase>,
1189
    ops::ActFwdInplaceInferer);
1190 1191
REGISTER_OPERATOR(square_grad,
                  ops::ActivationOpGrad,
1192
                  ops::ActivationGradOpInplaceInferer,
H
hong 已提交
1193 1194
                  ops::SquareDoubleGradMaker<paddle::framework::OpDesc>,
                  ops::SquareDoubleGradMaker<paddle::imperative::OpBase>);
1195 1196
REGISTER_OPERATOR(
    square_grad_grad,
1197
    ops::ActivationOpDoubleGrad<ops::SquareGradGradFunctor<float>::FwdDeps()>,
1198
    ops::ActivationDoubleGradOpInplaceInferer);
1199 1200

/* ========================================================================== */
1201 1202 1203 1204

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

REGISTER_OPERATOR(
1205 1206 1207 1208
    pow,
    ops::PowOp,
    ops::PowOpMaker,
    ops::ActivationOpInferVarType,
H
hong 已提交
1209 1210
    ops::PowGradOpMaker<paddle::framework::OpDesc>,
    ops::PowGradOpMaker<paddle::imperative::OpBase>,
1211
    std::conditional<ops::CanInplaceAct<ops::PowGradFunctor<float>>(),
1212 1213 1214 1215
                     ops::ActFwdInplaceInferer,
                     void>::type);
REGISTER_OPERATOR(pow_grad,
                  ops::PowOpGrad,
1216
                  ops::ActivationGradOpInplaceInferer);
1217 1218
/* ========================================================================== */

1219 1220
/* ==========================  Log register ==================================*/
REGISTER_OPERATOR(
1221 1222 1223 1224
    log,
    ops::ActivationOp,
    ops::LogOpMaker,
    ops::ActivationOpInferVarType,
1225 1226 1227 1228 1229
    ops::ActivationGradOpMaker<ops::LogGradFunctor<float>::FwdDeps(),
                               paddle::framework::OpDesc>,
    ops::ActivationGradOpMaker<ops::LogGradFunctor<float>::FwdDeps(),
                               paddle::imperative::OpBase>,
    ops::ActFwdInplaceInferer);
1230 1231
REGISTER_OPERATOR(log_grad,
                  ops::ActivationOpGrad,
1232 1233 1234 1235 1236 1237 1238 1239 1240
                  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);

1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
/* ==========================  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)"));

1260 1261
REGISTER_OP_VERSION(softplus).AddCheckpoint(
    R"ROC(add new attributes [beta] and [threshold], and the formula is changed to "
1262 1263
         " 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",
1264 1265 1266 1267 1268 1269 1270
    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(
1271 1272
        "use_mkldnn",
        "(bool, default false) Only used in mkldnn kernel",
1273
        false));
1274

1275
/* ========================================================================== */