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

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 "paddle/operators/mul_op.h"
16 17 18 19

namespace paddle {
namespace operators {

D
dongzhihong 已提交
20 21
using framework::Tensor;

22
class MulOpShapeInference : public framework::InferShapeBase {
Y
Yu Yang 已提交
23
 public:
24
  void operator()(framework::InferShapeContext* ctx) const override {
Q
Qiao Longfei 已提交
25 26 27 28 29 30 31
    PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) of MulOp should not be null.");
    PADDLE_ENFORCE(ctx->HasInput("Y"), "Input(Y) of MulOp should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput("Out"),
                   "Output(Out) of MulOp should not be null.");

    auto x_dims = ctx->GetInputDim("X");
    auto y_dims = ctx->GetInputDim("Y");
Y
Yu Yang 已提交
32

Q
Qiao Longfei 已提交
33 34
    int x_num_col_dims = ctx->Attrs().Get<int>("x_num_col_dims");
    int y_num_col_dims = ctx->Attrs().Get<int>("y_num_col_dims");
F
WIP  
fengjiayi 已提交
35

Y
Yu Yang 已提交
36 37 38 39
    VLOG(3) << "mul operator x.shape=" << x_dims << " y.shape=" << y_dims
            << " x_num_col_dims=" << x_num_col_dims
            << " y_num_col_dims=" << y_num_col_dims;

40 41 42 43 44 45 46 47
    PADDLE_ENFORCE_GT(
        x_dims.size(), x_num_col_dims,
        "The input tensor X's rank of MulOp should be larger than "
        "x_num_col_dims.");
    PADDLE_ENFORCE_GT(
        y_dims.size(), y_num_col_dims,
        "The input tensor Y's rank of MulOp should be larger than "
        "y_num_col_dims.");
48

F
fengjiayi 已提交
49 50
    auto x_mat_dims = framework::flatten_to_2d(x_dims, x_num_col_dims);
    auto y_mat_dims = framework::flatten_to_2d(y_dims, y_num_col_dims);
51

Y
Yan Chunwei 已提交
52
    PADDLE_ENFORCE_EQ(
53
        x_mat_dims[1], y_mat_dims[0],
54
        "First matrix's width must be equal with second matrix's height.");
Y
Yu Yang 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67
    std::vector<int64_t> output_dims;
    output_dims.reserve(
        static_cast<size_t>(x_num_col_dims + y_dims.size() - y_num_col_dims));

    for (int i = 0; i < x_num_col_dims; ++i) {
      output_dims.push_back(x_dims[i]);
    }

    for (int i = y_num_col_dims; i < y_dims.size(); ++i) {
      output_dims.push_back(y_dims[i]);
    }

