sequence_conv_op.cc 8.0 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

C
chengduoZH 已提交
33 34
    int context_length = ctx->Attrs().Get<int>("contextLength");
    int context_start = ctx->Attrs().Get<int>("contextStart");
C
chengduoZH 已提交
35

C
chengduoZH 已提交
36 37
    auto in_dims = ctx->GetInputDim("X");
    auto filter_dims = ctx->GetInputDim("Filter");
C
chengduoZH 已提交
38 39
    PADDLE_ENFORCE(ctx->Attrs().Get<int>("contextStride") == 1,
                   "Currently, SequenceConvOp only supports contextStride=1.");
C
chengduoZH 已提交
40 41
    PADDLE_ENFORCE(in_dims.size() == 2 && filter_dims.size() == 2,
                   "Input(X, Filter) should be 2-D tensor.");
C
chengduoZH 已提交
42 43
    PADDLE_ENFORCE(filter_dims[0] == context_length * in_dims[1],
                   "Filter's height should be context_length * "
C
chengduoZH 已提交
44
                   "input_hidden_size .");
C
chengduoZH 已提交
45

C
chengduoZH 已提交
46
    if (ctx->Attrs().Get<bool>("paddingTrainable")) {
C
chengduoZH 已提交
47 48 49
      PADDLE_ENFORCE(
          ctx->HasInput("PaddingData"),
          "Input(PaddingData) of SequenceConvOp should not be null.");
50
      framework::DDim padding_dim = ctx->GetInputDim("PaddingData");
C
chengduoZH 已提交
51 52 53 54 55
      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]);

56 57
      if (context_start == 0 && context_length == 1) {
        PADDLE_THROW(
C
chengduoZH 已提交
58
            "If context_start is 0 and context_length is 1, paddingTrainable "
59 60
            "should be false.");
      }
C
chengduoZH 已提交
61 62 63 64 65 66 67 68
      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 已提交
69
    in_dims[1] = filter_dims[1];
C
chengduoZH 已提交
70
    ctx->SetOutputDim("Out", in_dims);
C
chengduoZH 已提交
71
    ctx->ShareLoD("X", "Out");
C
chengduoZH 已提交
72 73 74
  }
};

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
    if (ctx->Attrs().Get<bool>("paddingTrainable") &&
C
chengduoZH 已提交
86
        ctx->HasOutput(framework::GradVarName("PaddingData"))) {
C
chengduoZH 已提交
87 88
      ctx->SetOutputDim(framework::GradVarName("PaddingData"),
                        ctx->GetInputDim("PaddingData"));
C
chengduoZH 已提交
89
    }
C
chengduoZH 已提交
90 91
    if (ctx->HasOutput(framework::GradVarName("X"))) {
      ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X"));
Q
Qiao Longfei 已提交
92
      ctx->ShareLoD("X", framework::GradVarName("X"));
C
chengduoZH 已提交
93
    }
C
chengduoZH 已提交
94 95 96 97
    if (ctx->HasOutput(framework::GradVarName("Filter"))) {
      ctx->SetOutputDim(framework::GradVarName("Filter"),
                        ctx->GetInputDim("Filter"));
    }
C
chengduoZH 已提交
98 99 100
  }
};

