mul_op.cc 9.7 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
2

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
6

7
    http://www.apache.org/licenses/LICENSE-2.0
8

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. */
14

15
#include <memory>
16
#include <string>
17
#include <unordered_map>
18
#include <vector>
19

20
#include "paddle/fluid/framework/op_registry.h"
P
Physher 已提交
21 22 23
#ifdef PADDLE_WITH_MKLDNN
#include "paddle/fluid/platform/mkldnn_helper.h"
#endif
24

C
Chen Weihang 已提交
25 26 27 28
#include "paddle/fluid/framework/infershape_utils.h"
#include "paddle/phi/core/infermeta_utils.h"
#include "paddle/phi/infermeta/backward.h"
#include "paddle/phi/infermeta/binary.h"
29 30 31
namespace paddle {
namespace operators {

32
using framework::OpKernelType;
D
dongzhihong 已提交
33

34 35 36
constexpr int kMULMKLDNNINT8 = 1;
constexpr int kMULMKLDNNFP32 = 2;

37
class MulOp : public framework::OperatorWithKernel {
Y
Yu Yang 已提交
38
 public:
39 40
  using framework::OperatorWithKernel::OperatorWithKernel;

P
Physher 已提交
41 42
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const {
43
    auto input_data_type = OperatorWithKernel::IndicateVarDataType(ctx, "X");
P
Physher 已提交
44

J
jiahongyu 已提交
45 46 47 48
#ifdef PADDLE_WITH_MKLDNN
    if (this->CanMKLDNNBeUsed(ctx, input_data_type)) {
      int customized_type_value =
          framework::OpKernelType::kDefaultCustomizedTypeValue;
49 50
      if (input_data_type == framework::DataTypeTrait<int8_t>::DataType() ||
          input_data_type == framework::DataTypeTrait<uint8_t>::DataType()) {
P
Physher 已提交
51
        customized_type_value = kMULMKLDNNINT8;
52 53 54 55 56 57
      } else if (input_data_type ==
                     framework::DataTypeTrait<
                         paddle::platform::bfloat16>::DataType() ||
                 input_data_type ==
                     framework::DataTypeTrait<float>::DataType()) {
        customized_type_value = kMULMKLDNNFP32;
P
Physher 已提交
58
      }
J
jiahongyu 已提交
59 60 61 62 63
      return framework::OpKernelType(input_data_type,
                                     ctx.GetPlace(),
                                     framework::DataLayout::kMKLDNN,
                                     framework::LibraryType::kMKLDNN,
                                     customized_type_value);
P
Physher 已提交
64 65 66
    }
#endif

J
jiahongyu 已提交
67
    return framework::OpKernelType(input_data_type, ctx.GetPlace());
P
Physher 已提交
68
  }
69 70
};

D
dongzhihong 已提交
71
class MulOpMaker : public framework::OpProtoAndCheckerMaker {
72
 public:
Y
Yu Yang 已提交
73
  void Make() override {
C
caoying03 已提交
74 75 76
    AddInput("X", "(Tensor), The first input tensor of mul op.");
    AddInput("Y", "(Tensor), The second input tensor of mul op.");
    AddOutput("Out", "(Tensor), The output tensor of mul op.");
F
WIP  
fengjiayi 已提交
77
    AddAttr<int>(
F
fengjiayi 已提交
78
        "x_num_col_dims",
C
caoying03 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
        R"DOC((int, default 1), The mul_op can take tensors with more than two
              dimensions as its inputs. If the input $X$ is a tensor with more
              than two dimensions, $X$ will be flattened into a two-dimensional
              matrix first. The flattening rule is: the first `num_col_dims`
              will be flattened to form the first dimension of the final matrix
              (the height of the matrix), and the rest `rank(X) - num_col_dims`
              dimensions are flattened to form the second dimension of the final
              matrix (the width of the matrix). As a result, height of the
              flattened matrix is equal to the product of $X$'s first
              `x_num_col_dims` dimensions' sizes, and width of the flattened
              matrix is equal to the product of $X$'s last `rank(x) - num_col_dims`
              dimensions' size. For example, suppose $X$ is a 6-dimensional
              tensor with the shape [2, 3, 4, 5, 6], and `x_num_col_dims` = 3.
              Thus, the flattened matrix will have a shape [2 x 3 x 4, 5 x 6] =
              [24, 30].
F
fengjiayi 已提交
94
        )DOC")
F
WIP  
fengjiayi 已提交
95
        .SetDefault(1)
F
fengjiayi 已提交
96
        .EqualGreaterThan(1);
F
WIP  
fengjiayi 已提交
97
    AddAttr<int>(
F
fengjiayi 已提交
98
        "y_num_col_dims",
C
caoying03 已提交
99 100 101 102
        R"DOC((int, default 1), The mul_op can take tensors with more than two,
              dimensions as its inputs. If the input $Y$ is a tensor with more
              than two dimensions, $Y$ will be flattened into a two-dimensional
              matrix first. The attribute `y_num_col_dims` determines how $Y$ is
C
caoying03 已提交
103
              flattened. See comments of `x_num_col_dims` for more details.
F
fengjiayi 已提交
104
        )DOC")
F
WIP  
fengjiayi 已提交
105
        .SetDefault(1)
F
fengjiayi 已提交
106
        .EqualGreaterThan(1);
107
    AddComment(R"DOC(
C
caoying03 已提交
108
Mul Operator.
K
kexinzhao 已提交
109

C
caoying03 已提交
110
This operator is used to perform matrix multiplication for input $X$ and $Y$.
111

112 113
The equation is:

C
caoying03 已提交
114
$$Out = X * Y$$
115

C
caoying03 已提交
116 117
Both the input $X$ and $Y$ can carry the LoD (Level of Details) information,
or not. But the output only shares the LoD information with input $X$.
K
kexinzhao 已提交
118

119 120 121 122
)DOC");
  }
};

C
chengduo 已提交
123 124
class MulOpInferVarType : public framework::PassInDtypeAndVarTypeToOutput {
 protected:
125
  std::unordered_map<std::string, std::string>& GetInputOutputWithSameType()
C
chengduo 已提交
126
      const override {
127 128
    static std::unordered_map<std::string, std::string> m{{"X", /*->*/ "Out"}};
    return m;
C
chengduo 已提交
129 130 131
  }
};

132
class MulGradOp : public framework::OperatorWithKernel {
Y
Yu Yang 已提交
133 134 135
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

136 137 138 139
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const {
    auto input_data_type = OperatorWithKernel::IndicateVarDataType(ctx, "X");

J
jiahongyu 已提交
140 141 142 143
#ifdef PADDLE_WITH_MKLDNN
    if (this->CanMKLDNNBeUsed(ctx, input_data_type)) {
      int customized_type_value =
          framework::OpKernelType::kDefaultCustomizedTypeValue;
144 145 146 147 148 149 150 151 152 153
      if (input_data_type == framework::DataTypeTrait<int8_t>::DataType() ||
          input_data_type == framework::DataTypeTrait<uint8_t>::DataType()) {
        customized_type_value = kMULMKLDNNINT8;
      } else if (input_data_type ==
                     framework::DataTypeTrait<
                         paddle::platform::bfloat16>::DataType() ||
                 input_data_type ==
                     framework::DataTypeTrait<float>::DataType()) {
        customized_type_value = kMULMKLDNNFP32;
      }
J
jiahongyu 已提交
154 155 156 157 158
      return framework::OpKernelType(input_data_type,
                                     ctx.GetPlace(),
                                     framework::DataLayout::kMKLDNN,
                                     framework::LibraryType::kMKLDNN,
                                     customized_type_value);
159 160 161
    }
#endif

J
jiahongyu 已提交
162
    return framework::OpKernelType(input_data_type, ctx.GetPlace());
163
  }
D
dongzhihong 已提交
164 165
};

H
hong 已提交
166 167
template <typename T>
class MulOpGradMaker : public framework::SingleGradOpMaker<T> {
S
sneaxiy 已提交
168
 public:
H
hong 已提交
169
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
S
sneaxiy 已提交
170 171

