lod_rank_table.cc 2.2 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Y
Yu Yang 已提交
2

L
Luo Tao 已提交
3 4 5
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
Y
Yu Yang 已提交
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
Y
Yu Yang 已提交
8

L
Luo Tao 已提交
9 10 11 12 13
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
Yu Yang 已提交
14

Y
Yi Wang 已提交
15
#include "paddle/fluid/framework/lod_rank_table.h"
Y
Yu Yang 已提交
16

17 18 19
#include "glog/logging.h"
#include "paddle/fluid/platform/enforce.h"

Y
Yu Yang 已提交
20 21 22 23 24
namespace paddle {
namespace framework {
void LoDRankTable::Reset(const LoD& lod, size_t level) {
  this->coarse_lod_.clear();
  this->items_.clear();
25 26 27 28 29
  PADDLE_ENFORCE_LT(
      level, lod.size(),
      platform::errors::InvalidArgument(
          "Cannot reset LoD since the level %d is less than lod size %d.",
          level, lod.size()));
Y
Yu Yang 已提交
30 31 32 33 34 35 36 37 38
  coarse_lod_.reserve(level);
  for (size_t i = 0; i < level; ++i) {
    coarse_lod_.push_back(lod[i]);
  }
  auto& vec = lod[level];
  for (size_t i = 0; i < vec.size() - 1; ++i) {
    TableItem item;
    item.index = i;
    item.length = vec[i + 1] - vec[i];
M
minqiyang 已提交
39
    VLOG(10) << "Add item to rank table " << item.index << " " << item.length;
Y
Yu Yang 已提交
40 41
    items_.emplace_back(item);
  }
42 43 44 45 46 47 48 49 50
  // NOTE(yuyang18):
  //
  // The time complexity of stable_sort is O(N*log(N)) if additional memory is
  // available. It is easy to debug and unit test when using `stable_sort`
  // instead of `sort`. Also, the items of a rank table will not be too large.
  std::stable_sort(items_.begin(), items_.end(),
                   [](const TableItem& a, const TableItem& b) {
                     return a.length > b.length;
                   });
Y
Yu Yang 已提交
51 52 53
}

}  // namespace framework
Y
Yu Yang 已提交
54 55 56 57 58 59 60 61 62

std::ostream& operator<<(std::ostream& out,
                         const framework::LoDRankTable& table) {
  out << "NumOfSequence " << table.items().size() << "\n";
  for (auto& each_item : table.items()) {
    out << "\tSeq #" << each_item.index << ", Len=" << each_item.length << "\n";
  }
  return out;
}
Y
Yu Yang 已提交
63
}  // namespace paddle