sequence_concat_op.cc 5.9 KB
Newer Older
C
chengduoZH 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
// 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.
Y
Yancey1989 已提交
14

W
Wu Yi 已提交
15
#include "paddle/fluid/operators/sequence_ops/sequence_concat_op.h"
16

17
#include <memory>
C
chengduoZH 已提交
18
#include <vector>
Y
Yancey1989 已提交
19 20 21 22

namespace paddle {
namespace operators {

C
chengduoZH 已提交
23
class SeqConcatOpMaker : public framework::OpProtoAndCheckerMaker {
Y
Yancey1989 已提交
24
 public:
C
chengduoZH 已提交
25 26 27 28 29 30 31 32 33 34 35
  void Make() override {
    AddInput("X", "The inputs of sequence concat op").AsDuplicable();
    AddOutput("Out", "The output of sequence concat op");
    AddComment(
        "Sequence Concat Op\n"
        "It will concat LoD tensors by its sequence information.\n"
        "For example:\n"
        "  LoD of X1 = [0, 3, 7]\n"
        "  LoD of X2 = [0, 7, 9]\n"
        "  Result LoD is [0, (3+7), (7+9)]\n"
        "            i.e.[0, 10, 16]\n");
Y
Yancey1989 已提交
36 37 38
  }
};

Z
Zeng Jinle 已提交
39
class SequenceConcatOp : public framework::OperatorWithKernel {
Y
Yancey1989 已提交
40
 public:
Z
Zeng Jinle 已提交
41 42 43 44
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
  void InferShape(framework::InferShapeContext *context) const override {
45
    PADDLE_ENFORCE_EQ(
46 47
        context->HasInputs("X"),
        true,
48 49 50
        platform::errors::NotFound("SequenceConcatOp Input(X) of Sequence "
                                   "Concat Op should not be null."));
    PADDLE_ENFORCE_EQ(
51 52
        context->HasOutput("Out"),
        true,
53 54
        platform::errors::NotFound("SequenceConcatOp Output(Out) of Sequence "
                                   "Concat Op should not be null."));
C
chengduoZH 已提交
55

56 57
    PADDLE_ENFORCE_GT(context->Inputs("X").size(),
                      1,
58 59 60 61 62
                      platform::errors::InvalidArgument(
                          "The number of SequenceConcatOp inputs should be "
                          "greater than 1. But "
                          "the number of inputs we received is %d",
                          context->Inputs("X").size()));
C
chengduoZH 已提交
63 64 65 66 67 68
    auto x_dims = context->GetInputsDim("X");
    int64_t batch_size = 0;
    int64_t feature_size = 0;
    std::vector<int64_t> out_dims;
    for (auto &x_dim : x_dims) {
      if (out_dims.empty()) {
69
        out_dims = phi::vectorize(x_dim);
C
chengduoZH 已提交
70
      }
C
chengduoZH 已提交
71
      batch_size += x_dim[0];
72 73 74 75 76
      PADDLE_ENFORCE_NE(
          x_dim[0],
          0,
          platform::errors::InvalidArgument(
              "The first dim of SequenceConcatOp inputs must not be 0."));
C
chengduoZH 已提交
77
      if (feature_size == 0) {
78
        feature_size = phi::product(x_dim) / x_dim[0];
C
chengduoZH 已提交
79 80
      } else {
        PADDLE_ENFORCE_EQ(
81 82
            feature_size,
            phi::product(x_dim) / x_dim[0],
83 84 85 86 87
            platform::errors::InvalidArgument(
                "Each input of SequenceConcatOp inputs must have same feature "
                "size, But "
                "the feature size we received is %d, the feature size of 1st "
                "input is %d",
88 89
                feature_size,
                phi::product(x_dim) / x_dim[0]));
C
chengduoZH 已提交
90
      }
C
chengduoZH 已提交
91 92 93 94 95
    }
    if (batch_size < 0) {
      batch_size = -1;  // Normalize batch size for compile time.
    }
    out_dims[0] = batch_size;
96
    context->SetOutputDim("Out", phi::make_ddim(out_dims));
C
chengduoZH 已提交
97 98 99
    if (!context->IsRuntime()) {  // Runtime LoD infershape will be computed
      // in Kernel.
      context->ShareLoD("X", "Out");
C
chengduoZH 已提交
100
    }
Y
Yancey1989 已提交
101 102 103
  }
};

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

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

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

  void InferShape(framework::InferShapeContext *context) const override {
C
chengduoZH 已提交
124 125
    context->SetOutputsDim(framework::GradVarName("X"),
                           context->GetInputsDim("X"));
Y
Yancey1989 已提交
126
  }
127 128

 protected:
129
  phi::KernelKey GetExpectedKernelType(
130
      const framework::ExecutionContext &ctx) const override {
131 132 133
    return phi::KernelKey(OperatorWithKernel::IndicateVarDataType(
                              ctx, framework::GradVarName("Out")),
                          ctx.GetPlace());
134
  }
Y
Yancey1989 已提交
135
};
136

137
DECLARE_NO_NEED_BUFFER_VARS_INFERER(SeqConcatGradNoNeedBufferVarsInferer, "X");
138

Y
Yancey1989 已提交
139 140 141
}  // namespace operators
}  // namespace paddle

C
chengduoZH 已提交
142 143
namespace op = paddle::operators;

144 145 146
REGISTER_OPERATOR(sequence_concat,
                  op::SequenceConcatOp,
                  op::SeqConcatOpMaker,
H
hong 已提交
147 148
                  op::SeqConcatGradOpMaker<paddle::framework::OpDesc>,
                  op::SeqConcatGradOpMaker<paddle::imperative::OpBase>);
L
Leo Chen 已提交
149 150 151 152 153
REGISTER_OP_CPU_KERNEL(sequence_concat,
                       op::SeqConcatKernel<phi::CPUContext, float>,
                       op::SeqConcatKernel<phi::CPUContext, double>,
                       op::SeqConcatKernel<phi::CPUContext, int>,
                       op::SeqConcatKernel<phi::CPUContext, int64_t>);
M
minqiyang 已提交
154

155 156
REGISTER_OPERATOR(sequence_concat_grad,
                  op::SeqConcatGradOp,
157
                  op::SeqConcatGradNoNeedBufferVarsInferer);
L
Leo Chen 已提交
158 159 160 161 162
REGISTER_OP_CPU_KERNEL(sequence_concat_grad,
                       op::SeqConcatGradKernel<phi::CPUContext, float>,
                       op::SeqConcatGradKernel<phi::CPUContext, double>,
                       op::SeqConcatGradKernel<phi::CPUContext, int>,
                       op::SeqConcatGradKernel<phi::CPUContext, int64_t>);