 protected:
172
  void Apply(GradOpPtr<T> retv) const override {
S
sneaxiy 已提交
173
    retv->SetType("mul_grad");
H
hong 已提交
174 175 176 177 178 179
    retv->SetInput("X", this->Input("X"));
    retv->SetInput("Y", this->Input("Y"));
    retv->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    retv->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    retv->SetOutput(framework::GradVarName("Y"), this->InputGrad("Y"));
    retv->SetAttrMap(this->Attrs());
S
sneaxiy 已提交
180 181 182
  }
};

183 184 185 186 187
class MulDoubleGradOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
188 189 190
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "mul");
    OP_INOUT_CHECK(ctx->HasInput("Y"), "Input", "Y", "mul");
    OP_INOUT_CHECK(ctx->HasInput("DOut"), "Input", "DOut", "mul");
191

L
lvmengsi 已提交
192 193
    if (ctx->HasOutput("DDOut") &&
        (ctx->HasInput("DDX") || (ctx->HasInput("DDY")))) {
194 195 196
      ctx->ShareDim("DOut", "DDOut");
    }
    if (ctx->HasOutput("DX") && ctx->HasInput("DDY")) {
197 198
      ctx->ShareDim("X", "DX");
    }
199
    if (ctx->HasOutput("DY") && ctx->HasInput("DDX")) {
200 201 202 203 204
      ctx->ShareDim("Y", "DY");
    }
  }
};