    ctx->SetOutputDim("Out", framework::make_ddim(output_dims));
Q
Qiao Longfei 已提交
68
    ctx->ShareLoD("X", /*->*/ "Out");
69 70 71
  }
};

D
dongzhihong 已提交
72
class MulOpMaker : public framework::OpProtoAndCheckerMaker {
73
 public:
74
  MulOpMaker(OpProto* proto, OpAttrChecker* op_checker)
75
      : OpProtoAndCheckerMaker(proto, op_checker) {
C
caoying03 已提交
76 77 78
    AddInput("X", "The first input tensor of the mul op.");
    AddInput("Y", "The second input tensor of the mul op.");
    AddOutput("Out", "The output tensor of the mul op.");
F
WIP  
fengjiayi 已提交
79
    AddAttr<int>(
F
fengjiayi 已提交
80
        "x_num_col_dims",
K
kexinzhao 已提交
81
        "(int, default 1) "
C
caoying03 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95
        R"DOC(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 flatten into a two-dimensional matrix
              first. The flatten rule is: the first `num_col_dims` will be
              flatten to form the first dimension of the matrix (height of the
              matrix), and the rest `rank(X) - num_col_dims` dimensions are
             flattened to form the second dimension of the matrix (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. Then, the flattened
             matrix will have a shape [2 x 3 x 4, 5 x 6] = [24, 30].
F
fengjiayi 已提交
96
        )DOC")
F
WIP  
fengjiayi 已提交
97
        .SetDefault(1)
F
fengjiayi 已提交
98
        .EqualGreaterThan(1);
F
WIP  
fengjiayi 已提交
99
    AddAttr<int>(
F
fengjiayi 已提交
100
        "y_num_col_dims",
K
kexinzhao 已提交
101
        "(int, default 1) "
C
caoying03 已提交
102 103 104 105 106 107
        R"DOC(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 flatten into a two-dimensional matrix
              first. The attribute `y_num_col_dims` is used to flatten `Y` into
              a two-dimensional matrix. See the comments of `x_num_col_dims` for
              more details.
F
fengjiayi 已提交
108
        )DOC")
F
WIP  
fengjiayi 已提交
109
        .SetDefault(1)
F
fengjiayi 已提交
110
        .EqualGreaterThan(1);
111
    AddComment(R"DOC(
K
kexinzhao 已提交
112 113 114
Mul Operator. 

This operator is used to perform matrix multiplication for input X and Y.
115

116 117
The equation is:

K
kexinzhao 已提交
118
    $$Out = X * Y$$
119 120

Both the input `X` and `Y` can carry the LoD (Level of Details) information,
K
kexinzhao 已提交
121 122
or not. But the output only shares the LoD information with input `X`.

123 124 125 126
)DOC");
  }
};

D
dongzhihong 已提交
127
class MulOpGrad : public framework::OperatorWithKernel {
Y
Yu Yang 已提交
128 129 130
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

131
  void InferShape(framework::InferShapeContext* ctx) const override {
Q
Qiao Longfei 已提交
132 133 134 135 136 137 138
    PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should not be null");
    PADDLE_ENFORCE(ctx->HasInput("Y"), "Input(Y) should not be null");
    PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
                   "Input(Out@GRAD) should not be null");
    auto x_dims = ctx->GetInputDim("X");
    auto y_dims = ctx->GetInputDim("Y");
    auto out_dims = ctx->GetInputDim(framework::GradVarName("Out"));
139

Q
Qiao Longfei 已提交
140 141 142 143
    auto x_mat_dims = framework::flatten_to_2d(
        x_dims, ctx->Attrs().Get<int>("x_num_col_dims"));
    auto y_mat_dims = framework::flatten_to_2d(
        y_dims, ctx->Attrs().Get<int>("y_num_col_dims"));
144

Q
Qiao Longfei 已提交
145 146 147 148 149 150 151 152 153
    auto x_grad_name = framework::GradVarName("X");
    auto y_grad_name = framework::GradVarName("Y");

    if (ctx->HasOutput(x_grad_name)) {
      ctx->SetOutputDim(x_grad_name, x_dims);
    }
    if (ctx->HasOutput(y_grad_name)) {
      ctx->SetOutputDim(y_grad_name, y_dims);
    }
D
dongzhihong 已提交
154 155 156
  }
};

157 158 159
}  // namespace operators
}  // namespace paddle

D
dongzhihong 已提交
160
namespace ops = paddle::operators;
161 162 163 164
REGISTER_OPERATOR(mul, paddle::framework::OperatorWithKernel, ops::MulOpMaker,
                  ops::MulOpShapeInference,
                  paddle::framework::DefaultGradOpDescMaker<true>);
REGISTER_OPERATOR(mul_grad, ops::MulOpGrad);
Q
QI JUN 已提交
165 166 167 168
REGISTER_OP_CPU_KERNEL(
    mul, ops::MulKernel<paddle::platform::CPUDeviceContext, float>);
REGISTER_OP_CPU_KERNEL(
    mul_grad, ops::MulGradKernel<paddle::platform::CPUDeviceContext, float>);