activation_op.cc 24.1 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

C
Charles-hit 已提交
23
#include "paddle/fluid/framework/infershape_utils.h"
24
#include "paddle/fluid/framework/op_version_registry.h"
25
#include "paddle/fluid/operators/common_infer_shape_functions.h"
26
#include "paddle/fluid/operators/mkldnn/mkldnn_activation_op.h"
27
#include "paddle/phi/backends/dynload/port.h"
C
Charles-hit 已提交
28
#include "paddle/phi/infermeta/backward.h"
Q
qijun 已提交
29

A
Adam 已提交
30 31
DECLARE_bool(use_mkldnn);

Q
qijun 已提交
32 33 34
namespace paddle {
namespace operators {

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

41 42 43 44 45 46 47 48 49 50 51 52 53 54
#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 已提交
55
  }
D
dzhwinter 已提交
56

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

 protected:
63
  void Apply(GradOpPtr<T> op) const override {
H
hong 已提交
64 65 66 67
    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());
68

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

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

84 85 86
framework::OpKernelType GetKernelType(const framework::ExecutionContext& ctx,
                                      const framework::OperatorWithKernel& oper,
                                      const std::string& name) {
87
  auto data_type = oper.IndicateVarDataType(ctx, name);
88 89 90 91 92 93 94 95 96 97 98
  // 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());
99 100
}

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

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

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

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

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

131
  void InferShape(framework::InferShapeContext* ctx) const override {
132 133 134
    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 已提交
135
  }
136

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

144 145
class BReluOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
146
  void Make() override {
147 148 149 150 151 152
    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``.");
153 154 155 156
    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 已提交
157
    AddComment(R"DOC(
K
kexinzhao 已提交
158
BRelu Activation Operator.
K
Kexin Zhao 已提交
159

160
$$out = \min(\max(x, t_{min}), t_{max})$$
K
Kexin Zhao 已提交
161 162

)DOC");
163 164 165 166 167
  }
};

class SoftReluOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
168
  void Make() override {
169
    AddInput("X", "Input of SoftRelu operator");
F
fengjiayi 已提交
170
    AddOutput("Out", "Output of SoftRelu operator");
171 172
    AddAttr<float>("threshold", "The threshold value of SoftRelu")
        .SetDefault(40.0f);
K
Kexin Zhao 已提交
173
    AddComment(R"DOC(
K
kexinzhao 已提交
174
SoftRelu Activation Operator.
K
Kexin Zhao 已提交
175

176
$$out = \ln(1 + \exp(\max(\min(x, threshold), -threshold)))$$
K
Kexin Zhao 已提交
177 178

)DOC");
179 180 181
  }
};

182 183
class Relu6OpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
184
  void Make() override {
Z
zhupengyang 已提交
185 186 187 188 189 190 191 192
    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. ")
193
        .SetDefault(6.0f);
K
Kexin Zhao 已提交
194
    AddComment(R"DOC(
K
kexinzhao 已提交
195
Relu6 Activation Operator.
K
Kexin Zhao 已提交
196

197
$$out = \min(\max(0, x), threshold)$$
K
Kexin Zhao 已提交
198 199

)DOC");
200 201 202
  }
};

203 204
class PowOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
205
  void Make() override {
206
    AddInput("X", "Input of Pow operator");
207 208 209 210 211
    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 已提交
212
    AddOutput("Out", "Output of Pow operator");
213
    AddAttr<float>("factor", "The exponential factor of Pow").SetDefault(1.0f);
K
Kexin Zhao 已提交
214
    AddComment(R"DOC(
K
kexinzhao 已提交
215
Pow Activation Operator.
K
Kexin Zhao 已提交
216

217
$$out = x^{factor}$$
K
Kexin Zhao 已提交
218 219

)DOC");
220 221 222 223 224
  }
};

class STanhOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
225
  void Make() override {
226 227
    AddInput("X",
             "Input of STanh operator."
N
Noel 已提交
228
             " A Tensor with type float32, float64.");
229 230 231
    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);
232 233
    AddAttr<float>("scale_b", "The scale parameter of b for the input")
        .SetDefault(1.7159f);
