kron_op.cc 5.9 KB
Newer Older
F
Feiyu Chan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

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 <memory>
#include <string>
#include <unordered_map>
#include <vector>

20
#include "paddle/fluid/framework/infershape_utils.h"
21
#include "paddle/fluid/framework/op_registry.h"
22
#include "paddle/phi/infermeta/binary.h"
F
Feiyu Chan 已提交
23 24 25 26 27 28 29 30 31 32 33

namespace paddle {
namespace operators {

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

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
34 35 36 37 38 39
    auto data_type =
        OperatorWithKernel::IndicateOrPromoteVarDataTypes(ctx, "X", "Y");
    return framework::OpKernelType(data_type, ctx.GetPlace());
  }

  framework::OpKernelType GetKernelTypeForVar(
40 41
      const std::string& var_name,
      const framework::Tensor& tensor,
42
      const framework::OpKernelType& expected_kernel_type) const override {
43 44
    if (framework::IsComplexType(expected_kernel_type.data_type_)) {
      // only promote inputs’s types when contains complex input
45
      return framework::OpKernelType(
46 47
          framework::TransToProtoVarType(tensor.dtype()),
          tensor.place(),
48
          tensor.layout());
49
    } else {
50 51
      return framework::OpKernelType(
          expected_kernel_type.data_type_, tensor.place(), tensor.layout());
52
    }
F
Feiyu Chan 已提交
53 54 55 56 57 58 59 60 61 62 63 64 65
  }
};

class KronOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X", "(Tensor), the first operand of kron op");
    AddInput("Y", "(Tensor), the second operand of kron op");
    AddOutput("Out", "(Tensor), the output of kron op.");
    AddComment(R"DOC(
          Kron Operator.

          This operator computes the Kronecker product of two tensors, a
66
          composite tensor made of blocks of the second tensor scaled by the
F
Feiyu Chan 已提交
67 68 69
          first.

          This operator assumes that the rank of the two tensors, $X$ and $Y$
70 71 72 73
          are the same, if necessary prepending the smallest with ones. If the
          shape of $X$ is [$r_0$, $r_1$, ..., $r_N$] and the shape of $Y$ is
          [$s_0$, $s_1$, ..., $s_N$], then the shape of the output tensor is
          [$r_{0}s_{0}$, $r_{1}s_{1}$, ..., $r_{N}s_{N}$]. The elements are
F
Feiyu Chan 已提交
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
          products of elements from $X$ and $Y$.

          The equation is:
          $$
          output[k_{0}, k_{1}, ..., k_{N}] = X[i_{0}, i_{1}, ..., i_{N}] *
          Y[j_{0}, j_{1}, ..., j_{N}]
          $$

          where
          $$
          k_{t} = i_{t} * s_{t} + j_{t}, t = 0, 1, ..., N
          $$
        )DOC");
  }
};

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

  void InferShape(framework::InferShapeContext* ctx) const override {
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "kron_grad");
    OP_INOUT_CHECK(ctx->HasInput("Y"), "Input", "Y", "kron_grad");
97 98 99 100
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")),
                   "Input",
                   framework::GradVarName("Out"),
                   "kron_grad");
F
Feiyu Chan 已提交
101 102 103

    auto x_grad_name = framework::GradVarName("X");
    auto y_grad_name = framework::GradVarName("Y");
104 105 106 107 108 109
    if (ctx->HasOutput(x_grad_name)) {
      ctx->SetOutputDim(x_grad_name, ctx->GetInputDim("X"));
    }
    if (ctx->HasOutput(y_grad_name)) {
      ctx->SetOutputDim(y_grad_name, ctx->GetInputDim("Y"));
    }
F
Feiyu Chan 已提交
110 111 112 113 114 115 116 117 118 119
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    auto out_grad_name = framework::GradVarName("Out");
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, out_grad_name),
        ctx.GetPlace());
  }
C
chentianyu03 已提交
120 121

  framework::OpKernelType GetKernelTypeForVar(
122 123
      const std::string& var_name,
      const framework::Tensor& tensor,
124
      const framework::OpKernelType& expected_kernel_type) const override {
C
chentianyu03 已提交
125 126
    if (framework::IsComplexType(expected_kernel_type.data_type_)) {
      // only promote inputs’s types when contains complex input
127
      return framework::OpKernelType(
128 129
          framework::TransToProtoVarType(tensor.dtype()),
          tensor.place(),
130
          tensor.layout());
C
chentianyu03 已提交
131
    } else {
132 133
      return framework::OpKernelType(
          expected_kernel_type.data_type_, tensor.place(), tensor.layout());
C
chentianyu03 已提交
134 135
    }
  }
F
Feiyu Chan 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
};

template <typename T>
class KronGradOpMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
  void Apply(GradOpPtr<T> grad_op) const override {
    grad_op->SetType("kron_grad");

    grad_op->SetInput("X", this->Input("X"));
    grad_op->SetInput("Y", this->Input("Y"));
    grad_op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));

    grad_op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    grad_op->SetOutput(framework::GradVarName("Y"), this->InputGrad("Y"));

    grad_op->SetAttrMap(this->Attrs());
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

163 164
DECLARE_INFER_SHAPE_FUNCTOR(kron,
                            KronInferShapeFunctor,
165
                            PD_INFER_META(phi::KronInferMeta));
166 167 168
REGISTER_OPERATOR(kron,
                  ops::KronOp,
                  ops::KronOpMaker,
F
Feiyu Chan 已提交
169
                  ops::KronGradOpMaker<paddle::framework::OpDesc>,
170 171
                  ops::KronGradOpMaker<paddle::imperative::OpBase>,
                  KronInferShapeFunctor);
F
Feiyu Chan 已提交
172
REGISTER_OPERATOR(kron_grad, ops::KronGradOp);