prelu_op.cc 5.4 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
L
Luo Tao 已提交
2 3 4 5 6 7 8 9 10
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
Z
zchen0211 已提交
11

Y
Yi Wang 已提交
12
#include "paddle/fluid/operators/prelu_op.h"
13
#include <string>
Z
zchen0211 已提交
14 15 16 17

namespace paddle {
namespace operators {

Z
fix  
zchen0211 已提交
18
class PReluOp : public framework::OperatorWithKernel {
Z
zchen0211 已提交
19
 public:
Z
fix  
zchen0211 已提交
20
  PReluOp(const std::string &type, const framework::VariableNameMap &inputs,
Z
zchen0211 已提交
21 22 23 24
          const framework::VariableNameMap &outputs,
          const framework::AttributeMap &attrs)
      : OperatorWithKernel(type, inputs, outputs, attrs) {}

25
  void InferShape(framework::InferShapeContext *ctx) const override {
J
jerrywgz 已提交
26 27 28
    std::string mode = ctx->Attrs().Get<std::string>("mode");

    auto x_dim = ctx->GetInputDim("X");
J
jerrywgz 已提交
29 30 31 32
    PADDLE_ENFORCE(ctx->HasInput("X"),
                   "Input(X) of PreluOp should not be null");
    PADDLE_ENFORCE(ctx->HasInput("Alpha"),
                   "Input(Alpha) of PreluOp should not be null");
J
jerrywgz 已提交
33

J
jerrywgz 已提交
34 35
    PADDLE_ENFORCE(ctx->HasOutput("Out"),
                   "Output(Out) of PreluOp should not be null");
J
jerrywgz 已提交
36 37 38 39 40 41 42 43 44
    if (mode == "all") {
      PADDLE_ENFORCE(product(ctx->GetInputDim("Alpha")) == 1,
                     "For mode 'all', size of weight Alpha must be one.");
    } else if (mode == "channel") {
      PADDLE_ENFORCE(product(ctx->GetInputDim("Alpha")) == x_dim[1],
                     "For channel-wise mode, size of weight Alpha must be "
                     "equal to the number of channels, should be %d",
                     x_dim[1]);
    } else if (mode == "element") {
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
      auto alpha_dim = ctx->GetInputDim("Alpha");
      auto alpha_rank = alpha_dim.size();
      auto x_rank = x_dim.size();
      size_t x_product = 1;
      size_t alpha_product = 1;
      PADDLE_ENFORCE_EQ(alpha_rank, x_rank,
                        "For element-wise mode, rank of weight Alpha must be ",
                        "equal to the rank of input.");
      for (int64_t i = x_rank - 1; i > 0; i--) {
        x_product *= x_dim[i];
        alpha_product *= alpha_dim[i];
      }
      PADDLE_ENFORCE_EQ(x_product, alpha_product,
                        "For element-wise mode, size of weight Alpha must be "
                        "equal to the number of input.");
J
jerrywgz 已提交
60 61 62
    } else {
      PADDLE_THROW("Unkown mode %s", mode);
    }
63
    ctx->ShareDim("X", /*->*/ "Out");
Q
Qiao Longfei 已提交
64
    ctx->ShareLoD("X", /*->*/ "Out");
Z
zchen0211 已提交
65
  }
J
jerrywgz 已提交
66 67 68 69

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
70 71 72
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        ctx.device_context());
J
jerrywgz 已提交
73
  }
Z
zchen0211 已提交
74 75
};

Z
fix  
zchen0211 已提交
76
class PReluOpMaker : public framework::OpProtoAndCheckerMaker {
Z
zchen0211 已提交
77
 public:
Y
Yu Yang 已提交
78
  void Make() override {
Z
zchen0211 已提交
79
    AddInput("X", "The input tensor of prelu operator.");
K
kexinzhao 已提交
80 81 82 83
    AddInput("Alpha", "The alpha weight of prelu operator.");
    AddOutput("Out", "The output tensor of prelu operator.");
    AddComment(R"DOC(
PRelu Operator.
Z
zchen0211 已提交
84
The equation is:
K
kexinzhao 已提交
85 86 87 88 89 90 91
$$
f(x) =
\begin{cases}
\alpha * x, \quad  \text{if} \ x < 0 \\
x,         \qquad  \text{if} \ x >= 0
\end{cases}
$$
92
The input `X` can carry the LoD (Level of Details) information,
K
kexinzhao 已提交
93
or not. And the output shares the LoD information with input `X`.
94
There are modes:
J
jerrywgz 已提交
95 96
  all: all elements share same weight
  channel: elements in a channel share same weight
97
  element: each element has a weight
Z
zchen0211 已提交
98
)DOC");
J
jerrywgz 已提交
99 100
    AddAttr<std::string>("mode", "The mode for inputs to share weights.")
        .SetDefault("all");
Z
zchen0211 已提交
101 102 103 104
  }
};

// The operator to calculate gradients of a prelu operator.
Z
fix  
zchen0211 已提交
105
class PReluGradOp : public framework::OperatorWithKernel {
Z
zchen0211 已提交
106 107 108
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

109
  void InferShape(framework::InferShapeContext *ctx) const override {
Q
Qiao Longfei 已提交
110 111 112
    PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) must not be null.");
    PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
                   "Input(Out@GRAD) should not be null");
J
jerrywgz 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126
    auto x_grad_name = framework::GradVarName("X");
    auto alpha_grad_name = framework::GradVarName("Alpha");

    if (ctx->HasOutput(x_grad_name)) {
      ctx->SetOutputDim(x_grad_name, ctx->GetInputDim("X"));
    }
    if (ctx->HasOutput(alpha_grad_name)) {
      ctx->SetOutputDim(alpha_grad_name, ctx->GetInputDim("Alpha"));
    }
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
127 128 129
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        ctx.device_context());
Z
zchen0211 已提交
130 131 132 133 134 135 136 137
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

H
hong 已提交
138 139 140 141
REGISTER_OPERATOR(
    prelu, ops::PReluOp, ops::PReluOpMaker,
    paddle::framework::DefaultGradOpMaker<paddle::framework::OpDesc, true>,
    paddle::framework::DefaultGradOpMaker<paddle::imperative::OpBase, true>);
142
REGISTER_OPERATOR(prelu_grad, ops::PReluGradOp);
Q
QI JUN 已提交
143 144 145 146 147
REGISTER_OP_CPU_KERNEL(
    prelu, ops::PReluKernel<paddle::platform::CPUDeviceContext, float>);
REGISTER_OP_CPU_KERNEL(
    prelu_grad,
    ops::PReluGradKernel<paddle::platform::CPUDeviceContext, float>);