matmul_op.cc 8.3 KB
Newer Older
1
/* Copyright (c) 2017 PaddlePaddle Authors. All Rights Reserved.
M
Markus Kliegl 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

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

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/matmul_op.h"
16 17
#include <algorithm>
#include <vector>
M
Markus Kliegl 已提交
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 44 45

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 已提交
46 47 48 49

    std::vector<int64_t> out_dim;
    int64_t batch_count = 1;
    if (dim_x.size() > 3) {
C
chengduoZH 已提交
50 51 52 53 54
      PADDLE_ENFORCE_EQ(
          dim_y.size(), dim_x.size(),
          "The dimensions of X and Y must be the same, and both of "
          "them should be %d-dimensional.",
          dim_x.size());
C
chengduoZH 已提交
55

C
chengduoZH 已提交
56
      // The first rank-2 dimensions are accumulated on the batch_count, and the
C
chengduoZH 已提交
57
      // last two dimensions are used for matrix multiplication.
C
chengduoZH 已提交
58
      for (int j = 0; j < dim_x.size() - 2; ++j) {
C
chengduoZH 已提交
59 60 61
        PADDLE_ENFORCE_EQ(dim_y[j], dim_x[j],
                          "The %d-th dimension of X and Y must be the same.",
                          j);
C
chengduoZH 已提交
62 63 64 65
        out_dim.push_back(dim_x[j]);
        batch_count *= dim_x[j];
      }
    }
M
Markus Kliegl 已提交
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

    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 已提交
91 92 93 94 95
        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 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
    }

    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 已提交
119 120 121 122
        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 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
    }

    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 已提交
138 139 140 141 142
      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 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
    }
    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:
162
  MatMulOpMaker(OpProto* proto, OpAttrChecker* op_checker)
M
Markus Kliegl 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175
      : 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 已提交
176 177 178 179
MatMul Operator.


This operator is used to perform (batched) matrix multiplication
M
Markus Kliegl 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193
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]
C
chengduoZH 已提交
194
- X: [B, ..., M, K], Y: [B, ..., K, N] => Out: [B, ..., M, N]
M
Markus Kliegl 已提交
195 196 197

The behavior is designed to be similar to the `numpy.matmul` function.
The differences are:
C
chengduoZH 已提交
198 199
- When the rank of the input data is less than or equal to 3, it
  is similar to the `numpy.matmul` function.
C
chengduoZH 已提交
200
- When the rank of the input is greater than 3, the rank of X and
C
chengduoZH 已提交
201
  Y must be equal, and the first `rank - 2` dimensions must be equal.
M
Markus Kliegl 已提交
202 203 204
- We add `transpose_X` and `transpose_Y` flags.

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

M
Markus Kliegl 已提交
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 233 234 235 236 237 238 239
)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;
Y
Yang Yang 已提交
240
REGISTER_OPERATOR(matmul, ops::MatMulOp, ops::MatMulOpMaker,
241 242
                  paddle::framework::DefaultGradOpDescMaker<true>);
REGISTER_OPERATOR(matmul_grad, ops::MatMulOpGrad);
M
Markus Kliegl 已提交
243
REGISTER_OP_CPU_KERNEL(
Q
QI JUN 已提交
244 245 246 247
    matmul, ops::MatMulKernel<paddle::platform::CPUDeviceContext, float>);
REGISTER_OP_CPU_KERNEL(
    matmul_grad,
    ops::MatMulGradKernel<paddle::platform::CPUDeviceContext, float>);