C
chengduoZH 已提交
101
class SequenceConvOpMaker : public framework::OpProtoAndCheckerMaker {
C
chengduoZH 已提交
102
 public:
C
chengduoZH 已提交
103 104
  SequenceConvOpMaker(framework::OpProto* proto,
                      framework::OpAttrChecker* op_checker)
C
chengduoZH 已提交
105
      : OpProtoAndCheckerMaker(proto, op_checker) {
C
chengduoZH 已提交
106 107
    AddInput(
        "X",
108
        "(LoDTensor) the input(X) is a LodTensor, which supports "
C
chengduoZH 已提交
109
        "variable-time length input sequence. The underlying tensor in "
110 111
        "this LoDTensor is a matrix with shape (T, N), where T is the "
        "total time steps in this mini-batch and N is the input_hidden_size.");
C
chengduoZH 已提交
112
    AddInput("PaddingData",
C
chengduoZH 已提交
113 114
             "(Tensor, optional) the input(PaddingData) is an optional "
             "parameter, and it is learnable. "
C
chengduoZH 已提交
115 116
             "This is a tensor with shape (P, N), where P is the "
             "top_pad + bottom_pad, N is the input_hidden_size. In order to "
C
chengduoZH 已提交
117 118 119 120
             "ensure the equal length of sequence before and after "
             "convolution, it is necessary to fill the top and bottom of each "
             "sequence according to context_length, context_stride and "
             "context_start")
C
chengduoZH 已提交
121
        .AsDispensable();
C
chengduoZH 已提交
122 123 124
    AddInput(
        "Filter",
        "(Tensor) the input(Filter) is an learnable parameter."
C
chengduoZH 已提交
125 126
        "This is a tensor with shape (K, M), where K is the "
        "context_length * input_hidden_size, M is the output feature size.");
C
chengduoZH 已提交
127 128 129 130
    AddOutput(
        "Out",
        "(LoDTensor) the output(Out) is a LodTensor, which support "
        "variable-time length output sequence. The underlying tensor in "
C
chengduoZH 已提交
131 132
        "this LoDTensor is a matrix with shape (T, M), where, T is the "
        "total time steps in this mini-batch, M is the output feature size.");
C
chengduoZH 已提交
133

C
chengduoZH 已提交
134
    AddAttr<bool>("paddingTrainable",
C
chengduoZH 已提交
135
                  "(bool, default:false) the padding data of SequenceConvOp "
C
chengduoZH 已提交
136 137
                  "is trainable or not.")
        .SetDefault(false);
C
chengduoZH 已提交
138
    AddAttr<int>("contextLength",
C
chengduoZH 已提交
139
                 "(int) the contextLength of SequenceConvOp is the "
C
chengduoZH 已提交
140
                 "height of the convolution kernel.")
C
chengduoZH 已提交
141
        .GreaterThan(0);
C
chengduoZH 已提交
142
    AddAttr<int>("contextStart",
C
chengduoZH 已提交
143
                 "(int, default:0) the contextStart of SequenceConvOp "
C
chengduoZH 已提交
144
                 "represents the beginning of the convolution of the number of "
C
chengduoZH 已提交
145 146 147 148 149
                 "rows of sequence, which can be negative. The negative number "
                 "means to pad contextStart time-steps of zeros or learnable "
                 "parameters at the beginning of each instance. The positive "
                 "number means to skip contextStart time-steps of each "
                 "instance.")
C
chengduoZH 已提交
150
        .SetDefault(0);
C
chengduoZH 已提交
151
    AddAttr<int>("contextStride",
C
chengduoZH 已提交
152
                 "(int, default:1) the contextStride of SequenceConvOp "
C
chengduoZH 已提交
153
                 "represents the stride length of convolution kernel. "
C
chengduoZH 已提交
154
                 "Currently, SequenceConvOp only supports"
C
chengduoZH 已提交
155
                 "contextStride=1.")
C
chengduoZH 已提交
156
        .SetDefault(1)
C
chengduoZH 已提交
157
        .GreaterThan(0);
C
chengduoZH 已提交
158 159

    AddComment(R"DOC(
160 161 162 163 164 165 166 167 168 169
Sequence Conv Operator.

SequenceConvOp performs convolution operation on features of contextLength
time-steps of each instance. The convolution operation calculates the output
based on the input, filter, strides and paddings parameters.
The size of each dimension of the parameters is checked during infer-shape.
In order to ensure the equal length of sequence before and after convolution,
it is necessary to fill the top and bottom of each sequence based on
context_length, context_stride and context_start.

C
chengduoZH 已提交
170 171 172 173 174 175 176 177
    )DOC");
  }
};

}  // namespace operators
}  // namespace paddle

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

REGISTER_OP_CPU_KERNEL(
Q
QI JUN 已提交
182 183 184
    sequence_conv,
    ops::SequenceConvKernel<paddle::platform::CPUDeviceContext, float>,
    ops::SequenceConvKernel<paddle::platform::CPUDeviceContext, double>);
C
chengduoZH 已提交
185
REGISTER_OP_CPU_KERNEL(
C
chengduoZH 已提交
186
    sequence_conv_grad,
Q
QI JUN 已提交
187 188
    ops::SequenceConvGradKernel<paddle::platform::CPUDeviceContext, float>,
    ops::SequenceConvGradKernel<paddle::platform::CPUDeviceContext, double>);