H
hong 已提交
205 206
template <typename T>
class MulDoubleGradMaker : public framework::SingleGradOpMaker<T> {
207
 public:
H
hong 已提交
208
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
209 210

 protected:
211
  void Apply(GradOpPtr<T> retv) const override {
212 213
    retv->SetType("mul_grad_grad");

H
hong 已提交
214 215 216 217 218
    retv->SetInput("X", this->Input("X"));
    retv->SetInput("Y", this->Input("Y"));
    retv->SetInput("DOut", this->Input(framework::GradVarName("Out")));
    retv->SetInput("DDX", this->OutputGrad(framework::GradVarName("X")));
    retv->SetInput("DDY", this->OutputGrad(framework::GradVarName("Y")));
219

H
hong 已提交
220 221
    auto ddx = this->OutputGrad(framework::GradVarName("X"));
    auto ddw = this->OutputGrad(framework::GradVarName("Y"));
222

L
lvmengsi 已提交
223
    if (!ddx.empty() || !ddw.empty()) {
H
hong 已提交
224
      retv->SetOutput("DDOut", this->InputGrad(framework::GradVarName("Out")));
L
lvmengsi 已提交
225
    }
226 227 228 229
    retv->SetOutput(
        "DX", ddw.empty() ? this->EmptyInputGrad() : this->InputGrad("X"));
    retv->SetOutput(
        "DY", ddx.empty() ? this->EmptyInputGrad() : this->InputGrad("Y"));
230

H
hong 已提交
231
    retv->SetAttrMap(this->Attrs());
232 233 234
  }
};

235 236 237
}  // namespace operators
}  // namespace paddle

D
dongzhihong 已提交
238
namespace ops = paddle::operators;
239 240
DECLARE_INFER_SHAPE_FUNCTOR(mul,
                            MulInferShapeFunctor,
C
Chen Weihang 已提交
241
                            PD_INFER_META(phi::MatmulWithFlattenInferMeta));
242 243 244 245
REGISTER_OPERATOR(mul,
                  ops::MulOp,
                  ops::MulOpMaker,
                  ops::MulOpInferVarType,
H
hong 已提交
246
                  ops::MulOpGradMaker<paddle::framework::OpDesc>,
C
Chen Weihang 已提交
247 248
                  ops::MulOpGradMaker<paddle::imperative::OpBase>,
                  MulInferShapeFunctor);
P
Physher 已提交
249

250 251
DECLARE_INFER_SHAPE_FUNCTOR(mul_grad,
                            MulGradInferShapeFunctor,
C
Chen Weihang 已提交
252
                            PD_INFER_META(phi::GeneralBinaryGradInferMeta));
253 254
REGISTER_OPERATOR(mul_grad,
                  ops::MulGradOp,
H
hong 已提交
255
                  ops::MulDoubleGradMaker<paddle::framework::OpDesc>,
C
Chen Weihang 已提交
256 257
                  ops::MulDoubleGradMaker<paddle::imperative::OpBase>,
                  MulGradInferShapeFunctor);
P
Physher 已提交
258

259
REGISTER_OPERATOR(mul_grad_grad, ops::MulDoubleGradOp);