K
Kexin Zhao 已提交
234
    AddComment(R"DOC(
K
kexinzhao 已提交
235
STanh Activation Operator.
K
Kexin Zhao 已提交
236

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

)DOC");
Q
qijun 已提交
240 241 242
  }
};

A
Abhinav Arora 已提交
243 244
class SwishOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
245
  void Make() override {
A
Abhinav Arora 已提交
246
    AddInput("X", "Input of Swish operator");
F
fengjiayi 已提交
247
    AddOutput("Out", "Output of Swish operator");
A
Abhinav Arora 已提交
248 249 250 251
    AddAttr<float>("beta", "Constant beta of swish operator").SetDefault(1.0f);
    AddComment(R"DOC(
Swish Activation Operator.

252
$$out = \\frac{x}{1 + e^{- \beta \ x}}$$
A
Abhinav Arora 已提交
253 254 255 256 257

)DOC");
  }
};

258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
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 已提交
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
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).

300
$$out = \frac{x * (min(max(0, x+offset), threshold))}{scale}$$
H
huangjun12 已提交
301 302 303 304 305 306 307 308 309

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");
  }
};

310
template <ActBwdOpFwdDeps kDepValue>
311 312 313 314 315
class ActivationOpDoubleGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
316 317
    if (static_cast<int>(kDepValue) &
        static_cast<int>(ActBwdOpFwdDeps::kDepX)) {
318
      if (ctx->HasOutput("DX")) {
319 320 321
        ctx->ShareDim("X", "DX");
        ctx->ShareLoD("X", "DX");
      }
322
      if (ctx->HasOutput("DDOut")) {
323 324 325
        ctx->ShareDim("X", "DDOut");
        ctx->ShareLoD("X", "DDOut");
      }
326
    }
327 328
    if (static_cast<int>(kDepValue) &
        static_cast<int>(ActBwdOpFwdDeps::kDepOut)) {
329
      if (ctx->HasOutput("DOut")) {
330 331 332
        ctx->ShareDim("Out", "DOut");
        ctx->ShareLoD("Out", "DOut");
      }
333 334 335 336
      if (ctx->HasOutput("DDOut")) {
        ctx->ShareDim("Out", "DDOut");
        ctx->ShareLoD("Out", "DDOut");
      }
337 338 339 340
      if (ctx->HasOutput("DOutNew")) {
        ctx->ShareDim("Out", "DOutNew");
        ctx->ShareLoD("Out", "DOutNew");
      }
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
    }
  }

 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 {
357 358
    if (static_cast<int>(kDepValue) &
        static_cast<int>(ActBwdOpFwdDeps::kDepX)) {
359 360 361 362 363
      if (ctx->HasOutput("DDOut")) {
        ctx->ShareDim("X", "DDOut");
        ctx->ShareLoD("X", "DDOut");
      }
    }
364 365
    if (static_cast<int>(kDepValue) &
        static_cast<int>(ActBwdOpFwdDeps::kDepOut)) {
366
      if (ctx->HasOutput("DDOut")) {
367 368 369
        ctx->ShareDim("Out", "DDOut");
        ctx->ShareLoD("Out", "DDOut");
      }
370 371 372 373 374 375 376 377 378 379
    }
  }

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

380 381 382 383 384 385
template <ActBwdOpFwdDeps kDepValue>
class ActivationOpTripleGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
386 387
    if (static_cast<int>(kDepValue) &
        static_cast<int>(ActBwdOpFwdDeps::kDepX)) {
388 389 390 391 392 393 394 395 396
      if (ctx->HasOutput("DX")) {
        ctx->ShareDim("X", "DX");
        ctx->ShareLoD("X", "DX");
      }
      if (ctx->HasOutput("DDOut")) {
        ctx->ShareDim("X", "DDOut");
        ctx->ShareLoD("X", "DDOut");
      }
    }
397 398
    if (static_cast<int>(kDepValue) &
        static_cast<int>(ActBwdOpFwdDeps::kDepOut)) {
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
      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");
  }
};

421
DECLARE_INPLACE_OP_INFERER(ActivationGradOpInplaceInferer,
422 423
                           {framework::GradVarName("Out"),  // dout
                            framework::GradVarName("X")});  // dx
424
DECLARE_INPLACE_OP_INFERER(ActivationDoubleGradOpInplaceInferer,
425
                           {"DDX", "DDOut"});
