sequence_expand_op.cc 7.4 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
W
wanghaoshuang 已提交
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
W
wanghaoshuang 已提交
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
W
wanghaoshuang 已提交
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. */
W
wanghaoshuang 已提交
14

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/sequence_expand_op.h"
W
wanghaoshuang 已提交
16 17 18 19

namespace paddle {
namespace operators {

Y
yangyaming 已提交
20
using framework::LoDTensor;
W
wanghaoshuang 已提交
21

W
wanghaoshuang 已提交
22
class SequenceExpandOp : public framework::OperatorWithKernel {
W
wanghaoshuang 已提交
23 24 25 26 27
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
  void InferShape(framework::InferShapeContext* ctx) const override {
Y
yangyaming 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 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 85 86 87 88
    PADDLE_ENFORCE(ctx->HasInput("X"),
                   "Input(X) of SequenceExpandOp should not be null.");
    PADDLE_ENFORCE(ctx->HasInput("Y"),
                   "Input(Y) of SequenceExpandOp should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput("Out"),
                   "Output(Out) of SequenceExpandOp should not be null.");

    auto x_dims = ctx->GetInputDim("X");
    PADDLE_ENFORCE_EQ(x_dims.size(), 2U,
                      "Dimension number of Input(X) should be 2.");
    int ref_level = ctx->Attrs().Get<int>("ref_level");

    if (ctx->IsRuntime()) {
      framework::Variable* x_var =
          boost::get<framework::Variable*>(ctx->GetInputVarPtrs("X")[0]);
      framework::Variable* y_var =
          boost::get<framework::Variable*>(ctx->GetInputVarPtrs("Y")[0]);

      auto& x_lod = x_var->Get<LoDTensor>().lod();
      auto& y_lod = y_var->Get<LoDTensor>().lod();

      PADDLE_ENFORCE_LE(x_lod.size(), 1,
                        "Number of lod level of Input(X) should not be "
                        "greater than 1.");

      PADDLE_ENFORCE(x_lod.size() == y_lod.size() || x_lod.size() == 0,
                     "Number of lod level of Input(X) either equal to 0 "
                     "or equal to that of Input(Y).");

      int64_t out_first_dim = 0;
      if (y_lod[ref_level].size() < 1) {
        out_first_dim = x_dims[0];
      } else {
        if (x_lod.size() == 1) {  // X is LoDTensor
          for (size_t i = 1; i < y_lod[ref_level].size(); ++i) {
            int x_seq_len = x_lod[0][i] - x_lod[0][i - 1];
            out_first_dim +=
                (y_lod[ref_level][i] - y_lod[ref_level][i - 1]) * x_seq_len;
          }
        } else {  // X is normal Tensor
          for (size_t i = 1; i < y_lod[ref_level].size(); ++i) {
            out_first_dim += y_lod[ref_level][i] - y_lod[ref_level][i - 1];
          }
        }
      }
      ctx->SetOutputDim("Out", {out_first_dim, x_dims[1]});
    } else {
      framework::VarDesc* in_reader =
          boost::get<framework::VarDesc*>(ctx->GetInputVarPtrs("Y")[0]);
      int lod_level_num = in_reader->GetLoDLevels().size();

      PADDLE_ENFORCE_GE(ref_level, 0,
                        "Level of referred lod should be greater or "
                        "equal to 0.");

      PADDLE_ENFORCE_LT(ref_level, lod_level_num,
                        "Level of referred lod should be smaller than "
                        "level number of Input(Y).");

      ctx->SetOutputDim("Out", {-1, x_dims[1]});
    }
W
wanghaoshuang 已提交
89 90 91
  }
};

W
wanghaoshuang 已提交
92
class SequenceExpandOpMaker : public framework::OpProtoAndCheckerMaker {
W
wanghaoshuang 已提交
93
 public:
94
  SequenceExpandOpMaker(OpProto* proto, OpAttrChecker* op_checker)
W
wanghaoshuang 已提交
95
      : OpProtoAndCheckerMaker(proto, op_checker) {
W
wanghaoshuang 已提交
96
    AddInput("X",
Y
yangyaming 已提交
97 98
             "(LoDTensor, default LoDTensor<float>) A 2-D LoDTensor whose lod "
             "level is at most 1.");
W
wanghaoshuang 已提交
99
    AddInput("Y",
Y
yangyaming 已提交
100 101
             "(LoDTensor, default LoDTensor<float>) Referred LoDTensor whose "
             "lod (specified level) is referred by Input(X).");
W
wanghaoshuang 已提交
102
    AddOutput("Out",
Y
yangyaming 已提交
103 104 105
              "(LodTensor, default LoDTensor<float>) Output LoDTensor which is "
              "generated from Input(X) by referring lod of Input(Y).");
    AddAttr<int>("ref_level", "Specify lod level of Input(Y).");
W
wanghaoshuang 已提交
106
    AddComment(R"DOC(
W
wanghaoshuang 已提交
107
Sequence Expand Operator.
W
wanghaoshuang 已提交
108

109 110
This operator expands input(X) according to LOD of input(Y).
Following are cases to better explain how this works:
W
wanghaoshuang 已提交
111
Case 1:
W
wanghaoshuang 已提交
112

W
wanghaoshuang 已提交
113
Given a 2-level LoDTensor input(X)
W
wanghaoshuang 已提交
114 115 116 117 118 119 120
    X.lod = [[0,       2, 3],
             [0, 1,    3, 4]]
    X.data = [a, b, c, d]
    X.dims = [4, 1]
and input(Y)
    Y.lod = [[0,    2,    4],
             [0, 3, 6, 7, 8]]
121
with condition len(Y.lod[-1]) -1 == X.dims[0]
W
wanghaoshuang 已提交
122 123 124 125 126
then we get 2-level LoDTensor
    Out.lod = [[0,                2,    4],
               [0,       3,       6, 7, 8]]
    Out.data = [a, a, a, b, b, b, c, d]
    Out.dims = [8, 1]
W
wanghaoshuang 已提交
127 128 129

Case 2:

W
wanghaoshuang 已提交
130
Given a common Tensor input(X)
W
wanghaoshuang 已提交
131 132 133 134
    X.data = [a, b, c]
    X.dims = [3, 1]
and input(Y)
    Y.lod = [[0, 2, 3, 6]]
135
with condition len(Y.lod[-1]) -1 == X.dims[0]
W
wanghaoshuang 已提交
136 137 138 139
then we get 1-level LoDTensor
    Out.lod = [[0,    2, 3,      6]]
    Out.data = [a, a, b, c, c, c]
    Out.dims = [6, 1]
W
wanghaoshuang 已提交
140 141 142

Case 3:

W
wanghaoshuang 已提交
143
Given a common Tensor input(X)
W
wanghaoshuang 已提交
144 145 146 147
    X.data = [[a, b], [c, d], [e, f]]
    X.dims = [3, 2]
and input(Y)
    Y.lod = [[0, 2, 3, 6]]
148
with condition len(Y.lod[-1]) -1 == X.dims[0]
W
wanghaoshuang 已提交
149
then we get 1-level LoDTensor
W
wanghaoshuang 已提交
150 151 152 153
    Out.lod = [[0,           2,     3,                     6]]
    Out.data = [[a,b], [a,b] [c,d], [e, f], [e, f], [e, f]]
    Out.dims = [6, 2]

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
Case 4:

Given 2-level a LoDTensor input(X)
    X.lod = [[0,       2, 3],
             [0, 1,    3, 4]]
    X.data = [a, b, c, d]
    X.dims = [4, 1]
and input(Y)
    Y.lod = [[0,    2,    4],
             [0, 3, 6, 6, 8]]
with condition len(Y.lod[-1]) -1 == X.dims[0]
then we get 2-level LoDTensor
    Out.lod = [[0,                2,    4],
               [0,       3,       6, 6, 8]]
    Out.data = [a, a, a, b, b, b, d, d]
    Out.dims = [8, 1]

W
wanghaoshuang 已提交
171 172 173 174 175

)DOC");
  }
};

W
wanghaoshuang 已提交
176
class SequenceExpandOpGrad : public framework::OperatorWithKernel {
W
wanghaoshuang 已提交
177 178 179 180 181
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
  void InferShape(framework::InferShapeContext* ctx) const override {
Y
yangyaming 已提交
182 183
    PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should not be null.");
    PADDLE_ENFORCE(ctx->HasInput("Out"), "Input(Out) should not be null.");
W
wanghaoshuang 已提交
184
    PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
Y
yangyaming 已提交
185 186
                   "Input(Out@GRAD) should not be null.");

W
wanghaoshuang 已提交
187 188
    auto x_dims = ctx->GetInputDim("X");
    auto x_grad_name = framework::GradVarName("X");
Y
yangyaming 已提交
189

W
wanghaoshuang 已提交
190 191 192 193 194 195 196 197 198 199
    if (ctx->HasOutput(x_grad_name)) {
      ctx->SetOutputDim(x_grad_name, x_dims);
    }
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
W
wanghaoshuang 已提交
200 201
REGISTER_OP(sequence_expand, ops::SequenceExpandOp, ops::SequenceExpandOpMaker,
            sequence_expand_grad, ops::SequenceExpandOpGrad);
Q
QI JUN 已提交
202
REGISTER_OP_CPU_KERNEL(
W
wanghaoshuang 已提交
203
    sequence_expand,
Y
yangyaming 已提交
204 205 206 207
    ops::SequenceExpandKernel<paddle::platform::CPUDeviceContext, float>,
    ops::SequenceExpandKernel<paddle::platform::CPUDeviceContext, double>,
    ops::SequenceExpandKernel<paddle::platform::CPUDeviceContext, int>,
    ops::SequenceExpandKernel<paddle::platform::CPUDeviceContext, int64_t>);
W
wanghaoshuang 已提交
208
REGISTER_OP_CPU_KERNEL(
W
wanghaoshuang 已提交
209
    sequence_expand_grad,
Y
yangyaming 已提交
210 211 212 213
    ops::SequenceExpandGradKernel<paddle::platform::CPUDeviceContext, float>,
    ops::SequenceExpandGradKernel<paddle::platform::CPUDeviceContext, double>,
    ops::SequenceExpandGradKernel<paddle::platform::CPUDeviceContext, int>,
    ops::SequenceExpandGradKernel<paddle::platform::CPUDeviceContext, int64_t>);