sequence_reshape_op.cc 5.4 KB
Newer Older
1
//   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2 3 4 5 6 7 8 9 10 11 12 13
//
// 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.
Y
yangyaming 已提交
14

W
Wu Yi 已提交
15
#include "paddle/fluid/operators/sequence_ops/sequence_reshape_op.h"
H
hong 已提交
16
#include <memory>
Y
Yi Wang 已提交
17
#include "paddle/fluid/framework/ddim.h"
Y
yangyaming 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30

namespace paddle {
namespace operators {

class SequenceReshapeOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("X"),
                   "Input(X) of SequenceReshapeOp should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput("Out"),
                   "Output(Out) of SequenceReshapeOp should not be null.");
    auto x_dims = ctx->GetInputDim("X");
Y
yangyaming 已提交
31
    auto x_numel = product(x_dims);
Y
yangyaming 已提交
32
    PADDLE_ENFORCE_EQ(x_dims.size(), 2U, "Rank of Input(X) should be 2.");
Y
yangyaming 已提交
33
    int new_dim = ctx->Attrs().Get<int>("new_dim");
34 35 36 37 38 39
    if (ctx->IsRuntime()) {
      ctx->SetOutputDim("Out",
                        {x_numel / new_dim, static_cast<int64_t>(new_dim)});
    } else {
      // when compiling, the batch size is undetermined, just set to -1
      ctx->SetOutputDim("Out", {-1, static_cast<int64_t>(new_dim)});
40 41 42
      // when compiling, the LodLevel of Out is set to be 1, which is consistent
      // with that in running time.
      ctx->SetLoDLevel("Out", 1);
43
    }
Y
yangyaming 已提交
44 45 46 47 48
  }
};

class SequenceReshapeOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
49
  void Make() override {
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
    AddInput("X",
             "(LoDTensor, default LoDTensor<float>) A 2-D LoDTensor with shape "
             "being [N, M].");
    AddOutput("Out",
              "(LoDTensor, default LoDTensor<float>) A 2-D LoDTensor with "
              "shape [T, new_dim] where T is calculated based on X.lod, M and "
              "new_dim.");
    AddAttr<int>("new_dim", "Sequence dimension of the output LoDTensor.");
    AddComment(R"DOC(
Sequence Reshape Operator.

This operator will rearrange the input sequences. The new dimension is set by
attribute and length of each sequence may change longer or shorter which is
decided by original length, original dimension and new dimension. The following
example will help to illustrate the function of this operator:

x is a LoDTensor:
    x.lod  = [[0, 2, 6]]
Y
yangyaming 已提交
68 69
    x.data = [[1, 2], [3, 4],
              [5, 6], [7, 8], [9, 10], [11, 12]]
70 71 72 73 74
    x.dims = [6, 2]

set new_dim = 4

then out is a LoDTensor:
Y
yangyaming 已提交
75 76 77
    out.lod  = [[0, 1, 3]]
    out.data = [[1, 2, 3, 4],
                [5, 6, 7, 8], [9, 10, 11, 12]]
78 79 80 81 82 83 84
    out.dims = [3, 4]

Currently, only 1-level LoDTensor is supported and please make sure (original
length * original dimension) can be divided by new_dim with no remainder for
each sequence.

)DOC");
Y
yangyaming 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98
  }
};

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

  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE(
        ctx->HasInput(framework::GradVarName("Out")),
        "Input(Out@GRAD) of SequenceReshapeGradOp should not be null.");
    PADDLE_ENFORCE(ctx->HasInput("X"),
                   "Input(X) of SequenceReshapeGradOp should  not be null.");

99
    ctx->ShareDim("X", /*->*/ framework::GradVarName("X"));
Y
yangyaming 已提交
100 101 102 103
    ctx->ShareLoD("X", /*->*/ framework::GradVarName("X"));
  }
};

H
hong 已提交
104 105
template <typename T>
class SequenceReshapeGradOpMaker : public framework::SingleGradOpMaker<T> {
106
 public:
H
hong 已提交
107
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
108 109

 protected:
110
  void Apply(GradOpPtr<T> op_desc_ptr) const override {
111
    op_desc_ptr->SetType("sequence_reshape_grad");
H
hong 已提交
112 113 114 115 116
    op_desc_ptr->SetInput("X", this->Input("X"));
    op_desc_ptr->SetInput(framework::GradVarName("Out"),
                          this->OutputGrad("Out"));
    op_desc_ptr->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op_desc_ptr->SetAttrMap(this->Attrs());
117 118 119
  }
};

Y
yangyaming 已提交
120 121 122 123 124
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OPERATOR(sequence_reshape, ops::SequenceReshapeOp,
H
hong 已提交
125 126 127
                  ops::SequenceReshapeOpMaker,
                  ops::SequenceReshapeGradOpMaker<paddle::framework::OpDesc>,
                  ops::SequenceReshapeGradOpMaker<paddle::imperative::OpBase>);
Y
yangyaming 已提交
128 129 130
REGISTER_OPERATOR(sequence_reshape_grad, ops::SequenceReshapeGradOp);
REGISTER_OP_CPU_KERNEL(
    sequence_reshape,
Y
yangyaming 已提交
131 132 133 134
    ops::SequenceReshapeKernel<paddle::platform::CPUDeviceContext, float>,
    ops::SequenceReshapeKernel<paddle::platform::CPUDeviceContext, double>,
    ops::SequenceReshapeKernel<paddle::platform::CPUDeviceContext, int>,
    ops::SequenceReshapeKernel<paddle::platform::CPUDeviceContext, int64_t>);
Y
yangyaming 已提交
135 136
REGISTER_OP_CPU_KERNEL(
    sequence_reshape_grad,
Y
yangyaming 已提交
137 138 139 140
    ops::SequenceReshapeGradKernel<paddle::platform::CPUDeviceContext, float>,
    ops::SequenceReshapeGradKernel<paddle::platform::CPUDeviceContext, double>,
    ops::SequenceReshapeGradKernel<paddle::platform::CPUDeviceContext, int64_t>,
    ops::SequenceReshapeGradKernel<paddle::platform::CPUDeviceContext, int>);