426 427
DECLARE_INPLACE_OP_INFERER(ActivationTripleGradOpInplaceInferer,
                           {"DDX", "D_DOut"});
428

H
hong 已提交
429 430
template <typename T>
class PowGradOpMaker : public framework::SingleGradOpMaker<T> {
431
 public:
H
hong 已提交
432
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
433 434

 protected:
435
  void Apply(GradOpPtr<T> op) const override {
436
    op->SetType("pow_grad");
H
hong 已提交
437 438
    op->SetInput("X", this->Input("X"));
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
C
Charles-hit 已提交
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
    op->SetOutput(framework ::GradVarName("X"), this->InputGrad("X"));
    op->SetInput("FactorTensor", this->Input("FactorTensor"));
    op->SetAttrMap(this->Attrs());
  }
};
template <typename T>
class PowDoubleGradOpMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
  void Apply(GradOpPtr<T> op) const override {
    op->SetType("pow_double_grad");
    op->SetInput("X", this->Input("X"));
    op->SetInput("DOut", this->Input(framework::GradVarName("Out")));
    op->SetInput("DDX", this->OutputGrad(framework ::GradVarName("X")));
    op->SetOutput("DX", this->InputGrad("X"));
    op->SetOutput("DDOut", this->InputGrad(framework::GradVarName("Out")));
H
hong 已提交
457 458
    op->SetInput("FactorTensor", this->Input("FactorTensor"));
    op->SetAttrMap(this->Attrs());
459 460
  }
};
C
Charles-hit 已提交
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
template <typename T>
class PowTripleGradOpMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
  void Apply(GradOpPtr<T> op) const override {
    op->SetType("pow_triple_grad");
    op->SetInput("X", this->Input("X"));
    op->SetInput("DOut", this->Input("DOut"));
    op->SetInput("DDX", this->Input("DDX"));
    op->SetInput("D_DX", this->OutputGrad("DX"));
    op->SetInput("D_DDOut", this->OutputGrad("DDOut"));
    op->SetOutput("D_X", this->InputGrad("X"));
    op->SetOutput("D_DOut", this->InputGrad("DOut"));
    op->SetOutput("D_DDX", this->InputGrad("DDX"));
    op->SetInput("FactorTensor", this->Input("FactorTensor"));
    op->SetAttrMap(this->Attrs());
  }
};
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
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(
497
      const std::string& var_name,
498
      const phi::DenseTensor& tensor,
499 500 501 502
      const framework::OpKernelType& expected_kernel_type) const override {
    if (var_name == "FactorTensor") {
      return expected_kernel_type;
    }
503 504
    return framework::OpKernelType(
        expected_kernel_type.data_type_, tensor.place(), tensor.layout());
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
  }
};

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(
525
      const std::string& var_name,
526
      const phi::DenseTensor& tensor,
527 528 529 530
      const framework::OpKernelType& expected_kernel_type) const override {
    if (var_name == "FactorTensor") {
      return expected_kernel_type;
    }
531 532
    return framework::OpKernelType(
        expected_kernel_type.data_type_, tensor.place(), tensor.layout());
533 534
  }
};
C
Charles-hit 已提交
535 536 537 538 539 540 541 542 543 544 545 546

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

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

C
Charles-hit 已提交
547 548 549 550 551 552 553 554 555 556
class PowOpTripleGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return GetKernelType(ctx, *this, "X");
  }
};
557
DECLARE_INPLACE_OP_INFERER(ActFwdInplaceInferer, {"X", "Out"});
Q
qijun 已提交
558 559 560 561
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
562
namespace plat = paddle::platform;
563

564 565
#define REGISTER_ACTIVATION_OP(KERNEL_TYPE, OP_NAME, functor, grad_functor) \
  REGISTER_OPERATOR(                                                        \
566 567 568
      KERNEL_TYPE,                                                          \
      ops::ActivationOp,                                                    \
      ops::OP_NAME##OpMaker,                                                \
569
      ops::ActivationOpInferVarType,                                        \
H
hong 已提交
570 571 572 573
      ops::ActivationGradOpMaker<ops::grad_functor<float>::FwdDeps(),       \
                                 paddle::framework::OpDesc>,                \
      ops::ActivationGradOpMaker<ops::grad_functor<float>::FwdDeps(),       \
                                 paddle::imperative::OpBase>,               \
574
      std::conditional<ops::CanInplaceAct<ops::grad_functor<float>>(),      \
575 576 577 578
                       ops::ActFwdInplaceInferer,                           \
                       void>::type);                                        \
  REGISTER_OPERATOR(KERNEL_TYPE##_grad,                                     \
                    ops::ActivationOpGrad,                                  \
579
                    ops::ActivationGradOpInplaceInferer);
