sequence_pad_op.cc 11.0 KB
Newer Older
Y
yangyaming 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* 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. */

W
Wu Yi 已提交
15
#include "paddle/fluid/operators/sequence_ops/sequence_pad_op.h"
16 17
#include <memory>
#include <string>
Y
yangyaming 已提交
18 19 20 21 22 23 24 25

namespace paddle {
namespace operators {

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

26
 protected:
Y
yangyaming 已提交
27
  void InferShape(framework::InferShapeContext* ctx) const override {
28
    PADDLE_ENFORCE_EQ(ctx->HasInput("X"), true,
29 30 31 32 33 34
                      platform::errors::InvalidArgument(
                          "Input(X) of SequencePadOp should not be null."));
    PADDLE_ENFORCE_EQ(
        ctx->HasInput("PadValue"), true,
        platform::errors::InvalidArgument(
            "Input(PadValue) of SequencePadOp should not be null."));
35
    PADDLE_ENFORCE_EQ(ctx->HasOutput("Out"), true,
36 37 38 39 40 41
                      platform::errors::InvalidArgument(
                          "Output(Out) of SequencePadOp should not be null."));
    PADDLE_ENFORCE_EQ(
        ctx->HasOutput("Length"), true,
        platform::errors::InvalidArgument(
            "Output(Length) of SequencePadOp should not be null."));
Y
yangyaming 已提交
42 43

    auto x_dims = ctx->GetInputDim("X");
44
    PADDLE_ENFORCE_GE(x_dims.size(), 2,
45 46 47 48
                      platform::errors::InvalidArgument(
                          "The rank of SequencePadOp Input(X) can't be less "
                          "than 2. But received (%d)",
                          x_dims.size()));
49 50
    auto time_step_dims = framework::slice_ddim(x_dims, 1, x_dims.size());
    auto pad_value_dims = ctx->GetInputDim("PadValue");
51 52 53
    PADDLE_ENFORCE_EQ(pad_value_dims == framework::make_ddim({1}) ||
                          pad_value_dims == time_step_dims,
                      true,
54 55 56
                      platform::errors::InvalidArgument(
                          "The Input(PadValue) must be a scalar or a tensor "
                          "whose shape equals to time steps in sequences"));
Y
yangyaming 已提交
57

F
fengjiayi 已提交
58
    int out_dim_0 = -1;
Y
yangyaming 已提交
59

60
    int padded_length = ctx->Attrs().Get<int>("padded_length");
Y
yangyaming 已提交
61
    if (ctx->IsRuntime()) {
62
      // run time
Y
yangyaming 已提交
63 64
      framework::Variable* x_var =
          boost::get<framework::Variable*>(ctx->GetInputVarPtrs("X")[0]);
65
      const auto& x_lod = x_var->Get<LoDTensor>().lod();
66
      PADDLE_ENFORCE_EQ(x_lod.empty(), false,
67 68
                        platform::errors::InvalidArgument(
                            "The Input(X) must hold lod info."));
69 70
      const auto& x_lod_0 = x_lod[0];
      PADDLE_ENFORCE_GE(x_lod_0.size(), 2,
71 72
                        platform::errors::InvalidArgument(
                            "The Input(X)'s lod info is corrupted. "));
73 74
      PADDLE_ENFORCE_EQ(
          x_dims[0], static_cast<int64_t>(x_lod_0.back()),
75 76 77 78
          platform::errors::InvalidArgument(
              "The Input(X)'s lod info mismatches the actual tensor shape. The "
              "Input(X)'s lod info is(%d), the actual tensor shape is(%d)",
              x_dims[0], static_cast<int64_t>(x_lod_0.back())));
79 80 81 82 83

      int seq_num = x_lod_0.size() - 1;
      int max_seq_len = math::MaximumSequenceLength(x_lod_0);
      if (padded_length == -1) {
        padded_length = max_seq_len;
Y
yangyaming 已提交
84
      }
85 86 87 88 89 90 91 92
      PADDLE_ENFORCE_GE(
          padded_length, max_seq_len,
          platform::errors::InvalidArgument(
              "The Attr(padded_length) must be -1 or an int greater than the "
              "length of the longest original sequence. But the padded_length "
              "received is (%d), the length of the longest original sequence "
              "is (%d)",
              padded_length, max_seq_len));
F
fengjiayi 已提交
93
      out_dim_0 = seq_num;
Y
yangyaming 已提交
94
    } else {
95
      // compile time
96 97 98
      if (padded_length == -1) {
        padded_length = 1;
      }
99 100 101 102 103
      PADDLE_ENFORCE_GT(ctx->GetLoDLevel("X"), 0,
                        platform::errors::InvalidArgument(
                            "The LoD level Input(X) of sequence_pad should be "
                            "larger than 0. But received (%d)",
                            ctx->GetLoDLevel("X")));
Y
yangyaming 已提交
104 105
    }

106
    std::vector<int> out_dims_vec{out_dim_0, padded_length};
107
    std::vector<int> len_dims_vec{out_dim_0};
108
    auto time_step_dims_vec = framework::vectorize<int>(time_step_dims);
F
fengjiayi 已提交
109 110 111
    out_dims_vec.insert(out_dims_vec.end(), time_step_dims_vec.begin(),
                        time_step_dims_vec.end());
    ctx->SetOutputDim("Out", framework::make_ddim(out_dims_vec));
112 113 114 115 116 117
    ctx->SetOutputDim("Length", framework::make_ddim(len_dims_vec));
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
118
    auto data_type = OperatorWithKernel::IndicateVarDataType(ctx, "X");
119
    return framework::OpKernelType(data_type, ctx.device_context());
Y
yangyaming 已提交
120 121 122 123 124
  }
};

class SequencePadOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
125
  void Make() override {
Y
yangyaming 已提交
126 127
    AddInput("X",
             "(LoDTensor, default LoDTensor<float>) Input variable which "
128 129 130 131 132 133 134 135 136
             "should contain lod information.");
    AddInput("PadValue",
             "(LoDTensor), this Tensor holds values that will be fill into "
             "padded steps. It can be a scalar or a tensor whose shape equals "
             "to time steps in sequences. If it's a scalar, it will be "
             "automatically broadcasted to the shape of time step.");
    AddOutput(
        "Out",
        "(LoDTensor) The output vairable, which contains padded sequences.");
137 138 139 140
    AddOutput(
        "Length",
        "(LoDTensor) The output vairable, which contains the actual length of "
        "sequences before padding.");
141 142
    AddAttr<int>(
        "padded_length",
T
tianshuo78520a 已提交
143
        "The length of padded sequences. It can be set to -1 or "
144 145 146 147 148
        "any positive int. When it is -1, all sequences will be padded up to "
        "the length of the longest one among them; when it a certain positive "
        "value, it must be greater than the length of the longest original "
        "sequence.")
        .SetDefault(-1);
Y
yangyaming 已提交
149
    AddComment(R"DOC(
F
fengjiayi 已提交
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
      Sequence Pad Operator

      This operator pads sequences in a same batch to a consistent length. 
      The length is specified by attribute 'padded_length'. New elements, 
      whose values are specified by input 'PadValue', will be appended to 
      the end of each sequence, to make their final lengths consistent.

      Following are cases to better explain how this works:

      Case 1:

      Given a 1-level LoDTensor input(X):
          X.lod = [[0, 2,       5]]
          X.data = [a, b, c, d, e]
      and Input(PadValue):
          PadValue.data = [0]
      and attribite 'padded_length' = 4,
F
fengjiayi 已提交
167 168 169
      then we get LoDTensor:
          Out.data = [[a, b, 0, 0], 
                      [c, d, e, 0]]
170
          Length.data = [2, 3]
F
fengjiayi 已提交
171 172 173 174 175 176 177 178 179 180
      
      Case 2:

      Given a 1-level LoDTensor input(X):
          X.lod = [[0,               2,                           5]]
          X.data = [[a1, a2], [b1, b2], [c1, c2], [d1, d2], [e1, e2]]
      and Input(PadValue):
          PadValue.data = [0]
      and attribite 'padded_length' = -1, which mean using the length 
      of longest input sequence(3 in this case),
F
fengjiayi 已提交
181 182 183
      then we get LoDTensor:
          Out.data = [[[a1, a2], [b1, b2], [0, 0]], 
                      [[c1, c2], [d1, d2], [e1, e2]]]
184
          Length.data = [2, 3]
185
 
F
fengjiayi 已提交
186 187 188 189 190 191 192 193 194
      Case 3:

      Given a 1-level LoDTensor input(X):
          X.lod = [[0,               2,                           5]]
          X.data = [[a1, a2], [b1, b2], [c1, c2], [d1, d2], [e1, e2]]
      and Input(PadValue):
          PadValue.data = [p1, p2]
      and attribite 'padded_length' = -1, which mean using the length 
      of longest input sequence(3 in this case),
F
fengjiayi 已提交
195 196 197
      then we get LoDTensor:
          Out.data = [[[a1, a2], [b1, b2], [p1, p2]], 
                      [[c1, c2], [d1, d2], [e1, e2]]]
198
          Length.data = [2, 3]
Y
yangyaming 已提交
199 200 201 202 203 204 205 206 207 208

    )DOC");
  }
};

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

  void InferShape(framework::InferShapeContext* ctx) const override {
209
    PADDLE_ENFORCE_EQ(ctx->HasInput("X"), true,
210 211
                      platform::errors::InvalidArgument(
                          "Input(X) of SequencePadGradOp should not be null."));
212 213
    PADDLE_ENFORCE_EQ(
        ctx->HasInput(framework::GradVarName("Out")), true,
214 215
        platform::errors::InvalidArgument(
            "Input(Out@GRAD) of SequencePadGradOp should not be null."));
Y
yangyaming 已提交
216 217 218 219 220 221

    if (ctx->HasOutput(framework::GradVarName("X"))) {
      ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X"));
      ctx->ShareLoD("X", /*->*/ framework::GradVarName("X"));
    }
  }
