mul_op.cc 7.2 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

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/mul_op.h"
16
#include <string>
17
#include <vector>
18 19 20 21

namespace paddle {
namespace operators {

22
using framework::OpKernelType;
D
dongzhihong 已提交
23 24
using framework::Tensor;

25
class MulOp : public framework::OperatorWithKernel {
Y
Yu Yang 已提交
26
 public:
27 28 29
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
Q
Qiao Longfei 已提交
30 31 32 33 34 35 36
    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 已提交
37

Q
Qiao Longfei 已提交
38 39
    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 已提交
40

Y
Yu Yang 已提交
41 42 43 44
    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;

45 46 47 48 49 50 51 52
    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.");
53

F
fengjiayi 已提交
54 55
    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);
56

Y
Yan Chunwei 已提交
57
    PADDLE_ENFORCE_EQ(
58
        x_mat_dims[1], y_mat_dims[0],
59
        "First matrix's width must be equal with second matrix's height.");
Y
Yu Yang 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72
    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 已提交
73
    ctx->ShareLoD("X", /*->*/ "Out");
74 75 76
  }
};

D
dongzhihong 已提交
77
class MulOpMaker : public framework::OpProtoAndCheckerMaker {
78
 public:
Y
Yu Yang 已提交
79
  void Make() override {
C
caoying03 已提交
80 81 82
    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 已提交
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
    AddComment(R"DOC(
C
caoying03 已提交
114
Mul Operator.
K
kexinzhao 已提交
115

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

118 119
The equation is:

C
caoying03 已提交
120
$$Out = X * Y$$
121

C
caoying03 已提交
122 123
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 已提交
124

125 126 127 128
)DOC");
  }
};

129
class MulGradOp : public framework::OperatorWithKernel {
Y
Yu Yang 已提交
130 131 132
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

133
  void InferShape(framework::InferShapeContext* ctx) const override {
Q
Qiao Longfei 已提交
134 135 136 137 138 139 140
    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"));
141

Q
Qiao Longfei 已提交
142 143 144 145
    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"));
146

Q
Qiao Longfei 已提交
147 148 149 150 151 152 153 154 155
    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 已提交
156 157 158
  }
};

S
sneaxiy 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
class MulOpGradMaker : public framework::SingleGradOpDescMaker {
 public:
  using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;

 protected:
  std::unique_ptr<framework::OpDesc> Apply() const override {
    std::unique_ptr<framework::OpDesc> retv(new framework::OpDesc());
    retv->SetType("mul_grad");
    retv->SetInput("X", Input("X"));
    retv->SetInput("Y", Input("Y"));
    retv->SetInput(framework::GradVarName("Out"), OutputGrad("Out"));
    retv->SetOutput(framework::GradVarName("X"), InputGrad("X"));
    retv->SetOutput(framework::GradVarName("Y"), InputGrad("Y"));
    retv->SetAttrMap(Attrs());
    return retv;
  }
};

177 178 179
}  // namespace operators
}  // namespace paddle

D
dongzhihong 已提交
180
namespace ops = paddle::operators;
S
sneaxiy 已提交
181
REGISTER_OPERATOR(mul, ops::MulOp, ops::MulOpMaker, ops::MulOpGradMaker);
182
REGISTER_OPERATOR(mul_grad, ops::MulGradOp);
Q
QI JUN 已提交
183
REGISTER_OP_CPU_KERNEL(
D
dzhwinter 已提交
184 185
    mul, ops::MulKernel<paddle::platform::CPUDeviceContext, float>,
    ops::MulKernel<paddle::platform::CPUDeviceContext, double>);
Q
QI JUN 已提交
186
REGISTER_OP_CPU_KERNEL(
D
dzhwinter 已提交
187 188
    mul_grad, ops::MulGradKernel<paddle::platform::CPUDeviceContext, float>,
    ops::MulGradKernel<paddle::platform::CPUDeviceContext, double>);