mul_op.cc 10.8 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
using framework::Tensor;

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

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

P
Physher 已提交
42 43 44 45 46 47
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const {
    framework::LibraryType library = framework::LibraryType::kPlain;
    framework::DataLayout layout = framework::DataLayout::kAnyLayout;
    int customized_type_value =
        framework::OpKernelType::kDefaultCustomizedTypeValue;
48
    auto input_data_type = OperatorWithKernel::IndicateVarDataType(ctx, "X");
P
Physher 已提交
49 50
#ifdef PADDLE_WITH_MKLDNN
    if (library == framework::LibraryType::kPlain &&
51
        this->CanMKLDNNBeUsed(ctx, input_data_type)) {
P
Physher 已提交
52 53 54
      library = framework::LibraryType::kMKLDNN;
      layout = framework::DataLayout::kMKLDNN;

55 56
      if (input_data_type == framework::DataTypeTrait<int8_t>::DataType() ||
          input_data_type == framework::DataTypeTrait<uint8_t>::DataType()) {
P
Physher 已提交
57
        customized_type_value = kMULMKLDNNINT8;
58 59 60 61 62 63
      } else if (input_data_type ==
                     framework::DataTypeTrait<
                         paddle::platform::bfloat16>::DataType() ||
                 input_data_type ==
                     framework::DataTypeTrait<float>::DataType()) {
        customized_type_value = kMULMKLDNNFP32;
P
Physher 已提交
64 65 66 67 68 69 70
      }
    }
#endif

    return framework::OpKernelType(input_data_type, ctx.GetPlace(), layout,
                                   library, customized_type_value);
  }
71 72
};

D
dongzhihong 已提交
73
class MulOpMaker : public framework::OpProtoAndCheckerMaker {
74
 public:
Y
Yu Yang 已提交
75
  void Make() override {
C
caoying03 已提交
76 77 78
    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.");
P
Physher 已提交
79 80
    AddAttr<bool>("use_mkldnn",
                  "(bool, default false) Only used in mkldnn kernel")
81 82
        .SetDefault(false)
        .AsExtra();
F
WIP  
fengjiayi 已提交
83
    AddAttr<int>(
F
fengjiayi 已提交
84
        "x_num_col_dims",
C
caoying03 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
        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 已提交
100
        )DOC")
F
WIP  
fengjiayi 已提交
101
        .SetDefault(1)
F
fengjiayi 已提交
102
        .EqualGreaterThan(1);
F
WIP  
fengjiayi 已提交
103
    AddAttr<int>(
F
fengjiayi 已提交
104
        "y_num_col_dims",
C
caoying03 已提交
105 106 107 108
        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 已提交
109
              flattened. See comments of `x_num_col_dims` for more details.
F
fengjiayi 已提交
110
        )DOC")
F
WIP  
fengjiayi 已提交
111
        .SetDefault(1)
F
fengjiayi 已提交
112
        .EqualGreaterThan(1);
113 114 115 116 117
    AddAttr<float>(
        "scale_x",
        "scale_x to be used for int8 mul input data x. scale_x has the"
        "same purpose as scale_in in OPs that support quantization."
        "Only to be used with MKL-DNN INT8")
118 119
        .SetDefault(1.0f)
        .AsExtra();
120 121 122 123 124
    AddAttr<std::vector<float>>(
        "scale_y",
        "scale_y to be used for int8 mul input data y. scale_y has the"
        "same purpose as scale_weights in OPs that support quantization."
        "Only to be used with MKL-DNN INT8")
125 126
        .SetDefault({1.0f})
        .AsExtra();
P
Physher 已提交
127 128 129
    AddAttr<float>("scale_out",
                   "scale_out to be used for int8 output data."
                   "Only used with MKL-DNN INT8")
130 131
        .SetDefault(1.0f)
        .AsExtra();
P
Physher 已提交
132 133 134 135
    AddAttr<bool>(
        "force_fp32_output",
        "(bool, default false) Force quantize kernel output FP32, only "
        "used in quantized MKL-DNN.")
136 137
        .SetDefault(false)
        .AsExtra();
138
    AddComment(R"DOC(
C
caoying03 已提交
139
Mul Operator.
K
kexinzhao 已提交
140

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

143 144
The equation is:

C
caoying03 已提交
145
$$Out = X * Y$$
146

C
caoying03 已提交
147 148
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 已提交
149

150 151 152 153
)DOC");
  }
};

C
chengduo 已提交
154 155
class MulOpInferVarType : public framework::PassInDtypeAndVarTypeToOutput {
 protected:
156
  std::unordered_map<std::string, std::string>& GetInputOutputWithSameType()
C
chengduo 已提交
157
      const override {
158 159
    static std::unordered_map<std::string, std::string> m{{"X", /*->*/ "Out"}};
    return m;
C
chengduo 已提交
160 161 162
  }
};

