sequence_conv_op.cc 7.1 KB
Newer Older
C
chengduoZH 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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. */

C
chengduoZH 已提交
15
#include "paddle/operators/sequence_conv_op.h"
C
chengduoZH 已提交
16 17 18 19

namespace paddle {
namespace operators {

C
chengduoZH 已提交
20
class SequenceConvOp : public framework::OperatorWithKernel {
C
chengduoZH 已提交
21 22 23 24 25 26
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("X"),
C
chengduoZH 已提交
27 28 29
                   "Input(X) of SequenceConvOp should not be null.");
    PADDLE_ENFORCE(ctx->HasInput("Filter"),
                   "Input(Filter) of SequenceConvOp should not be null.");
C
chengduoZH 已提交
30
    PADDLE_ENFORCE(ctx->HasOutput("Out"),
C
chengduoZH 已提交
31
                   "Output(Out) of SequenceConvOp should not be null.");
C
chengduoZH 已提交
32 33
    // PaddingData mast be not empty. Otherwise(EnforceNotMet: enforce numel() >
    // 0 failed, 0 <= 0)
C
chengduoZH 已提交
34 35
    PADDLE_ENFORCE(ctx->HasInput("PaddingData"),
                   "Input(PaddingData) of SequenceConvOp should not be null.");
C
chengduoZH 已提交
36 37 38 39 40

    int context_length = ctx->Attrs().Get<int>("context_length");
    bool padding_trainable = ctx->Attrs().Get<bool>("padding_trainable");
    int context_start = ctx->Attrs().Get<int>("context_start");

C
chengduoZH 已提交
41 42 43 44 45 46 47 48 49
    auto in_dims = ctx->GetInputDim("X");
    auto filter_dims = ctx->GetInputDim("Filter");
    PADDLE_ENFORCE(in_dims.size() == 2 && filter_dims.size() == 2,
                   "Input(X, Filter) should be 2-D tensor.");
    PADDLE_ENFORCE(
        filter_dims[0] == context_length && filter_dims[1] == in_dims[1],
        "Filter's shape should be (context_length x "
        "number_of_input_features).");

C
chengduoZH 已提交
50
    if (padding_trainable) {
51
      framework::DDim padding_dim = ctx->GetInputDim("PaddingData");
C
chengduoZH 已提交
52 53 54 55 56
      int up_pad = std::max(0, -context_start);
      int down_pad = std::max(0, context_start + context_length - 1);
      int total_pad = up_pad + down_pad;
      int input_width = static_cast<int>(in_dims[1]);

57 58
      if (context_start == 0 && context_length == 1) {
        PADDLE_THROW(
C
chengduoZH 已提交
59
            "If context_start is 0 and context_length is 1, padding_trainable "
60 61
            "should be false.");
      }
C
chengduoZH 已提交
62 63 64 65 66 67 68 69
      PADDLE_ENFORCE(padding_dim.size() == 2,
                     "Input(PaddingData) should be 2-D tensor.");
      PADDLE_ENFORCE(
          padding_dim[0] == total_pad && padding_dim[1] == input_width,
          "Input(PaddingData)'s shape is not consistent with 'context_start' "
          "and 'context_length'.");
    }

C
chengduoZH 已提交
70
    in_dims[1] = 1;
C
chengduoZH 已提交
71 72 73 74
    ctx->SetOutputDim("Out", in_dims);
  }
};

C
chengduoZH 已提交
75
class SequenceConvGradOp : public framework::OperatorWithKernel {
C
chengduoZH 已提交
76 77 78 79 80 81
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
C
chengduoZH 已提交
82 83
                   "Gradient of output(Out) should not be null.");
    PADDLE_ENFORCE(ctx->HasInput("X"), "The input(X) should not be null.");
C
chengduoZH 已提交
84

C
chengduoZH 已提交
85 86
    if (ctx->Attrs().Get<bool>("padding_trainable") &&
        ctx->HasOutput(framework::GradVarName("PaddingData"))) {
C
chengduoZH 已提交
87 88
      ctx->SetOutputDim(framework::GradVarName("PaddingData"),
                        ctx->GetInputDim("PaddingData"));
C
chengduoZH 已提交
89
    }
C
chengduoZH 已提交
90 91 92
    if (ctx->HasOutput(framework::GradVarName("X"))) {
      ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X"));
    }
C
chengduoZH 已提交
93 94 95 96
    if (ctx->HasOutput(framework::GradVarName("Filter"))) {
      ctx->SetOutputDim(framework::GradVarName("Filter"),
                        ctx->GetInputDim("Filter"));
    }
C
chengduoZH 已提交
97 98 99
  }
};

