sequence2batch.h 7.5 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
D
dangqingqing 已提交
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. */

15
#pragma once
16 17
#include <algorithm>
#include <vector>
18

Y
Yi Wang 已提交
19 20 21
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/tensor.h"
#include "paddle/fluid/platform/device_context.h"
22
#include "paddle/phi/kernels/funcs/eigen/common.h"
23

F
Feiyu Chan 已提交
24 25
namespace phi {
namespace funcs {
D
dangqingqing 已提交
26

F
Feiyu Chan 已提交
27 28
template <typename T,
          int MajorType = Eigen::RowMajor,
29
          typename IndexType = Eigen::DenseIndex>
30
using EigenMatrix = phi::EigenMatrix<T, MajorType, IndexType>;
31

Q
QI JUN 已提交
32
template <typename DeviceContext, typename T>
D
dangqingqing 已提交
33 34 35 36 37 38 39
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.
F
Feiyu Chan 已提交
40
  void operator()(const DeviceContext& context,
41
                  const phi::DenseTensor& src,
F
Feiyu Chan 已提交
42
                  paddle::framework::Vector<size_t> index_lod,
43
                  phi::DenseTensor* dst,
Q
QI JUN 已提交
44
                  bool is_src_index);
D
dangqingqing 已提交
45 46
};

Q
QI JUN 已提交
47
template <typename DeviceContext, typename T>
D
dangqingqing 已提交
48
class LoDTensor2BatchFunctor {
Y
Yu Yang 已提交
49 50 51 52 53 54 55
  // 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 {
56
    SeqInfo(size_t start, size_t length, size_t seq_idx)
Y
Yu Yang 已提交
57
        : start(start), length(length), seq_idx(seq_idx) {}
58 59 60
    size_t start;
    size_t length;
    size_t seq_idx;
Y
Yu Yang 已提交
61 62
  };

D
dangqingqing 已提交
63
 public:
Q
QI JUN 已提交
64
  void operator()(const DeviceContext& context,
65 66
                  const phi::DenseTensor& lod_tensor,
                  phi::DenseTensor* batch,
F
Feiyu Chan 已提交
67
                  bool is_cal_batch_lod,
D
dangqingqing 已提交
68 69
                  bool is_reverse = false) const {
    if (!is_cal_batch_lod) {
70
      auto lods = batch->lod();
71
      PADDLE_ENFORCE_GT(
F
Feiyu Chan 已提交
72 73 74
          lods.size(),
          2UL,
          phi::errors::InvalidArgument(
75 76 77 78
              "The LoD of LoDTensor should inlcude at least 2-level "
              "sequence information, but got the LoD level is %lu. Please "
              "check the input value.",
              lods.size()));
79
      PADDLE_ENFORCE_EQ(
F
Feiyu Chan 已提交
80 81 82
          lods[1].size(),
          static_cast<size_t>(lod_tensor.dims()[0]),
          phi::errors::InvalidArgument(
83 84
              "The LoD information should be consistent with the dims, but got "
              "%lu != %lu. Please check the input value.",
F
Feiyu Chan 已提交
85 86
              lods[1].size(),
              static_cast<size_t>(lod_tensor.dims()[0])));
Q
QI JUN 已提交
87
      CopyMatrixRowsFunctor<DeviceContext, T> to_batch;
D
dzhwinter 已提交
88
      to_batch(context, lod_tensor, lods[1], batch, true);
D
dangqingqing 已提交
89 90 91
      return;
    }

92
    auto lods = lod_tensor.lod();
F
Feiyu Chan 已提交
93 94 95
    PADDLE_ENFORCE_EQ(lods.size(),
                      1UL,
                      phi::errors::InvalidArgument(
96 97 98
                          "Only support one level sequence now, but got the "
                          "LoD level is %lu. Please check the input value.",
                          lods.size()));
D
dangqingqing 已提交
99

100
    const auto& lod = lods[0];
101

D
dangqingqing 已提交
102
    std::vector<SeqInfo> seq_info;
103
    for (size_t seq_id = 0; seq_id < lod.size() - 1; ++seq_id) {
104
      size_t length = lod[seq_id + 1] - lod[seq_id];
D
dangqingqing 已提交
105 106 107
      seq_info.emplace_back(lod[seq_id], length, seq_id);
    }

F
Feiyu Chan 已提交
108 109 110
    std::sort(seq_info.begin(), seq_info.end(), [](SeqInfo a, SeqInfo b) {
      return a.length > b.length;
    });
D
dangqingqing 已提交
111

112
    // Calculate the start position of each batch.
D
dangqingqing 已提交
113 114
    // example:  sequences = {s0, s1, s2}
    //           s0: 0 0 0 0, s1: 1 1 1 1 1, s2: 2 2 2
T
tensor-tang 已提交
115
    //           max_seqlen = 5,
D
dangqingqing 已提交
116 117 118
    //           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 已提交
119 120 121 122
    //              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 已提交
123 124 125 126 127
    //           seq2batch_idx[12] = {4, 0, 9,
    //                                5, 1, 10,
    //                                6, 2, 11,
    //                                7, 3,
    //                                8}
128 129 130 131
    //           seq_order = {1, 0, 2}, the sort order.
    //               where 1 is the second sequence,
    //                     0 is the first sequence,
    //                     2 is the third sequence.
T
tensor-tang 已提交
132
    // The max_seqlen represents batch size after rearranging the
D
dangqingqing 已提交
133
    // input LodTensor. It is also the maximum length of input sequence.
134 135

    paddle::framework::LoD batch_lods;
Y
Yu Yang 已提交
136 137
    batch_lods.emplace_back(std::vector<size_t>{0});
    batch_lods.emplace_back(std::vector<size_t>{0});
138
    batch_lods.emplace_back(std::vector<size_t>{0});
139

D
dangqingqing 已提交
140
    // batch_lods[0] is the start positions for batch LoDTensor
141 142
    size_t max_seqlen = seq_info[0].length;
    batch_lods[0].resize(max_seqlen + 1);
D
dangqingqing 已提交
143
    // batch_lods[1] is the raw index in the input LoDTensor
D
dangqingqing 已提交
144
    batch_lods[1].resize(static_cast<size_t>(lod_tensor.dims()[0]));
145 146
    // batch_lods[2] is the sort order for the input LoDTensor.
    batch_lods[2].resize(seq_info.size());
D
dangqingqing 已提交
147

148 149
    size_t* batch_starts = batch_lods[0].data();
    size_t* seq2batch_idx = batch_lods[1].data();
D
dangqingqing 已提交
150
    batch_starts[0] = 0;
151 152
    for (size_t n = 0; n < max_seqlen; n++) {
      size_t batch_id = batch_starts[n];
D
dangqingqing 已提交
153
      for (size_t i = 0; i < seq_info.size(); ++i) {
154 155
        size_t seq_len = seq_info[i].length;
        size_t start = seq_info[i].start;
D
dangqingqing 已提交
156
        if (n < seq_len) {
D
dangqingqing 已提交
157 158
          seq2batch_idx[batch_id] =
              is_reverse ? start + seq_len - 1 - n : start + n;
D
dangqingqing 已提交
159 160 161 162 163
          batch_id++;
        } else {
          break;
        }
      }
164
      batch_starts[n + 1] = batch_id;
D
dangqingqing 已提交
165
    }
166 167 168 169
    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;
    }
170
    batch->set_lod(batch_lods);
D
dangqingqing 已提交
171

Q
QI JUN 已提交
172
    CopyMatrixRowsFunctor<DeviceContext, T> to_batch;
D
dzhwinter 已提交
173
    to_batch(context, lod_tensor, batch_lods[1], batch, true);
D
dangqingqing 已提交
174
  }