222 223 224 225

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
226 227
    auto data_type = OperatorWithKernel::IndicateVarDataType(
        ctx, framework::GradVarName("Out"));
228 229
    return framework::OpKernelType(data_type, ctx.device_context());
  }
Y
yangyaming 已提交
230 231
};

H
hong 已提交
232 233
template <typename T>
class SequencePadGradOpMaker : public framework::SingleGradOpMaker<T> {
234
 public:
H
hong 已提交
235
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
236 237

 protected:
238
  void Apply(GradOpPtr<T> op) const override {
239
    op->SetType("sequence_pad_grad");
H
hong 已提交
240 241 242 243
    op->SetAttrMap(this->Attrs());
    op->SetInput("X", this->Input("X"));
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
244 245 246
  }
};

247 248
DECLARE_NO_NEED_BUFFER_VARS_INFERER(SequencePadGradOpNoNeedBufferVarsInference,
                                    "X");
249

Y
yangyaming 已提交
250 251 252 253 254
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OPERATOR(sequence_pad, ops::SequencePadOp, ops::SequencePadOpMaker,
H
hong 已提交
255 256
                  ops::SequencePadGradOpMaker<paddle::framework::OpDesc>,
                  ops::SequencePadGradOpMaker<paddle::imperative::OpBase>);
257 258
REGISTER_OPERATOR(sequence_pad_grad, ops::SequencePadGradOp,
                  ops::SequencePadGradOpNoNeedBufferVarsInference);
Y
yangyaming 已提交
259 260 261 262 263 264 265 266 267 268 269 270
REGISTER_OP_CPU_KERNEL(
    sequence_pad,
    ops::SequencePadOpKernel<paddle::platform::CPUDeviceContext, float>,
    ops::SequencePadOpKernel<paddle::platform::CPUDeviceContext, double>,
    ops::SequencePadOpKernel<paddle::platform::CPUDeviceContext, int>,
    ops::SequencePadOpKernel<paddle::platform::CPUDeviceContext, int64_t>);
REGISTER_OP_CPU_KERNEL(
    sequence_pad_grad,
    ops::SequencePadGradOpKernel<paddle::platform::CPUDeviceContext, float>,
    ops::SequencePadGradOpKernel<paddle::platform::CPUDeviceContext, double>,
    ops::SequencePadGradOpKernel<paddle::platform::CPUDeviceContext, int>,
    ops::SequencePadGradOpKernel<paddle::platform::CPUDeviceContext, int64_t>);