mul_op.cc 5.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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

15
#include "paddle/operators/mul_op.h"
16 17 18 19

namespace paddle {
namespace operators {

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

D
dongzhihong 已提交
23
class MulOp : public framework::OperatorWithKernel {
Y
Yu Yang 已提交
24 25
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
26

27
 protected:
D
dongzhihong 已提交
28
  void InferShape(const framework::InferShapeContext &ctx) const override {
29 30 31 32 33 34 35
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("X"),
                            "Input(X) of MulOp should not be null.");
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("Y"),
                            "Input(Y) of MulOp should not be null.");
    PADDLE_ENFORCE_NOT_NULL(ctx.OutputVar("Out"),
                            "Output(Out) of MulOp should not be null.");

36 37
    auto x_dims = ctx.Input<Tensor>("X")->dims();
    auto y_dims = ctx.Input<Tensor>("Y")->dims();
F
fengjiayi 已提交
38 39
    int x_num_col_dims = Attr<int>("x_num_col_dims");
    int y_num_col_dims = Attr<int>("y_num_col_dims");
F
WIP  
fengjiayi 已提交
40

F
fengjiayi 已提交
41
    PADDLE_ENFORCE(x_dims.size() > x_num_col_dims,
F
WIP  
fengjiayi 已提交
42
                   "The rank of input tensor X(%s) should be larger than "
F
fengjiayi 已提交
43
                   "`mul_op`'s `x_num_col_dims`.",
44
                   ctx.op().Input("X"));
F
fengjiayi 已提交
45
    PADDLE_ENFORCE(y_dims.size() > y_num_col_dims,
F
WIP  
fengjiayi 已提交
46
                   "The rank of input tensor Y(%s) should be larger than "
F
fengjiayi 已提交
47
                   "`mul_op`'s `y_num_col_dims`.",
48
                   ctx.op().Input("Y"));
49

F
fengjiayi 已提交
50 51
    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);
52

Y
Yan Chunwei 已提交
53
    PADDLE_ENFORCE_EQ(
54
        x_mat_dims[1], y_mat_dims[0],
55
        "First matrix's width must be equal with second matrix's height.");
56 57
    ctx.Output<framework::LoDTensor>("Out")->Resize(
        {x_mat_dims[0], y_mat_dims[1]});
58
    ctx.ShareLoD("X", "Out");
59 60 61
  }
};

D
dongzhihong 已提交
62
class MulOpMaker : public framework::OpProtoAndCheckerMaker {
63
 public:
D
dongzhihong 已提交
64
  MulOpMaker(framework::OpProto *proto, framework::OpAttrChecker *op_checker)
65
      : OpProtoAndCheckerMaker(proto, op_checker) {
66 67 68
    AddInput("X", "The first input of mul op");
    AddInput("Y", "The second input of mul op");
    AddOutput("Out", "The output of mul op");
F
WIP  
fengjiayi 已提交
69
    AddAttr<int>(
F
fengjiayi 已提交
70
        "x_num_col_dims",
F
fengjiayi 已提交
71 72 73 74 75 76
        R"DOC(mul_op can take tensors with more than two dimensions as input `X`, 
            in that case, tensors will be reshaped to a matrix. The matrix's first 
            dimension(column length) will be the product of tensor's last 
            `num_col_dims` dimensions, and the matrix's second dimension(row length)
            will be the product of tensor's first `rank - num_col_dims` dimensions.
        )DOC")
F
WIP  
fengjiayi 已提交
77
        .SetDefault(1)
F
fengjiayi 已提交
78
        .EqualGreaterThan(1);
F
WIP  
fengjiayi 已提交
79
    AddAttr<int>(
F
fengjiayi 已提交
80
        "y_num_col_dims",
F
fengjiayi 已提交
81 82 83
        R"DOC(mul_op can take tensors with more than two dimensions as input `Y`,
             in that case, tensors will be reshaped to a matrix. Just like input `X`.
        )DOC")
F
WIP  
fengjiayi 已提交
84
        .SetDefault(1)
F
fengjiayi 已提交
85
        .EqualGreaterThan(1);
86
    AddComment(R"DOC(
87
Mul operator is used to perform matrix multiplication for input X and Y.
88

89 90 91 92 93 94
The equation is:

    Out = X * Y

Both the input `X` and `Y` can carry the LoD (Level of Details) information,
or not. But the output only shares the LoD with input `X`.
95 96 97 98
)DOC");
  }
};

D
dongzhihong 已提交
99
class MulOpGrad : public framework::OperatorWithKernel {
Y
Yu Yang 已提交
100 101 102
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

103
 protected:
D
dongzhihong 已提交
104 105 106 107 108
  void InferShape(const framework::InferShapeContext &ctx) const override {
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("X"), "Input(X) should not be null");
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("Y"), "Input(Y) should not be null");
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar(framework::GradVarName("Out")),
                            "Input(Out@GRAD) should not be null");
D
dongzhihong 已提交
109 110 111
    auto x_dims = ctx.Input<Tensor>("X")->dims();
    auto y_dims = ctx.Input<Tensor>("Y")->dims();
    auto out_dims = ctx.Input<Tensor>(framework::GradVarName("Out"))->dims();
112 113 114 115
    auto *x_grad =
        ctx.Output<framework::LoDTensor>(framework::GradVarName("X"));
    auto *y_grad =
        ctx.Output<framework::LoDTensor>(framework::GradVarName("Y"));
116 117

    auto x_mat_dims =
F
fengjiayi 已提交
118
        framework::flatten_to_2d(x_dims, Attr<int>("x_num_col_dims"));
119
    auto y_mat_dims =
F
fengjiayi 已提交
120
        framework::flatten_to_2d(y_dims, Attr<int>("y_num_col_dims"));
121 122 123

    PADDLE_ENFORCE_EQ(
        x_mat_dims[0], out_dims[0],
F
WIP  
fengjiayi 已提交
124 125
        "The first dimension of Out@GRAD must equal to the first dimension of "
        "the first operand.");
126 127
    PADDLE_ENFORCE_EQ(
        y_mat_dims[1], out_dims[1],
128 129
        "The second dimension of Out@GRAD must equal to the second "
        "dimension of the second operand.");
D
dongzhihong 已提交
130

131 132
    if (x_grad) x_grad->Resize(x_dims);
    if (y_grad) y_grad->Resize(y_dims);
D
dongzhihong 已提交
133 134 135
  }
};

136 137 138
}  // namespace operators
}  // namespace paddle

D
dongzhihong 已提交
139
namespace ops = paddle::operators;
140
REGISTER_OP(mul, ops::MulOp, ops::MulOpMaker, mul_grad, ops::MulOpGrad);
D
dongzhihong 已提交
141
REGISTER_OP_CPU_KERNEL(mul, ops::MulKernel<paddle::platform::CPUPlace, float>);
D
dongzhihong 已提交
142 143
REGISTER_OP_CPU_KERNEL(mul_grad,
                       ops::MulGradKernel<paddle::platform::CPUPlace, float>);