prelu_op.cc 7.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

12
#include <memory>
13
#include <string>
14

15 16 17 18 19
#include "paddle/fluid/framework/infershape_utils.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/op_version_registry.h"
#include "paddle/phi/core/infermeta_utils.h"
#include "paddle/phi/infermeta/binary.h"
Z
zchen0211 已提交
20 21 22 23

namespace paddle {
namespace operators {

24 25
using Tensor = framework::Tensor;

J
Jacek Czaja 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
framework::OpKernelType innerGetKernelTypeForVar(
    const Tensor &tensor, const framework::OpKernelType &expected_kernel_type) {
#ifdef PADDLE_WITH_MKLDNN
  auto isOneDNNKernelChosen =
      (expected_kernel_type.data_layout_ == framework::DataLayout::kMKLDNN);
  auto isNotOneDNNTensor = (tensor.layout() != framework::DataLayout::kMKLDNN);
  auto isModelNHWC =
      (paddle::platform::MKLDNNDeviceContext::tls()
           .get_cur_paddle_data_layout() == framework::DataLayout::kNHWC);
  // All inputs (including alpha) need shape rotating
  if (isOneDNNKernelChosen && isNotOneDNNTensor && isModelNHWC) {
    return framework::OpKernelType(expected_kernel_type.data_type_,
                                   tensor.place(),
                                   framework::DataLayout::kNHWC);
  }
#endif
42 43
  return framework::OpKernelType(
      expected_kernel_type.data_type_, tensor.place(), tensor.layout());
J
Jacek Czaja 已提交
44 45
}

Z
fix  
zchen0211 已提交
46
class PReluOp : public framework::OperatorWithKernel {
Z
zchen0211 已提交
47
 public:
48 49
  PReluOp(const std::string &type,
          const framework::VariableNameMap &inputs,
Z
zchen0211 已提交
50 51 52 53
          const framework::VariableNameMap &outputs,
          const framework::AttributeMap &attrs)
      : OperatorWithKernel(type, inputs, outputs, attrs) {}

J
jerrywgz 已提交
54 55 56
 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
57 58 59 60 61
    auto input_data_type =
        framework::OperatorWithKernel::IndicateVarDataType(ctx, "X");

#ifdef PADDLE_WITH_MKLDNN
    if (this->CanMKLDNNBeUsed(ctx, input_data_type)) {
62 63
      return framework::OpKernelType(input_data_type,
                                     ctx.GetPlace(),
64 65 66 67 68
                                     framework::DataLayout::kMKLDNN,
                                     framework::LibraryType::kMKLDNN);
    }
#endif
    return framework::OpKernelType(input_data_type, ctx.GetPlace());
J
jerrywgz 已提交
69
  }
J
Jacek Czaja 已提交
70 71

