sequence_unpad_op.cc 6.5 KB
Newer Older
Y
Yibing Liu 已提交
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_unpad_op.h"
16 17
#include <memory>
#include <string>
Y
Yibing Liu 已提交
18 19 20 21 22 23 24 25 26 27

namespace paddle {
namespace operators {

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

 protected:
  void InferShape(framework::InferShapeContext* ctx) const override {
28 29 30 31 32 33
    PADDLE_ENFORCE_EQ(ctx->HasInput("X"), true,
                      "Input(X) of SequenceUnpadOp should not be null.");
    PADDLE_ENFORCE_EQ(ctx->HasInput("Length"), true,
                      "Input(Length) of SequenceUnpadOp should not be null.");
    PADDLE_ENFORCE_EQ(ctx->HasOutput("Out"), true,
                      "Output(Out) of SequenceUnpadOp should not be null.");
Y
Yibing Liu 已提交
34 35 36 37 38 39

    auto x_dims = ctx->GetInputDim("X");
    PADDLE_ENFORCE_GE(x_dims.size(), 2,
                      "The rank of Input(X) can't be less than 2.");

    auto len_dims = ctx->GetInputDim("Length");
40 41 42 43
    PADDLE_ENFORCE_EQ(len_dims.size(), 1,
                      "The shape of Input(Length) should be [batch_size].");
    PADDLE_ENFORCE_EQ(
        len_dims[0], x_dims[0],
Y
Yibing Liu 已提交
44 45 46 47 48 49 50 51 52 53 54
        "Input(X) and Input(Length) should have the same first dimension.");

    int64_t out_dim_0 = -1;
    if (ctx->IsRuntime()) {
      out_dim_0 = x_dims[0] * x_dims[1];
    }

    std::vector<int64_t> out_dims_vec{out_dim_0};
    if (x_dims.size() == 2) {
      out_dims_vec.push_back(1);
    } else {
T
Tao Luo 已提交
55
      for (int i = 2; i < x_dims.size(); ++i) {
Y
Yibing Liu 已提交
56 57 58 59
        out_dims_vec.push_back(x_dims[i]);
      }
    }
    ctx->SetOutputDim("Out", framework::make_ddim(out_dims_vec));
60 61 62 63 64
    if (!ctx->IsRuntime()) {
      framework::VarDesc* out_desc =
          boost::get<framework::VarDesc*>(ctx->GetOutputVarPtrs("Out")[0]);
      out_desc->SetLoDLevel(1);
    }
Y
Yibing Liu 已提交
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    auto data_type = framework::GetDataTypeOfVar(ctx.InputVar("X"));
    return framework::OpKernelType(data_type, ctx.device_context());
  }
};

class SequenceUnpadOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X",
             "(LoDTensor, default LoDTensor<float>) Input tensor which "
             "contains the padded sequences with equal length.");
    AddInput("Length",
             "(LoDTensor) The input tensor which specifies the actual ength of "
             "sequences after unpadding.");
    AddOutput(
        "Out",
        "(LoDTensor) The output tensor which contains unpadded sequences.");
    AddComment(R"DOC(
      Sequence Unpad Operator

      This operator removes the padding data in the input sequences and convert 
      them into sequences with actual length as output, identitied by lod 
      information.

      Example:

      Given input tensor Input(X):
          X.data = [[ 1.0,  2.0,  3.0,  4.0,  5.0],
                    [ 6.0,  7.0,  8.0,  9.0, 10.0],
                    [11.0, 12.0, 13.0, 14.0, 15.0]], 
`     
      in which there are 3 sequences padded to length 5, and the acutal length 
      specified by Input(Length):

104
          Length.data = [2, 3, 4],
Y
Yibing Liu 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

      after unpadding, Output(Out) will be:

          Out.data = [[1.0, 2.0, 6.0, 7.0, 8.0, 11.0, 12.0, 13.0, 14.0]]
          Out.lod = [[0, 2, 5, 9]]      

    )DOC");
  }
};

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

  void InferShape(framework::InferShapeContext* ctx) const override {
120 121 122 123
    PADDLE_ENFORCE_EQ(ctx->HasInput("X"), true,
                      "Input(X) of SequenceUnpadGradOp should not be null.");
    PADDLE_ENFORCE_EQ(
        ctx->HasInput(framework::GradVarName("Out")), true,
Y
Yibing Liu 已提交
124 125 126 127 128 129 130 131 132 133 134
        "Input(Out@GRAD) of SequenceUnpadGradOp should not be null.");

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

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
135 136
    auto data_type = framework::GetDataTypeOfVar(
        ctx.InputVar(framework::GradVarName("Out")));
Y
Yibing Liu 已提交
137 138 139 140
    return framework::OpKernelType(data_type, ctx.device_context());
  }
};

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
class SequenceUnpadGradOpDescMaker : 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("sequence_unpad_grad");
    op->SetAttrMap(Attrs());
    op->SetInput("X", Input("X"));
    op->SetInput(framework::GradVarName("Out"), OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), InputGrad("X"));
    return op;
  }
};

DECLARE_NO_NEED_BUFFER_VARS_INFERENCE(
    SequenceUnpadGradOpNoNeedBufferVarsInference, "X");

Y
Yibing Liu 已提交
160 161 162 163 164
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OPERATOR(sequence_unpad, ops::SequenceUnpadOp,
165 166 167
                  ops::SequenceUnpadOpMaker, ops::SequenceUnpadGradOpDescMaker);
REGISTER_OPERATOR(sequence_unpad_grad, ops::SequenceUnpadGradOp,
                  ops::SequenceUnpadGradOpNoNeedBufferVarsInference);
Y
Yibing Liu 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180
REGISTER_OP_CPU_KERNEL(
    sequence_unpad,
    ops::SequenceUnpadOpKernel<paddle::platform::CPUDeviceContext, float>,
    ops::SequenceUnpadOpKernel<paddle::platform::CPUDeviceContext, double>,
    ops::SequenceUnpadOpKernel<paddle::platform::CPUDeviceContext, int>,
    ops::SequenceUnpadOpKernel<paddle::platform::CPUDeviceContext, int64_t>);
REGISTER_OP_CPU_KERNEL(
    sequence_unpad_grad,
    ops::SequenceUnpadGradOpKernel<paddle::platform::CPUDeviceContext, float>,
    ops::SequenceUnpadGradOpKernel<paddle::platform::CPUDeviceContext, double>,
    ops::SequenceUnpadGradOpKernel<paddle::platform::CPUDeviceContext, int>,
    ops::SequenceUnpadGradOpKernel<paddle::platform::CPUDeviceContext,
                                   int64_t>);