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

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_conv_op.h"
C
chengduoZH 已提交
16

Y
Yang Yang 已提交
17
#include <algorithm>
18 19 20
#include <memory>
#include <string>
#include <unordered_set>
Y
Yang Yang 已提交
21

C
chengduoZH 已提交
22 23 24
namespace paddle {
namespace operators {

C
chengduoZH 已提交
25
class SequenceConvOp : public framework::OperatorWithKernel {
C
chengduoZH 已提交
26 27 28 29
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
30
  void InferShape(framework::InferShapeContext *ctx) const override {
31 32 33
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "SequenceConv");
    OP_INOUT_CHECK(ctx->HasInput("Filter"), "Input", "Filter", "SequenceConv");
    OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "SequenceConv");
C
chengduoZH 已提交
34

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

C
chengduoZH 已提交
38 39
    auto in_dims = ctx->GetInputDim("X");
    auto filter_dims = ctx->GetInputDim("Filter");
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
    PADDLE_ENFORCE_EQ(
        ctx->Attrs().Get<int>("contextStride"), 1,
        platform::errors::InvalidArgument(
            "Currently, SequenceConvOp only supports contextStride=1. But "
            "received contextStride = %u.",
            ctx->Attrs().Get<int>("contextStride")));
    PADDLE_ENFORCE_EQ(
        in_dims.size() == 2 && filter_dims.size() == 2, true,
        platform::errors::InvalidArgument(
            "Input(X, Filter) should be 2-D tensor. But received Input(X): "
            "input rank %u, input shape [%s]; received Input(Filter): "
            "input rank %u, input shape [%s].",
            in_dims.size(), in_dims, filter_dims.size(), filter_dims));
    PADDLE_ENFORCE_EQ(
        filter_dims[0], context_length * in_dims[1],
        platform::errors::InvalidArgument(
            "Filter's height should be context_length * "
            "input_hidden_size. But received: filter's height = %d, "
            "context_length * input_hidden_size = %d.",
            filter_dims[0], context_length * in_dims[1]));
C
chengduoZH 已提交
60

C
chengduoZH 已提交
61
    if (ctx->Attrs().Get<bool>("paddingTrainable")) {
C
chengduoZH 已提交
62 63 64
      PADDLE_ENFORCE(
          ctx->HasInput("PaddingData"),
          "Input(PaddingData) of SequenceConvOp should not be null.");
65
      framework::DDim padding_dim = ctx->GetInputDim("PaddingData");
C
chengduoZH 已提交
66 67 68 69 70
      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]);

71 72
      if (context_start == 0 && context_length == 1) {
        PADDLE_THROW(
C
chengduoZH 已提交
73
            "If context_start is 0 and context_length is 1, paddingTrainable "
74 75
            "should be false.");
      }
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
      PADDLE_ENFORCE_EQ(
          padding_dim.size(), 2,
          platform::errors::InvalidArgument(
              "Input(PaddingData) should be 2-D tensor. But received: "
              "input rank %u, input shape [%s].",
              padding_dim.size(), padding_dim));
      PADDLE_ENFORCE_EQ(
          padding_dim[0] == total_pad && padding_dim[1] == input_width, true,
          platform::errors::InvalidArgument("Input(PaddingData)'s shape is not "
                                            "consistent with 'context_start' "
                                            "and 'context_length'. Received "
                                            "Input(PaddingData): input rank "
                                            "%u, "
                                            "input shape [%s].",
                                            padding_dim.size(), padding_dim));
C
chengduoZH 已提交
91 92
    }

C
chengduoZH 已提交
93
    in_dims[1] = filter_dims[1];
C
chengduoZH 已提交
94
    ctx->SetOutputDim("Out", in_dims);
C
chengduoZH 已提交
95
    ctx->ShareLoD("X", "Out");
C
chengduoZH 已提交
96 97 98
  }
};

C
chengduoZH 已提交
99
class SequenceConvGradOp : public framework::OperatorWithKernel {
C
chengduoZH 已提交
100 101 102 103
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
104
  void InferShape(framework::InferShapeContext *ctx) const override {
105 106 107
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")), "Input",
                   framework::GradVarName("Out"), "SequenceConvGrad");
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "SequenceConvGrad");
C
chengduoZH 已提交
108

C
chengduoZH 已提交
109
    if (ctx->Attrs().Get<bool>("paddingTrainable") &&
C
chengduoZH 已提交
110
        ctx->HasOutput(framework::GradVarName("PaddingData"))) {
C
chengduoZH 已提交
111 112
      ctx->SetOutputDim(framework::GradVarName("PaddingData"),
                        ctx->GetInputDim("PaddingData"));
C
chengduoZH 已提交
113
    }
C
chengduoZH 已提交
114
    if (ctx->HasOutput(framework::GradVarName("X"))) {
115 116
      ctx->ShareDim("X", /*->*/ framework::GradVarName("X"));
      ctx->ShareLoD("X", /*->*/ framework::GradVarName("X"));
C
chengduoZH 已提交
117
    }
C
chengduoZH 已提交
118 119 120 121
    if (ctx->HasOutput(framework::GradVarName("Filter"))) {
      ctx->SetOutputDim(framework::GradVarName("Filter"),
                        ctx->GetInputDim("Filter"));
    }
C
chengduoZH 已提交
122 123 124
  }
};