  framework::OpKernelType GetKernelTypeForVar(
72 73
      const std::string &var_name,
      const Tensor &tensor,
J
Jacek Czaja 已提交
74 75 76
      const framework::OpKernelType &expected_kernel_type) const {
    return innerGetKernelTypeForVar(tensor, expected_kernel_type);
  }
Z
zchen0211 已提交
77 78
};

Z
fix  
zchen0211 已提交
79
class PReluOpMaker : public framework::OpProtoAndCheckerMaker {
Z
zchen0211 已提交
80
 public:
Y
Yu Yang 已提交
81
  void Make() override {
Z
zchen0211 已提交
82
    AddInput("X", "The input tensor of prelu operator.");
K
kexinzhao 已提交
83 84 85 86
    AddInput("Alpha", "The alpha weight of prelu operator.");
    AddOutput("Out", "The output tensor of prelu operator.");
    AddComment(R"DOC(
PRelu Operator.
Z
zchen0211 已提交
87
The equation is:
K
kexinzhao 已提交
88 89 90 91 92 93 94
$$
f(x) =
\begin{cases}
\alpha * x, \quad  \text{if} \ x < 0 \\
x,         \qquad  \text{if} \ x >= 0
\end{cases}
$$
95
The input `X` can carry the LoD (Level of Details) information,
K
kexinzhao 已提交
96
or not. And the output shares the LoD information with input `X`.
97
There are modes:
J
jerrywgz 已提交
98 99
  all: all elements share same weight
  channel: elements in a channel share same weight
100
  element: each element has a weight
Z
zchen0211 已提交
101
)DOC");
J
jerrywgz 已提交
102 103
    AddAttr<std::string>("mode", "The mode for inputs to share weights.")
        .SetDefault("all");
104 105 106
    AddAttr<std::string>("data_format",
                         "Data format that specifies the layout of input")
        .SetDefault("NCHW");
107 108
    AddAttr<bool>("use_mkldnn",
                  "(bool, default false) Only used in mkldnn kernel")
C
cc 已提交
109 110
        .SetDefault(false)
        .AsExtra();
111 112 113 114
    AddAttr<std::string>(
        "mkldnn_data_type",
        "(string, default \"float32\"). Data type of mkldnn kernel")
        .SetDefault("float32")
C
cc 已提交
115 116
        .InEnum({"float32", "bfloat16"})
        .AsExtra();
117 118 119
    AddAttr<bool>("is_test",
                  "(bool, default false) Set to true for inference only, false "
                  "for training. Some layers may run faster when this is true.")
C
cc 已提交
120 121
        .SetDefault(false)
        .AsExtra();
Z
zchen0211 已提交
122 123 124 125
  }
};

// The operator to calculate gradients of a prelu operator.
Z
fix  
zchen0211 已提交
126
class PReluGradOp : public framework::OperatorWithKernel {
Z
zchen0211 已提交
127 128 129
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

130
  void InferShape(framework::InferShapeContext *ctx) const override {
131
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "prelu");
132 133 134 135
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")),
                   "Input",
                   "Out@GRAD",
                   "prelu");
136

J
jerrywgz 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149 150
    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 {
151 152 153 154 155
    auto input_data_type =
        framework::OperatorWithKernel::IndicateVarDataType(ctx, "X");

#ifdef PADDLE_WITH_MKLDNN
    if (this->CanMKLDNNBeUsed(ctx, input_data_type)) {
156 157
      return framework::OpKernelType(input_data_type,
                                     ctx.GetPlace(),
158 159 160 161 162
                                     framework::DataLayout::kMKLDNN,
                                     framework::LibraryType::kMKLDNN);
    }
#endif
    return framework::OpKernelType(input_data_type, ctx.GetPlace());
Z
zchen0211 已提交
163
  }
J
Jacek Czaja 已提交
164 165

  framework::OpKernelType GetKernelTypeForVar(
166 167
      const std::string &var_name,
      const Tensor &tensor,
J
Jacek Czaja 已提交
168 169 170
      const framework::OpKernelType &expected_kernel_type) const {
    return innerGetKernelTypeForVar(tensor, expected_kernel_type);
  }
Z
zchen0211 已提交
171 172
};

173 174 175 176 177 178
template <typename T>
class PReluGradOpMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
179
  void Apply(GradOpPtr<T> op) const override {
180 181 182 183 184 185 186 187 188 189
    op->SetType("prelu_grad");
    op->SetInput("X", this->Input("X"));
    op->SetInput("Alpha", this->Input("Alpha"));
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetOutput(framework::GradVarName("Alpha"), this->InputGrad("Alpha"));
    op->SetAttrMap(this->Attrs());
  }
};

Z
zchen0211 已提交
190 191 192 193 194
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

195 196
DECLARE_INFER_SHAPE_FUNCTOR(prelu,
                            PReluInferShapeFunctor,
197
                            PD_INFER_META(phi::PReluInferMeta));
198 199 200
REGISTER_OPERATOR(prelu,
                  ops::PReluOp,
                  ops::PReluOpMaker,
201
                  ops::PReluGradOpMaker<paddle::framework::OpDesc>,
202 203
                  ops::PReluGradOpMaker<paddle::imperative::OpBase>,
                  PReluInferShapeFunctor);
204
REGISTER_OPERATOR(prelu_grad, ops::PReluGradOp);