multiplex_op.cc 6.5 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

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/multiplex_op.h"
S
sneaxiy 已提交
16
#include <memory>
S
sneaxiy 已提交
17
#include <vector>
Y
Yibing Liu 已提交
18 19 20 21 22 23 24 25

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;

class MultiplexOp : public framework::OperatorWithKernel {
 public:
26
  using framework::OperatorWithKernel::OperatorWithKernel;
Y
Yibing Liu 已提交
27

28
  void InferShape(framework::InferShapeContext* ctx) const override {
Q
Qiao Longfei 已提交
29 30
    PADDLE_ENFORCE(ctx->HasInput("Ids"), "Input(Ids) shouldn't be null.");
    PADDLE_ENFORCE(!ctx->Inputs("X").empty(),
31
                   "MultiInput(X) shouldn't be empty.");
Q
Qiao Longfei 已提交
32 33
    PADDLE_ENFORCE(ctx->HasOutput("Out"), "Output(Out) shouldn't be null.");
    auto ids_dim = ctx->GetInputDim("Ids");
34 35 36 37
    PADDLE_ENFORCE(
        ids_dim.size() == 2 && ids_dim[1] == 1,
        "The index tensor must be a vector with size batchSize x 1.");

Q
Qiao Longfei 已提交
38 39
    auto ins_dims = ctx->GetInputsDim("X");
    auto num_ins = ins_dims.size();
40 41 42
    PADDLE_ENFORCE(num_ins > 1,
                   "multiplex operator should have more than "
                   "one candidate input tensors.");
Y
Yibing Liu 已提交
43

Q
Qiao Longfei 已提交
44
    auto in_dim = ins_dims[0];
45 46
    PADDLE_ENFORCE(in_dim.size() >= 2,
                   "The rank of candidate tensors must be not less than 2.");
47
    for (size_t i = 1; i < num_ins; i++) {
Q
Qiao Longfei 已提交
48
      auto dim = ins_dims[i];
Y
Yibing Liu 已提交
49
      PADDLE_ENFORCE(in_dim == dim,
50
                     "All the candidate tensors must have the same size.");
Y
Yibing Liu 已提交
51
    }
Q
Qiao Longfei 已提交
52
    ctx->SetOutputDim("Out", in_dim);
Y
Yibing Liu 已提交
53
  }
Y
Yu Yang 已提交
54

55
 protected:
56
  framework::OpKernelType GetExpectedKernelType(
Y
Yu Yang 已提交
57
      const framework::ExecutionContext& ctx) const override {
Y
Yu Yang 已提交
58 59
    return framework::OpKernelType(ctx.MultiInput<Tensor>("X")[0]->type(),
                                   ctx.device_context());
Y
Yu Yang 已提交
60
  }
Y
Yibing Liu 已提交
61 62 63 64
};

class MultiplexOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
65
  void Make() override {
Y
yuyang18 已提交
66 67 68 69 70 71
    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.")
72
        .AsDuplicable();
Y
Yibing Liu 已提交
73
    AddOutput("Out", "The output tensor of multiplex operator.");
K
kexinzhao 已提交
74
    AddComment(R"DOC(
Y
yuyang18 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
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
96
the (Ids[i])-th tensor.
Y
Yibing Liu 已提交
97

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

Y
yuyang18 已提交
100 101 102
$$
y[i] = x_{k}[i]
$$
Y
Yibing Liu 已提交
103

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

Y
Yibing Liu 已提交
107 108 109 110 111 112
)DOC");
  }
};

class MultiplexGradOp : public framework::OperatorWithKernel {
 public:
113
  using framework::OperatorWithKernel::OperatorWithKernel;
Y
Yibing Liu 已提交
114

115
  void InferShape(framework::InferShapeContext* ctx) const override {
S
sneaxiy 已提交
116 117
    auto& dxs = ctx->Outputs(framework::GradVarName("X"));
    PADDLE_ENFORCE(!dxs.empty(), "Output(X@Grad) should not be null.");
Q
Qiao Longfei 已提交
118 119
    PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
                   "Input(Out@GRAD) should not be null.");
S
sneaxiy 已提交
120 121 122
    auto dout_dim = ctx->GetInputDim(framework::GradVarName("Out"));
    ctx->SetOutputsDim(framework::GradVarName("X"),
                       std::vector<framework::DDim>(dxs.size(), dout_dim));
Y
Yibing Liu 已提交
123
  }
Y
Yu Yang 已提交
124

125
 protected:
126
  framework::OpKernelType GetExpectedKernelType(
Y
Yu Yang 已提交
127
      const framework::ExecutionContext& ctx) const override {
S
sneaxiy 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
    return framework::OpKernelType(
        ctx.Input<Tensor>(framework::GradVarName("Out"))->type(),
        ctx.device_context());
  }
};

class MultiplexGradDescMaker : public framework::SingleGradOpDescMaker {
 public:
  using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;

 protected:
  std::unique_ptr<framework::OpDesc> Apply() const override {
    std::unique_ptr<framework::OpDesc> op(new framework::OpDesc());
    op->SetType("multiplex_grad");
    op->SetInput("Ids", Input("Ids"));
    op->SetInput(framework::GradVarName("Out"), OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), InputGrad("X", false));
    op->SetAttrMap(Attrs());
    return op;
Y
Yu Yang 已提交
147
  }
Y
Yibing Liu 已提交
148 149 150 151
};

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

Y
Yibing Liu 已提交
153 154
namespace ops = paddle::operators;

155
REGISTER_OPERATOR(multiplex, ops::MultiplexOp, ops::MultiplexOpMaker,
S
sneaxiy 已提交
156
                  ops::MultiplexGradDescMaker);
157
REGISTER_OPERATOR(multiplex_grad, ops::MultiplexGradOp);
Y
Yibing Liu 已提交
158
REGISTER_OP_CPU_KERNEL(
Q
QI JUN 已提交
159
    multiplex,
160 161 162 163
    ops::MultiplexCPUKernel<paddle::platform::CPUDeviceContext, float>,
    ops::MultiplexCPUKernel<paddle::platform::CPUDeviceContext, double>,
    ops::MultiplexCPUKernel<paddle::platform::CPUDeviceContext, int>,
    ops::MultiplexCPUKernel<paddle::platform::CPUDeviceContext, int64_t>);
164 165
REGISTER_OP_CPU_KERNEL(
    multiplex_grad,
166 167 168 169
    ops::MultiplexGradCPUKernel<paddle::platform::CPUDeviceContext, float>,
    ops::MultiplexGradCPUKernel<paddle::platform::CPUDeviceContext, double>,
    ops::MultiplexGradCPUKernel<paddle::platform::CPUDeviceContext, int>,
    ops::MultiplexGradCPUKernel<paddle::platform::CPUDeviceContext, int64_t>);