580

L
Leo Chen 已提交
581 582 583 584 585 586 587 588 589 590
#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>>);
591

592 593
FOR_EACH_ACTIVATION_OP(REGISTER_ACTIVATION_OP);
FOR_EACH_ACTIVATION_OP(REGISTER_ACTIVATION_CPU_KERNEL);
594

595
REGISTER_ACTIVATION_OP(brelu, BRelu, BReluFunctor, BReluGradFunctor);
596
REGISTER_ACTIVATION_OP(relu6, Relu6, Relu6Functor, Relu6GradFunctor);
597 598
REGISTER_ACTIVATION_OP(mish, Mish, MishFunctor, MishGradFunctor);
REGISTER_ACTIVATION_OP(stanh, STanh, STanhFunctor, STanhGradFunctor);
599 600 601
REGISTER_ACTIVATION_OP(hard_swish,
                       HardSwish,
                       HardSwishFunctor,
Y
YuanRisheng 已提交
602 603
                       HardSwishGradFunctor);
REGISTER_ACTIVATION_OP(swish, Swish, SwishFunctor, SwishGradFunctor);
604

605
/* ==========================   pow register  ============================ */
C
Charles-hit 已提交
606 607 608
DECLARE_INFER_SHAPE_FUNCTOR(pow_double_grad,
                            PowDoubleGradInferShapeFunctor,
                            PD_INFER_META(phi::GeneralBinaryGradInferMeta));
C
Charles-hit 已提交
609 610 611
DECLARE_INFER_SHAPE_FUNCTOR(pow_triple_grad,
                            PowTripleGradInferShapeFunctor,
                            PD_INFER_META(phi::GeneralTernaryGradInferMeta));
612 613

REGISTER_OPERATOR(
614 615 616 617
    pow,
    ops::PowOp,
    ops::PowOpMaker,
    ops::ActivationOpInferVarType,
H
hong 已提交
618 619
    ops::PowGradOpMaker<paddle::framework::OpDesc>,
    ops::PowGradOpMaker<paddle::imperative::OpBase>,
620
    std::conditional<ops::CanInplaceAct<ops::PowGradFunctor<float>>(),
621 622 623 624
                     ops::ActFwdInplaceInferer,
                     void>::type);
REGISTER_OPERATOR(pow_grad,
                  ops::PowOpGrad,
C
Charles-hit 已提交
625 626 627 628 629 630
                  ops::ActivationGradOpInplaceInferer,
                  ops::PowDoubleGradOpMaker<paddle::framework::OpDesc>,
                  ops::PowDoubleGradOpMaker<paddle::imperative::OpBase>);
REGISTER_OPERATOR(pow_double_grad,
                  ops::PowOpDoubleGrad,
                  ops::ActivationDoubleGradOpInplaceInferer,
C
Charles-hit 已提交
631 632
                  ops::PowTripleGradOpMaker<paddle::framework::OpDesc>,
                  ops::PowTripleGradOpMaker<paddle::imperative::OpBase>,
C
Charles-hit 已提交
633
                  PowDoubleGradInferShapeFunctor);
C
Charles-hit 已提交
634 635 636
REGISTER_OPERATOR(pow_triple_grad,
                  ops::PowOpTripleGrad,
                  PowTripleGradInferShapeFunctor);
637 638
/* ========================================================================== */

639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
/* ==========================  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)"));

658 659
REGISTER_OP_VERSION(softplus).AddCheckpoint(
    R"ROC(add new attributes [beta] and [threshold], and the formula is changed to "
660 661
         " 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",
662 663 664 665 666 667 668
    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(
669 670
        "use_mkldnn",
        "(bool, default false) Only used in mkldnn kernel",
671
        false));
672

673
/* ========================================================================== */