C
chengduoZH 已提交
100
class SequenceConvOpMaker : public framework::OpProtoAndCheckerMaker {
C
chengduoZH 已提交
101
 public:
C
chengduoZH 已提交
102 103
  SequenceConvOpMaker(framework::OpProto* proto,
                      framework::OpAttrChecker* op_checker)
C
chengduoZH 已提交
104
      : OpProtoAndCheckerMaker(proto, op_checker) {
C
chengduoZH 已提交
105
    AddInput("X",
C
chengduoZH 已提交
106
             "(A float LoDTensor) the input of SequenceConvOp, a vector of "
C
chengduoZH 已提交
107 108
             "2-D matrix of size (minibatch, number_of_input_features).");
    AddInput("PaddingData",
C
chengduoZH 已提交
109
             "(A float LoDTensor) the input of SequenceConvOp, a vector of "
C
chengduoZH 已提交
110 111
             "2-D matrix of size (up_pad + down_pad, "
             "number_of_input_features). ");
C
chengduoZH 已提交
112 113 114 115 116 117
    AddInput("Filter",
             "(A float LoDTensor) the input of SequenceConvOp, a vector of "
             "2-D matrix of size (context_length x number_of_input_features).");
    AddOutput("Out",
              "(A float LoDTensor) the output of SequenceConvOp, a vector "
              "of 2-D matrix of size (minibatch, 1).");
C
chengduoZH 已提交
118 119

    AddAttr<bool>("padding_trainable",
C
chengduoZH 已提交
120
                  "(bool, default false) the padding data of SequenceConvOp "
C
chengduoZH 已提交
121 122 123
                  "is trainable or not.")
        .SetDefault(false);
    AddAttr<int>("context_length",
C
chengduoZH 已提交
124
                 "(int, default 3) the context_length of SequenceConvOp.")
C
chengduoZH 已提交
125 126 127
        .SetDefault(3)
        .GreaterThan(0);
    AddAttr<int>("context_start",
C
chengduoZH 已提交
128
                 "(int, default 0) the context_start of SequenceConvOp.")
C
chengduoZH 已提交
129 130
        .SetDefault(0);
    AddAttr<int>("context_stride",
C
chengduoZH 已提交
131
                 "(int, default 1) the context_stride of SequenceConvOp. "
C
chengduoZH 已提交
132 133
                 "Currently, sequence_project_op only support "
                 "context_stride=1.")
C
chengduoZH 已提交
134
        .SetDefault(1)
C
chengduoZH 已提交
135
        .GreaterThan(0);
C
chengduoZH 已提交
136 137

    AddComment(R"DOC(
C
chengduoZH 已提交
138
    SequenceConvOp projects features of context_length time-steps of each instance.
C
chengduoZH 已提交
139 140 141 142 143 144

    For a mini-batch of 2 variable lengths sentences, containing 3, and 1 time-steps:

    Assumed input (X) is a [4, M, N] float LoDTensor, and X->lod()[0] = [0, 3, 4].
    Besides, for the sake of simplicity, we assume M=1 and N=2.

C
chengduoZH 已提交
145 146
    X = [[a1, a2;
          b1, b2;
C
chengduoZH 已提交
147 148 149 150 151 152 153
          c1, c2]
         [d1, d2]]

    This is to say that input (X) has 4 words and the dimension of each word
    representation is 2.

    - Case1:
C
chengduoZH 已提交
154
    If context_start is -1 and padding_trainable is false, we use zero to pad instead of learned weight to pad,
C
chengduoZH 已提交
155 156
    and the context_lenth is 3, the output (Out) is:

C
chengduoZH 已提交
157
    Out =[[0,  0,  a1, a2, b1, b2;
C
chengduoZH 已提交
158
           a1, a2, b1, b2, c1, c2;
C
chengduoZH 已提交
159 160
           b1, b2, c1, c2, 0,  0 ]
           [0,  0,  d1, d2, 0,  0 ]]
C
chengduoZH 已提交
161 162

    - Case2:
C
chengduoZH 已提交
163 164 165
    If context_start is -1 and padding_trainable is true, we use learned weight to pad,
    and the context_lenth is 3, the output (Out) is:

C
chengduoZH 已提交
166
    Out = [[w1, w2, a1, a2, b1, b2;
C
chengduoZH 已提交
167
           a1, a2, b1, b2, c1, c2;
C
chengduoZH 已提交
168 169
           b1, b2, c1, c2, w3, w4]
           [w1, w2, d1, d2, w3, w4]]
C
chengduoZH 已提交
170 171 172 173 174 175 176 177 178

    )DOC");
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
C
chengduoZH 已提交
179 180
REGISTER_OP(sequence_conv, ops::SequenceConvOp, ops::SequenceConvOpMaker,
            sequence_conv_grad, ops::SequenceConvGradOp);
C
chengduoZH 已提交
181 182

REGISTER_OP_CPU_KERNEL(
C
chengduoZH 已提交
183
    sequence_conv, ops::SequenceConvKernel<paddle::platform::CPUPlace, float>);
C
chengduoZH 已提交
184
REGISTER_OP_CPU_KERNEL(
C
chengduoZH 已提交
185 186
    sequence_conv_grad,
    ops::SequenceConvGradKernel<paddle::platform::CPUPlace, float>);