matmul_op.cc 7.8 KB
Newer Older
M
Markus Kliegl 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
/* Copyright (c) 2017 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. */

#include "paddle/operators/matmul_op.h"

namespace paddle {
namespace operators {

using framework::Tensor;

class MatMulOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
  void InferShape(framework::InferShapeContext* context) const override {
    PADDLE_ENFORCE(context->HasInput("X"),
                   "Input(X) of MatMulOp should not be null.");
    PADDLE_ENFORCE(context->HasInput("Y"),
                   "Input(Y) of MatMulOp should not be null.");
    PADDLE_ENFORCE(context->HasOutput("Out"),
                   "Output(Out) of MatMulOp should not be null.");

    auto dim_x = context->GetInputDim("X");
    auto dim_y = context->GetInputDim("Y");
    bool transpose_x = context->Attrs().Get<bool>("transpose_X");
    bool transpose_y = context->Attrs().Get<bool>("transpose_Y");

    PADDLE_ENFORCE_GE(dim_x.size(), 1,
                      "Input tensor X must be at least 1-dimensional.");
    PADDLE_ENFORCE_GE(dim_y.size(), 1,
                      "Input tensor Y must be at least 1-dimensional.");
C
chengduoZH 已提交
44 45 46 47 48 49

    std::vector<int64_t> out_dim;
    int64_t batch_count = 1;
    if (dim_x.size() > 3) {
      PADDLE_ENFORCE(dim_y.size() == dim_x.size(),
                     "The dimensions of X and Y must be the same, and both of "
C
chengduoZH 已提交
50 51
                     "them should be %d-dimensional.",
                     dim_x.size());
C
chengduoZH 已提交
52
      for (int j = 0; j < dim_x.size() - 2; ++j) {
C
chengduoZH 已提交
53 54 55
        PADDLE_ENFORCE(dim_y[j] == dim_x[j],
                       "The dimensions of X[%d] and Y[%d] must be the same.", j,
                       j);
C
chengduoZH 已提交
56 57 58 59
        out_dim.push_back(dim_x[j]);
        batch_count *= dim_x[j];
      }
    }
M
Markus Kliegl 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84

    int M = 0, N = 0, KX = 0, KY = 0, batchCountX = 0, batchCountY = 0;
    bool remove_initial_dim = false, remove_final_dim = false;

    switch (dim_x.size()) {
      case 1:
        if (transpose_x) {
          M = dim_x[0];
          KX = 1;
        } else {
          M = 1;
          KX = dim_x[0];
          remove_initial_dim = true;
        }
        break;
      case 2:
        M = transpose_x ? dim_x[1] : dim_x[0];
        KX = transpose_x ? dim_x[0] : dim_x[1];
        break;
      case 3:
        batchCountX = dim_x[0];
        M = transpose_x ? dim_x[2] : dim_x[1];
        KX = transpose_x ? dim_x[1] : dim_x[2];
        break;
      default:
C
chengduoZH 已提交
85 86 87 88 89
        batchCountX = batch_count;
        size_t mat_s = dim_x.size() - 2;
        M = transpose_x ? dim_x[mat_s + 1] : dim_x[mat_s];
        KX = transpose_x ? dim_x[mat_s] : dim_x[mat_s + 1];
        break;
M
Markus Kliegl 已提交
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
    }

    switch (dim_y.size()) {
      case 1:
        if (transpose_y) {
          N = dim_y[0];
          KY = 1;
        } else {
          N = 1;
          KY = dim_y[0];
          remove_final_dim = true;
        }
        break;
      case 2:
        KY = transpose_y ? dim_y[1] : dim_y[0];
        N = transpose_y ? dim_y[0] : dim_y[1];
        break;
      case 3:
        batchCountY = dim_y[0];
        KY = transpose_y ? dim_y[2] : dim_y[1];
        N = transpose_y ? dim_y[1] : dim_y[2];
        break;
      default:
C
chengduoZH 已提交
113 114 115 116
        batchCountY = batch_count;
        size_t mat_s = dim_y.size() - 2;
        KY = transpose_y ? dim_y[mat_s + 1] : dim_y[mat_s];
        N = transpose_y ? dim_y[mat_s] : dim_y[mat_s + 1];
M
Markus Kliegl 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    }

    PADDLE_ENFORCE_EQ(
        KX, KY,
        "First matrix's width must be equal with second matrix's height.");
    if (batchCountX && batchCountY) {
      PADDLE_ENFORCE_EQ(
          batchCountX, batchCountY,
          "When Input(X) and Input(Y) are both three dimensional, they "
          "must have the same batch dimension.");
    }
    int batchCount = std::max(batchCountX, batchCountY);

    std::vector<int64_t> dim_out;
    if (batchCount) {
C
chengduoZH 已提交
132 133 134 135 136
      if (dim_x.size() > 3) {
        dim_out.insert(dim_out.begin(), out_dim.begin(), out_dim.end());
      } else {
        dim_out.push_back(batchCount);
      }
M
Markus Kliegl 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
    }
    if (!remove_initial_dim) {
      dim_out.push_back(M);
    }
    if (!remove_final_dim) {
      dim_out.push_back(N);
    }
    if (dim_out.size() == 0) {
      // We don't support 0-dimensional Tensors (scalars), so instead
      // treat the output as a Tensor of shape (1, ) in this case.
      dim_out.push_back(1);
    }
    context->SetOutputDim("Out", framework::make_ddim(dim_out));
    context->ShareLoD("X", /*->*/ "Out");
  }
};

class MatMulOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
156
  MatMulOpMaker(OpProto* proto, OpAttrChecker* op_checker)
M
Markus Kliegl 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput("X", "The first input of MatMul op");
    AddInput("Y", "The second input of MatMul op");
    AddOutput("Out", "The output of MatMul op");
    AddAttr<bool>("transpose_X",
                  R"DOC(If true, use the transpose of `X`.
        )DOC")
        .SetDefault(false);
    AddAttr<bool>("transpose_Y",
                  R"DOC(If true, use the transpose of `Y`.
        )DOC")
        .SetDefault(false);
    AddComment(R"DOC(
K
kexinzhao 已提交
170 171 172 173
MatMul Operator.


This operator is used to perform (batched) matrix multiplication
M
Markus Kliegl 已提交
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
over the last two dimensions of the input tensors `X` and `Y`.

If a transpose flag is specified, the last two dimensions of the
tensor are transposed. If the tensor is rank-1 of shape [D], then
for `X` it is treated as [1, D] in nontransposed form and as [D, 1]
in transposed form, whereas for `Y` it is the opposite: It is treated
as [D, 1] in nontransposed form and as [1, D] in transposed form.

Examples without transpose:
- X: [K], Y: [K] => Out: [1]
- X: [K], Y: [K, N] => Out: [N]
- X: [B, M, K], Y: [K] => Out: [B, M]
- X: [M, K], Y: [B, K, N] => Out: [B, M, N]
- X: [B, M, K], Y: [B, K, N] => Out: [B, M, N]

The behavior is designed to be similar to the `numpy.matmul` function.
The differences are:
- Currently only rank 1 to rank 3 input tensors are supported.
- We add `transpose_X` and `transpose_Y` flags.

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

M
Markus Kliegl 已提交
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
)DOC");
  }
};

class MatMulOpGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
  void InferShape(framework::InferShapeContext* context) const override {
    PADDLE_ENFORCE(context->HasInput("X"), "Input(X) should not be null");
    PADDLE_ENFORCE(context->HasInput("Y"), "Input(Y) should not be null");
    PADDLE_ENFORCE(context->HasInput(framework::GradVarName("Out")),
                   "Input(Out@GRAD) should not be null");
    auto x_dims = context->GetInputDim("X");
    auto y_dims = context->GetInputDim("Y");

    auto x_grad_name = framework::GradVarName("X");
    auto y_grad_name = framework::GradVarName("Y");

    if (context->HasOutput(x_grad_name)) {
      context->SetOutputDim(x_grad_name, x_dims);
    }
    if (context->HasOutput(y_grad_name)) {
      context->SetOutputDim(y_grad_name, y_dims);
    }
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OP(matmul, ops::MatMulOp, ops::MatMulOpMaker, matmul_grad,
            ops::MatMulOpGrad);
REGISTER_OP_CPU_KERNEL(
Q
QI JUN 已提交
233 234 235 236
    matmul, ops::MatMulKernel<paddle::platform::CPUDeviceContext, float>);
REGISTER_OP_CPU_KERNEL(
    matmul_grad,
    ops::MatMulGradKernel<paddle::platform::CPUDeviceContext, float>);