sequence2batch.h 6.2 KB
Newer Older
D
dangqingqing 已提交
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. */

15
#pragma once
16
#include "paddle/framework/eigen.h"
17 18 19 20
#include "paddle/framework/lod_tensor.h"
#include "paddle/framework/tensor.h"
#include "paddle/platform/device_context.h"

D
dangqingqing 已提交
21 22 23 24
namespace paddle {
namespace operators {
namespace math {

25 26 27 28
template <typename T, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenMatrix = framework::EigenMatrix<T, MajorType, IndexType>;

Q
QI JUN 已提交
29
template <typename DeviceContext, typename T>
D
dangqingqing 已提交
30 31 32 33 34 35 36
class CopyMatrixRowsFunctor {
 public:
  // If is_src_index is true,
  // copy the indexed rows of input src to the output dst.
  // If is_src_index is false,
  // copy the input src to the indexed rows of output dst.
  // The indexed rows are based on the input index.
Q
QI JUN 已提交
37
  void operator()(const DeviceContext& context, const framework::Tensor& src,
D
dzhwinter 已提交
38
                  framework::Vector<size_t> index_lod, framework::Tensor& dst,
Q
QI JUN 已提交
39
                  bool is_src_index);
D
dangqingqing 已提交
40 41
};

Q
QI JUN 已提交
42
template <typename DeviceContext, typename T>
D
dangqingqing 已提交
43
class LoDTensor2BatchFunctor {
Y
Yu Yang 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57
  // Calculate the length of each sequence and
  // sort sequence index by the length.
  // example:  sequences = {s0, s1, s2}
  //           s0: 0 0 0 0, s1: 1 1 1 1 1, s2: 2 2 2
  //           seq_info[3] = {(4, 5, 1), (0, 4, 0), (9, 3, 2)}
  //
  struct SeqInfo {
    SeqInfo(int start, int length, int seq_idx)
        : start(start), length(length), seq_idx(seq_idx) {}
    int start;
    int length;
    int seq_idx;
  };

D
dangqingqing 已提交
58
 public:
Q
QI JUN 已提交
59
  void operator()(const DeviceContext& context,
D
dangqingqing 已提交
60
                  const framework::LoDTensor& lod_tensor,
D
dangqingqing 已提交
61 62 63 64
                  framework::LoDTensor& batch, bool is_cal_batch_lod,
                  bool is_reverse = false) const {
    if (!is_cal_batch_lod) {
      auto lods = batch.lod();
D
dangqingqing 已提交
65
      PADDLE_ENFORCE_GT(lods.size(), 2UL);
D
dangqingqing 已提交
66 67
      PADDLE_ENFORCE_EQ(lods[1].size(),
                        static_cast<size_t>(lod_tensor.dims()[0]));
Q
QI JUN 已提交
68
      CopyMatrixRowsFunctor<DeviceContext, T> to_batch;
D
dzhwinter 已提交
69
      to_batch(context, lod_tensor, lods[1], batch, true);
D
dangqingqing 已提交
70 71 72
      return;
    }

73
    auto lods = lod_tensor.lod();
D
dangqingqing 已提交
74
    auto lod = lods[0];
75
    PADDLE_ENFORCE_EQ(lods.size(), 1UL, "Only support one level sequence now.");
D
dangqingqing 已提交
76 77

    std::vector<SeqInfo> seq_info;
78
    for (size_t seq_id = 0; seq_id < lod.size() - 1; ++seq_id) {
D
dangqingqing 已提交
79 80 81 82 83 84 85
      int length = lod[seq_id + 1] - lod[seq_id];
      seq_info.emplace_back(lod[seq_id], length, seq_id);
    }

    std::sort(seq_info.begin(), seq_info.end(),
              [](SeqInfo a, SeqInfo b) { return a.length > b.length; });

86
    // Calculate the start position of each batch.
D
dangqingqing 已提交
87 88 89 90 91 92
    // example:  sequences = {s0, s1, s2}
    //           s0: 0 0 0 0, s1: 1 1 1 1 1, s2: 2 2 2
    //           num_batch = 5,
    //           batchIndex = {b0, b1, b2, b3, b4}
    //           b0: 1 0 2, b1: 1 0 2, b2: 1 0 2, b3: 1 0, b4: 1
    //           batch_start_positions[6] = {0, 3, 6, 9, 11, 12}
Y
Yu Yang 已提交
93 94 95 96
    //              batch_start_positions[0] = len(b0)
    //              batch_start_positions[1] = len(b0) + len(b1)
    //              batch_start_positions[2] = len(b0) + len(b1) + len(b2)
    //              ...
D
dangqingqing 已提交
97 98 99 100 101
    //           seq2batch_idx[12] = {4, 0, 9,
    //                                5, 1, 10,
    //                                6, 2, 11,
    //                                7, 3,
    //                                8}
102 103 104 105 106
    //           seq_order = {1, 0, 2}, the sort order.
    //               where 1 is the second sequence,
    //                     0 is the first sequence,
    //                     2 is the third sequence.
    // The num_batch represents batch size after rearranging the
D
dangqingqing 已提交
107
    // input LodTensor. It is also the maximum length of input sequence.
108 109

    paddle::framework::LoD batch_lods;
Y
Yu Yang 已提交
110 111
    batch_lods.emplace_back(std::vector<size_t>{0});
    batch_lods.emplace_back(std::vector<size_t>{0});
112
    batch_lods.emplace_back(std::vector<size_t>{0});
113

D
dangqingqing 已提交
114
    // batch_lods[0] is the start positions for batch LoDTensor
Y
Yu Yang 已提交
115 116
    int num_batch = seq_info[0].length;
    batch_lods[0].resize(static_cast<size_t>(num_batch + 1));
D
dangqingqing 已提交
117
    // batch_lods[1] is the raw index in the input LoDTensor
D
dangqingqing 已提交
118
    batch_lods[1].resize(static_cast<size_t>(lod_tensor.dims()[0]));
119 120
    // batch_lods[2] is the sort order for the input LoDTensor.
    batch_lods[2].resize(seq_info.size());
D
dangqingqing 已提交
121

122 123
    size_t* batch_starts = batch_lods[0].data();
    size_t* seq2batch_idx = batch_lods[1].data();
D
dangqingqing 已提交
124
    batch_starts[0] = 0;
D
dangqingqing 已提交
125
    for (int n = 0; n < num_batch; n++) {
Y
Yu Yang 已提交
126
      auto batch_id = static_cast<int>(batch_starts[n]);
D
dangqingqing 已提交
127
      for (size_t i = 0; i < seq_info.size(); ++i) {
D
dangqingqing 已提交
128
        int seq_len = seq_info[i].length;
D
dangqingqing 已提交
129 130
        int start = seq_info[i].start;
        if (n < seq_len) {
D
dangqingqing 已提交
131 132
          seq2batch_idx[batch_id] =
              is_reverse ? start + seq_len - 1 - n : start + n;
D
dangqingqing 已提交
133 134 135 136 137
          batch_id++;
        } else {
          break;
        }
      }
Y
Yu Yang 已提交
138
      batch_starts[n + 1] = static_cast<size_t>(batch_id);
D
dangqingqing 已提交
139
    }
140 141 142 143
    size_t* seq_order = batch_lods[2].data();
    for (size_t i = 0; i < seq_info.size(); ++i) {
      seq_order[i] = seq_info[i].seq_idx;
    }
144
    batch.set_lod(batch_lods);
D
dangqingqing 已提交
145

Q
QI JUN 已提交
146
    CopyMatrixRowsFunctor<DeviceContext, T> to_batch;
D
dzhwinter 已提交
147
    to_batch(context, lod_tensor, batch_lods[1], batch, true);
D
dangqingqing 已提交
148
  }
D
dangqingqing 已提交
149
};
D
dangqingqing 已提交
150

Q
QI JUN 已提交
151
template <typename DeviceContext, typename T>
152
class Batch2LoDTensorFunctor {
D
dangqingqing 已提交
153
 public:
Q
QI JUN 已提交
154
  void operator()(const DeviceContext& context,
D
dangqingqing 已提交
155
                  const framework::LoDTensor& batch,
156 157
                  framework::LoDTensor& lod_tensor) const {
    auto in_lod = batch.lod();
D
dangqingqing 已提交
158
    PADDLE_ENFORCE_GT(in_lod.size(), 2UL);
159 160
    PADDLE_ENFORCE_EQ(in_lod[1].size(),
                      static_cast<size_t>(lod_tensor.dims()[0]));
Q
QI JUN 已提交
161
    CopyMatrixRowsFunctor<DeviceContext, T> to_seq;
D
dzhwinter 已提交
162
    to_seq(context, batch, in_lod[1], lod_tensor, false);
163
  }
D
dangqingqing 已提交
164
};
D
dangqingqing 已提交
165 166 167 168

}  // namespace math
}  // namespace operators
}  // namespace paddle