C
chengduoZH 已提交
125
class SequenceConvOpMaker : public framework::OpProtoAndCheckerMaker {
C
chengduoZH 已提交
126
 public:
Y
Yu Yang 已提交
127
  void Make() override {
C
chengduoZH 已提交
128 129
    AddInput(
        "X",
130
        "(LoDTensor) the input(X) is a LodTensor, which supports "
C
chengduoZH 已提交
131
        "variable-time length input sequence. The underlying tensor in "
132 133
        "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 已提交
134
    AddInput("PaddingData",
C
chengduoZH 已提交
135 136
             "(Tensor, optional) the input(PaddingData) is an optional "
             "parameter, and it is learnable. "
C
chengduoZH 已提交
137 138
             "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 已提交
139 140 141 142
             "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 已提交
143
        .AsDispensable();
C
chengduoZH 已提交
144 145 146
    AddInput(
        "Filter",
        "(Tensor) the input(Filter) is an learnable parameter."
C
chengduoZH 已提交
147 148
        "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 已提交
149 150 151 152
    AddOutput(
        "Out",
        "(LoDTensor) the output(Out) is a LodTensor, which support "
        "variable-time length output sequence. The underlying tensor in "
C
chengduoZH 已提交
153 154
        "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 已提交
155

C
chengduoZH 已提交
156
    AddAttr<bool>("paddingTrainable",
C
chengduoZH 已提交
157
                  "(bool, default:false) the padding data of SequenceConvOp "
C
chengduoZH 已提交
158 159
                  "is trainable or not.")
        .SetDefault(false);
C
chengduoZH 已提交
160
    AddAttr<int>("contextLength",
C
chengduoZH 已提交
161
                 "(int) the contextLength of SequenceConvOp is the "
C
chengduoZH 已提交
162
                 "height of the convolution kernel.")
C
chengduoZH 已提交
163
        .GreaterThan(0);
C
chengduoZH 已提交
164
    AddAttr<int>("contextStart",
C
chengduoZH 已提交
165
                 "(int, default:0) the contextStart of SequenceConvOp "
C
chengduoZH 已提交
166
                 "represents the beginning of the convolution of the number of "
C
chengduoZH 已提交
167 168 169 170 171
                 "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 已提交
172
        .SetDefault(0);
C
chengduoZH 已提交
173
    AddAttr<int>("contextStride",
C
chengduoZH 已提交
174
                 "(int, default:1) the contextStride of SequenceConvOp "
C
chengduoZH 已提交
175
                 "represents the stride length of convolution kernel. "
C
chengduoZH 已提交
176
                 "Currently, SequenceConvOp only supports"
C
chengduoZH 已提交
177
                 "contextStride=1.")
C
chengduoZH 已提交
178
        .SetDefault(1)
C
chengduoZH 已提交
179
        .GreaterThan(0);
C
chengduoZH 已提交
180 181

    AddComment(R"DOC(
182 183 184 185 186 187 188 189 190 191
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 已提交
192 193 194 195
    )DOC");
  }
};

H
hong 已提交
196 197
template <typename T>
class SequenceConvGradOpMaker : public framework::SingleGradOpMaker<T> {
198
 public:
H
hong 已提交
199
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
200 201

 protected:
202
  void Apply(GradOpPtr<T> op) const override {
203
    op->SetType("sequence_conv_grad");
H
hong 已提交
204
    op->SetAttrMap(this->Attrs());
205

H
hong 已提交
206
    if (op->HasAttr("paddingTrainable") &&
207
        BOOST_GET_CONST(bool, op->GetAttr("paddingTrainable")) &&
H
hong 已提交
208 209
        this->HasInput("PaddingData")) {
      op->SetInput("PaddingData", this->Input("PaddingData"));
210
      op->SetOutput(framework::GradVarName("PaddingData"),
H
hong 已提交
211
                    this->InputGrad("PaddingData"));
212 213
    }

H
hong 已提交
214 215 216
    op->SetInput("X", this->Input("X"));
    op->SetInput("Filter", this->Input("Filter"));
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
217

H
hong 已提交
218 219
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetOutput(framework::GradVarName("Filter"), this->InputGrad("Filter"));
220 221 222 223 224 225 226 227
  }
};

class SequenceConvGradNoNeedBufferVarsInference
    : public framework::NoNeedBufferVarsInference {
 public:
  using framework::NoNeedBufferVarsInference::NoNeedBufferVarsInference;

228 229 230
  const std::unordered_set<std::string> &operator()(
      const framework::InferNoNeedBufferVarsContext &ctx) const final {
    static const std::unordered_set<std::string> kPaddingData({"PaddingData"});
231
    if (!BOOST_GET_CONST(bool, ctx.GetAttr("paddingTrainable"))) {
232
      return kPaddingData;
233
    } else {
234
      return Empty();
235 236 237 238
    }
  }
};

C
chengduoZH 已提交
239 240 241 242
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
Y
Yang Yang 已提交
243
REGISTER_OPERATOR(sequence_conv, ops::SequenceConvOp, ops::SequenceConvOpMaker,
H
hong 已提交
244 245
                  ops::SequenceConvGradOpMaker<paddle::framework::OpDesc>,
                  ops::SequenceConvGradOpMaker<paddle::imperative::OpBase>);
246 247 248

REGISTER_OPERATOR(sequence_conv_grad, ops::SequenceConvGradOp,
                  ops::SequenceConvGradNoNeedBufferVarsInference);
C
chengduoZH 已提交
249 250

REGISTER_OP_CPU_KERNEL(
Q
QI JUN 已提交
251 252 253
    sequence_conv,
    ops::SequenceConvKernel<paddle::platform::CPUDeviceContext, float>,
    ops::SequenceConvKernel<paddle::platform::CPUDeviceContext, double>);
C
chengduoZH 已提交
254
REGISTER_OP_CPU_KERNEL(
C
chengduoZH 已提交
255
    sequence_conv_grad,
Q
QI JUN 已提交
256 257
    ops::SequenceConvGradKernel<paddle::platform::CPUDeviceContext, float>,
    ops::SequenceConvGradKernel<paddle::platform::CPUDeviceContext, double>);