163
class MulGradOp : public framework::OperatorWithKernel {
Y
Yu Yang 已提交
164 165 166
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const {
    framework::LibraryType library = framework::LibraryType::kPlain;
    framework::DataLayout layout = framework::DataLayout::kAnyLayout;
    int customized_type_value =
        framework::OpKernelType::kDefaultCustomizedTypeValue;
    auto input_data_type = OperatorWithKernel::IndicateVarDataType(ctx, "X");
#ifdef PADDLE_WITH_MKLDNN
    if (library == framework::LibraryType::kPlain &&
        this->CanMKLDNNBeUsed(ctx, input_data_type)) {
      library = framework::LibraryType::kMKLDNN;
      layout = framework::DataLayout::kMKLDNN;

      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;
      }
    }
#endif

    return framework::OpKernelType(input_data_type, ctx.GetPlace(), layout,
                                   library, customized_type_value);
  }
D
dongzhihong 已提交
196 197
};

H
hong 已提交
198 199
template <typename T>
class MulOpGradMaker : public framework::SingleGradOpMaker<T> {
S
sneaxiy 已提交
200
 public:
H
hong 已提交
201
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
S
sneaxiy 已提交
202 203

 protected:
204
  void Apply(GradOpPtr<T> retv) const override {
S
sneaxiy 已提交
205
    retv->SetType("mul_grad");
H
hong 已提交
206 207 208 209 210 211
    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 已提交
212 213 214
  }
};

215 216 217 218 219
class MulDoubleGradOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
220 221 222
    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");
223

L
lvmengsi 已提交
224 225
    if (ctx->HasOutput("DDOut") &&
        (ctx->HasInput("DDX") || (ctx->HasInput("DDY")))) {
226 227 228
      ctx->ShareDim("DOut", "DDOut");
    }
    if (ctx->HasOutput("DX") && ctx->HasInput("DDY")) {
229 230
      ctx->ShareDim("X", "DX");
    }
231
    if (ctx->HasOutput("DY") && ctx->HasInput("DDX")) {
232 233 234 235 236
      ctx->ShareDim("Y", "DY");
    }
  }
};

H
hong 已提交
237 238
template <typename T>
class MulDoubleGradMaker : public framework::SingleGradOpMaker<T> {
239
 public:
H
hong 已提交
240
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
241 242

 protected:
243
  void Apply(GradOpPtr<T> retv) const override {
244 245
    retv->SetType("mul_grad_grad");

H
hong 已提交
246 247 248 249 250
    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")));
251

H
hong 已提交
252 253
    auto ddx = this->OutputGrad(framework::GradVarName("X"));
    auto ddw = this->OutputGrad(framework::GradVarName("Y"));
254

L
lvmengsi 已提交
255
    if (!ddx.empty() || !ddw.empty()) {
H
hong 已提交
256
      retv->SetOutput("DDOut", this->InputGrad(framework::GradVarName("Out")));
L
lvmengsi 已提交
257
    }
258 259 260 261
    retv->SetOutput(
        "DX", ddw.empty() ? this->EmptyInputGrad() : this->InputGrad("X"));
    retv->SetOutput(
        "DY", ddx.empty() ? this->EmptyInputGrad() : this->InputGrad("Y"));
262

H
hong 已提交
263
    retv->SetAttrMap(this->Attrs());
264 265 266
  }
};

267 268 269
}  // namespace operators
}  // namespace paddle

D
dongzhihong 已提交
270
namespace ops = paddle::operators;
C
Chen Weihang 已提交
271 272
DECLARE_INFER_SHAPE_FUNCTOR(mul, MulInferShapeFunctor,
                            PD_INFER_META(phi::MatmulWithFlattenInferMeta));
C
chengduo 已提交
273
REGISTER_OPERATOR(mul, ops::MulOp, ops::MulOpMaker, ops::MulOpInferVarType,
H
hong 已提交
274
                  ops::MulOpGradMaker<paddle::framework::OpDesc>,
C
Chen Weihang 已提交
275 276
                  ops::MulOpGradMaker<paddle::imperative::OpBase>,
                  MulInferShapeFunctor);
P
Physher 已提交
277

C
Chen Weihang 已提交
278 279
DECLARE_INFER_SHAPE_FUNCTOR(mul_grad, MulGradInferShapeFunctor,
                            PD_INFER_META(phi::GeneralBinaryGradInferMeta));
H
hong 已提交
280 281
REGISTER_OPERATOR(mul_grad, ops::MulGradOp,
                  ops::MulDoubleGradMaker<paddle::framework::OpDesc>,
C
Chen Weihang 已提交
282 283
                  ops::MulDoubleGradMaker<paddle::imperative::OpBase>,
                  MulGradInferShapeFunctor);
P
Physher 已提交
284

285
REGISTER_OPERATOR(mul_grad_grad, ops::MulDoubleGradOp);