multiplex_op.cc 5.3 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Y
Yibing Liu 已提交
2

L
Luo Tao 已提交
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
Y
Yibing Liu 已提交
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
Y
Yibing Liu 已提交
8

L
Luo Tao 已提交
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. */
Y
Yibing Liu 已提交
14

S
sneaxiy 已提交
15
#include <memory>
S
sneaxiy 已提交
16
#include <vector>
17 18

#include "paddle/fluid/framework/infershape_utils.h"
19
#include "paddle/fluid/framework/op_registry.h"
20 21 22
#include "paddle/phi/core/infermeta_utils.h"
#include "paddle/phi/infermeta/multiary.h"

Y
Yibing Liu 已提交
23 24 25 26 27
namespace paddle {
namespace operators {

class MultiplexOp : public framework::OperatorWithKernel {
 public:
28
  using framework::OperatorWithKernel::OperatorWithKernel;
Y
Yibing Liu 已提交
29

30
 protected:
31
  framework::OpKernelType GetExpectedKernelType(
Y
Yu Yang 已提交
32
      const framework::ExecutionContext& ctx) const override {
33 34 35
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        ctx.device_context());
Y
Yu Yang 已提交
36
  }
Y
Yibing Liu 已提交
37 38 39 40
};

class MultiplexOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
41
  void Make() override {
Y
yuyang18 已提交
42 43 44 45 46 47
    AddInput("Ids",
             "Tensor<int32>, index variable which is a 2-D tensor with shape "
             "[M, 1] where M is the batch size.");
    AddInput("X",
             "A list of variables to gather from. All variables have the same "
             "shape and the rank is at least 2.")
48
        .AsDuplicable();
Y
Yibing Liu 已提交
49
    AddOutput("Out", "The output tensor of multiplex operator.");
K
kexinzhao 已提交
50
    AddComment(R"DOC(
Y
yuyang18 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
Referring to the given index variable, this layer selects rows from the
input variables to construct a multiplex variable. Assuming that there are
:math:`m` input variables and :math:`I_i` represents the i-th input
variable and :math:`i` is in [0, :math:`m`). All input variables are
tensors with same shape [:math:`d_0`, :math:`d_1`, ..., :math:`d_R`].
Please note that rank of the input tensor should be at least 2. Each input
variable will be treated as a 2-D matrix with shape [:math:`M`, :math:`N`]
where :math:`M` for :math:`d_0` and :math:`N` for :math:`d_1` * :math:`d_2`
* ... * :math:`d_R`. Let :math:`I_i[j]` be the j-th row of the i-th input
variable. The given index variable should be a 2-D tensor with shape
[:math:`M`, 1]. Let `ID[i]` be the i-th index value of the index variable.
Then the output variable will be a tensor with shape [:math:`d_0`,
:math:`d_1`, ..., :math:`d_R`]. If we treat the output tensor as a 2-D
matrix with shape [:math:`M`, :math:`N`] and let :math:`O[i]` be the i-th
row of the matrix, then `O[i]` is equal to :math:`I_{ID[i]}[i]`.

* Ids: the index tensor.

* X[0 : N - 1]: the candidate tensors for output (N >= 2).

* For each index i from 0 to batchSize - 1, the output is the i-th row of the
72
the (Ids[i])-th tensor.
Y
Yibing Liu 已提交
73

74
For i-th row of the output tensor:
Y
Yibing Liu 已提交
75

Y
yuyang18 已提交
76 77 78
$$
y[i] = x_{k}[i]
$$
Y
Yibing Liu 已提交
79

Y
yuyang18 已提交
80 81
where $y$ is the output tensor, $x_{k}$ is the k-th input tensor,
and $k = Ids[i]$.
K
kexinzhao 已提交
82

Y
Yibing Liu 已提交
83 84 85 86 87 88
)DOC");
  }
};

class MultiplexGradOp : public framework::OperatorWithKernel {
 public:
89
  using framework::OperatorWithKernel::OperatorWithKernel;
Y
Yibing Liu 已提交
90

91
  void InferShape(framework::InferShapeContext* ctx) const override {
H
hong 已提交
92
    auto dxs = ctx->Outputs(framework::GradVarName("X"));
93 94
    PADDLE_ENFORCE_NE(dxs.empty(),
                      true,
95 96
                      platform::errors::InvalidArgument(
                          "Output(X@Grad) should not be null."));
97 98 99 100
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")),
                   "Input",
                   framework::GradVarName("Out"),
                   "MultiplexGrad");
S
sneaxiy 已提交
101 102 103
    auto dout_dim = ctx->GetInputDim(framework::GradVarName("Out"));
    ctx->SetOutputsDim(framework::GradVarName("X"),
                       std::vector<framework::DDim>(dxs.size(), dout_dim));
Y
Yibing Liu 已提交
104
  }
Y
Yu Yang 已提交
105

106
 protected:
107
  framework::OpKernelType GetExpectedKernelType(
Y
Yu Yang 已提交
108
      const framework::ExecutionContext& ctx) const override {
109 110 111
    return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
                                       ctx, framework::GradVarName("Out")),
                                   ctx.device_context());
S
sneaxiy 已提交
112 113 114
  }
};

H
hong 已提交
115 116
template <typename T>
class MultiplexGradMaker : public framework::SingleGradOpMaker<T> {
S
sneaxiy 已提交
117
 public:
H
hong 已提交
118
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
S
sneaxiy 已提交
119 120

 protected:
121
  void Apply(GradOpPtr<T> op) const override {
S
sneaxiy 已提交
122
    op->SetType("multiplex_grad");
H
hong 已提交
123 124 125 126
    op->SetInput("Ids", this->Input("Ids"));
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X", false));
    op->SetAttrMap(this->Attrs());
Y
Yu Yang 已提交
127
  }
Y
Yibing Liu 已提交
128 129 130 131
};

}  // namespace operators
}  // namespace paddle
S
sneaxiy 已提交
132

Y
Yibing Liu 已提交
133
namespace ops = paddle::operators;
134 135
DECLARE_INFER_SHAPE_FUNCTOR(multiplex,
                            MultiplexInferShapeFunctor,
136
                            PD_INFER_META(phi::MultiplexInferMeta));
Y
Yibing Liu 已提交
137

138 139 140
REGISTER_OPERATOR(multiplex,
                  ops::MultiplexOp,
                  ops::MultiplexOpMaker,
H
hong 已提交
141
                  ops::MultiplexGradMaker<paddle::framework::OpDesc>,
142 143
                  ops::MultiplexGradMaker<paddle::imperative::OpBase>,
                  MultiplexInferShapeFunctor);
144
REGISTER_OPERATOR(multiplex_grad, ops::MultiplexGradOp);