sequence_concat_op.h 6.1 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 15

#pragma once
C
chengduoZH 已提交
16

17
#include <utility>
18
#include <vector>
19

20
#include "boost/optional.hpp"
Y
Yi Wang 已提交
21
#include "paddle/fluid/framework/op_registry.h"
C
chengduo 已提交
22
#include "paddle/fluid/operators/math/concat_and_split.h"
Y
Yancey1989 已提交
23 24 25 26

namespace paddle {
namespace operators {

C
chengduoZH 已提交
27 28 29 30 31 32 33 34 35 36 37 38
namespace detail {
template <typename Container>
inline framework::LoD ConcatLoD(const Container &xs,
                                std::vector<framework::Tensor> *xs_in_order) {
  std::vector<size_t> result;
  result.resize(xs[0].get().lod()[0].size());

  for (size_t i = 1; i < result.size(); ++i) {
    size_t sum = 0;
    for (size_t j = 0; j < xs.size(); ++j) {
      auto &x_lod = xs[j].get().lod()[0];
      const framework::Tensor &tensor = xs[j].get();
39 40 41
      if (x_lod[i - 1] < x_lod[i]) {
        xs_in_order->emplace_back(tensor.Slice(x_lod[i - 1], x_lod[i]));
      }
C
chengduoZH 已提交
42
      sum += x_lod[i];
43
    }
C
chengduoZH 已提交
44
    result[i] = sum;
45
  }
C
chengduoZH 已提交
46 47 48
  framework::LoD lod;
  lod.emplace_back(result);
  return lod;
Y
Yancey1989 已提交
49
}
50 51 52

template <typename T, typename... ARGS>
inline std::vector<std::reference_wrapper<T>> GetDataVectorSafely(
53
    const std::vector<T *> &vec, ARGS &&...args) {
54 55 56 57 58 59 60 61 62
  std::vector<std::reference_wrapper<T>> result;
  result.reserve(vec.size());
  for (auto *ptr : vec) {
    PADDLE_ENFORCE_NOT_NULL(ptr, platform::errors::InvalidArgument(
                                     "The input variable X contains nullptr."));
    result.emplace_back(*ptr);
  }
  return result;
}
C
chengduoZH 已提交
63
}  // namespace detail
Y
Yancey1989 已提交
64

Q
QI JUN 已提交
65
template <typename DeviceContext, typename T>
C
chengduoZH 已提交
66
class SeqConcatKernel : public framework::OpKernel<T> {
Y
Yancey1989 已提交
67
 public:
C
chengduoZH 已提交
68
  void Compute(const framework::ExecutionContext &context) const override {
69 70 71
    auto xs = detail::GetDataVectorSafely(
        context.MultiInput<framework::LoDTensor>("X"));
    auto &out = *context.Output<framework::LoDTensor>("Out");
C
chengduoZH 已提交
72 73 74 75

    size_t lod_size = 0;
    for (auto &x : xs) {
      if (lod_size == 0) {
76
        PADDLE_ENFORCE_EQ(x.get().lod().empty(), false,
77 78 79
                          platform::errors::NotFound(
                              "Input(X) Tensor of SequenceConcatOp does not "
                              "contain LoD information."));
C
chengduoZH 已提交
80 81
        lod_size = x.get().lod()[0].size();
      } else {
82 83 84 85 86 87
        PADDLE_ENFORCE_EQ(lod_size, x.get().lod()[0].size(),
                          platform::errors::InvalidArgument(
                              "The lod size of each input must be the same, "
                              "But the lod size of input we received is %d, "
                              "the first input is %d",
                              x.get().lod()[0].size(), lod_size));
Y
Yancey1989 已提交
88 89
      }
    }
90 91 92 93 94 95
    PADDLE_ENFORCE_NE(
        lod_size, 0,
        platform::errors::InvalidArgument(
            "Each input must have sequence lod information. But we "
            "received input lod size is %d",
            lod_size));
C
chengduoZH 已提交
96 97 98 99 100 101 102

    std::vector<framework::Tensor> x_in_order;
    out.set_lod(detail::ConcatLoD(xs, &x_in_order));
    out.mutable_data<T>(context.GetPlace());
    math::ConcatFunctor<DeviceContext, T> functor;
    functor(context.template device_context<DeviceContext>(), x_in_order, 0,
            &out);
Y
Yancey1989 已提交
103 104 105
  }
};

Q
QI JUN 已提交
106
template <typename DeviceContext, typename T>
C
chengduoZH 已提交
107
class SeqConcatGradKernel : public framework::OpKernel<T> {
Y
Yancey1989 已提交
108
 public:
C
chengduoZH 已提交
109 110 111 112
  void Compute(const framework::ExecutionContext &context) const override {
    auto xs = context.MultiInput<framework::LoDTensor>("X");
    auto dxs =
        context.MultiOutput<framework::LoDTensor>(framework::GradVarName("X"));
113 114 115 116 117 118
    PADDLE_ENFORCE_EQ(xs.size(), dxs.size(),
                      platform::errors::InvalidArgument(
                          "The rank of Input X and Output Grad X must be "
                          "same, But the rank of Input X we received is %d, "
                          "the rank of Output Grad X is %d",
                          xs.size(), dxs.size()));
C
chengduoZH 已提交
119 120 121 122 123
    for (size_t i = 0; i < dxs.size(); ++i) {
      if (dxs[i] != nullptr) {
        dxs[i]->set_lod(xs[i]->lod());
        dxs[i]->mutable_data<T>(context.GetPlace());
      }
Y
Yancey1989 已提交
124
    }
125

C
chengduoZH 已提交
126
    std::vector<framework::Tensor> sliced_x;
127
    std::vector<paddle::optional<framework::Tensor>> sliced_dx;
C
chengduoZH 已提交
128 129 130 131

    for (size_t i = 1; i < xs[0]->lod()[0].size(); ++i) {
      for (size_t j = 0; j < xs.size(); ++j) {
        const framework::LoDTensor *x = xs[j];
132 133
        framework::DDim x_dims = x->dims();

C
chengduoZH 已提交
134 135
        framework::LoDTensor *dx = dxs[j];
        auto &x_lod = x->lod()[0];
136
        if (x_lod[i - 1] == x_lod[i]) continue;
137 138 139 140 141 142 143 144 145 146 147

        auto prev_lod = x_lod[i - 1];
        auto next_lod = x_lod[i];

        x_dims[0] = next_lod - prev_lod;

        sliced_x.emplace_back();
        sliced_x.back().Resize(x_dims);

        if (dx) {
          sliced_dx.emplace_back(dx->Slice(prev_lod, next_lod));
C
chengduoZH 已提交
148
        } else {
149
          sliced_dx.emplace_back(paddle::none);
C
chengduoZH 已提交
150 151
        }
      }
152
    }
Y
Yancey1989 已提交
153

C
chengduoZH 已提交
154
    std::vector<const framework::Tensor *> sliced_x_ptr;
155
    sliced_x_ptr.reserve(sliced_x.size());
C
chengduoZH 已提交
156 157 158
    for (auto &x : sliced_x) {
      sliced_x_ptr.emplace_back(&x);
    }
Y
Yancey1989 已提交
159

160 161
    std::vector<framework::Tensor *> sliced_dx_ptr;
    sliced_dx_ptr.reserve(sliced_dx.size());
C
chengduoZH 已提交
162
    for (auto &dx : sliced_dx) {
163 164
      if (dx) {
        sliced_dx_ptr.emplace_back(&dx.get());
Y
Yancey1989 已提交
165 166
      }
    }
167 168

    math::SplitFunctor<DeviceContext, T> functor;
C
chengduoZH 已提交
169
    functor(context.template device_context<DeviceContext>(),
170
            GET_DATA_SAFELY(
C
chengduoZH 已提交
171
                context.Input<framework::Tensor>(framework::GradVarName("Out")),
172
                "Input", framework::GradVarName("Out"), "SeqConcatGrad"),
C
chengduoZH 已提交
173
            sliced_x_ptr, 0, &sliced_dx_ptr);
Y
Yancey1989 已提交
174 175 176 177 178
  }
};

}  // namespace operators
}  // namespace paddle