D
dangqingqing 已提交
175
};
D
dangqingqing 已提交
176

Q
QI JUN 已提交
177
template <typename DeviceContext, typename T>
178
class Batch2LoDTensorFunctor {
D
dangqingqing 已提交
179
 public:
Q
QI JUN 已提交
180
  void operator()(const DeviceContext& context,
181 182
                  const phi::DenseTensor& batch,
                  phi::DenseTensor* lod_tensor) const {
183
    auto in_lod = batch.lod();
184
    PADDLE_ENFORCE_GT(
F
Feiyu Chan 已提交
185 186 187
        in_lod.size(),
        2UL,
        phi::errors::InvalidArgument(
188 189 190 191
            "The LoD of LoDTensor should inlcude at least 2-level "
            "sequence information, but got the LoD level is %lu. Please check "
            "the input value.",
            in_lod.size()));
192
    PADDLE_ENFORCE_EQ(
F
Feiyu Chan 已提交
193 194 195
        in_lod[1].size(),
        static_cast<size_t>(lod_tensor->dims()[0]),
        phi::errors::InvalidArgument(
196 197
            "The LoD information should be consistent with the dims, but got "
            "%lu != %lu. Please check the input value.",
F
Feiyu Chan 已提交
198 199
            in_lod[1].size(),
            static_cast<size_t>(lod_tensor->dims()[0])));
Q
QI JUN 已提交
200
    CopyMatrixRowsFunctor<DeviceContext, T> to_seq;
D
dzhwinter 已提交
201
    to_seq(context, batch, in_lod[1], lod_tensor, false);
202
  }
D
dangqingqing 已提交
203
};
D
dangqingqing 已提交
204

F
Feiyu Chan 已提交
205 206
}  // namespace funcs
}  // namespace phi