lod_tensor.cc 7.4 KB
Newer Older
1 2
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
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. */
14 15

#include "paddle/framework/lod_tensor.h"
武毅 已提交
16 17
#include "paddle/framework/data_type.h"
#include "paddle/framework/framework.pb.h"
18 19 20 21 22 23 24 25

#include "paddle/memory/memcpy.h"
#include "paddle/memory/memory.h"

#include <stdint.h>
#include <string.h>
#include <algorithm>
#include <iterator>
26 27 28 29 30 31

#include <glog/logging.h>

namespace paddle {
namespace framework {

武毅 已提交
32
std::ostream &operator<<(std::ostream &os, const LoD &lod) {
33
  os << "{";
武毅 已提交
34
  for (auto &v : lod) {
35
    os << "{";
武毅 已提交
36
    for (auto &i : v) {
37 38 39 40 41 42 43 44 45
      os << i << ",";
    }
    os << "}";
  }
  os << "}";

  return os;
}

武毅 已提交
46
LoD SliceLevels(const LoD &in, size_t level_begin, size_t level_end) {
47
  LoD new_lod;
48 49
  new_lod.reserve(level_end - level_begin);
  for (size_t i = level_begin; i < level_end; i++) {
Q
qijun 已提交
50
    new_lod.emplace_back(in.at(i));
51
  }
52 53 54
  // transform the lowest level to absolute offset.
  LoD abs_offset_lod = ToAbsOffset(in);
  new_lod.back() = abs_offset_lod[level_end - 1];
55
  return new_lod;
56 57
}

武毅 已提交
58
LoD SliceInLevel(const LoD &in, size_t level, size_t elem_begin,
Q
qijun 已提交
59
                 size_t elem_end) {
60 61 62 63 64 65 66 67 68
  PADDLE_ENFORCE_LT(level, in.size());
  PADDLE_ENFORCE_LT(elem_end, in[level].size());

  LoD res;
  res.resize(in.size() - level);
  // copy the first level
  res[0].assign(in[level].begin() + elem_begin,
                in[level].begin() + elem_end + 1);
  for (size_t lvl = 1; lvl < res.size(); lvl++) {
武毅 已提交
69 70 71
    const auto &in_level = in[level + lvl];
    const auto &above_level = res[lvl - 1];
    auto &out_level = res[lvl];
72 73
    out_level.assign(in_level.begin() + above_level.front(),
                     in_level.begin() + above_level.back() + 1);
74
  }
75 76 77 78
  for (size_t lvl = 0; lvl < res.size(); lvl++) {
    // to make the first offset equals 0, all the elements minus the first
    // element
    size_t front = res[lvl].front();
武毅 已提交
79
    for (auto &ele : res[lvl]) {
80 81 82 83 84 85
      ele -= front;
    }
  }
  return res;
}

武毅 已提交
86
LoD ToAbsOffset(const LoD &in) {
87 88 89 90
  // the lowest level stores relative offsets
  if (in.empty() || in.size() == 1) return in;
  LoD result = in;
  for (int level = result.size() - 2; level >= 0; level--) {
武毅 已提交
91
    for (auto &ele : result[level]) {
92 93 94 95
      ele = result[level + 1][ele];
    }
  }
  return result;
96 97
}

武毅 已提交
98
bool operator==(const LoD &a, const LoD &b) {
99 100 101 102 103
  if (a.size() != b.size()) {
    return false;
  }

  for (size_t i = 0; i < a.size(); i++) {
武毅 已提交
104 105
    const auto &a_level = a[i];
    const auto &b_level = b[i];
106 107 108 109 110 111 112 113 114 115
    if (a_level.size() != b_level.size()) {
      return false;
    }
    for (size_t j = 0; j < a_level.size(); j++) {
      if (a_level[j] != b_level[j]) {
        return false;
      }
    }
  }
  return true;
116 117
}

118 119 120
size_t LoDTensor::NumElements(size_t level, size_t idx) const {
  PADDLE_ENFORCE_LT(level, NumLevels());
  PADDLE_ENFORCE_LT(idx, NumElements(level));
121
  return lod_[level][idx + 1] - lod_[level][idx];
122 123
}

124 125 126 127 128 129 130 131 132
size_t LoDTensor::NumInstancesInElement(size_t level, size_t idx) const {
  PADDLE_ENFORCE_LT(level, NumLevels());
  PADDLE_ENFORCE_LT(idx, NumElements(level));
  auto abs_lod = ToAbsOffset(lod());
  size_t begin = abs_lod[level][idx];
  size_t end = abs_lod[level][idx + 1];
  return end - begin;
}

133
void LoDTensor::ShrinkLevels(size_t level_begin, size_t level_end) {
Q
qijun 已提交
134 135 136 137
  auto new_lod = framework::SliceLevels(lod_, level_begin, level_end);
  lod_ = new_lod;
}

138 139 140 141 142
void LoDTensor::ShrinkInLevel(size_t level, size_t elem_begin,
                              size_t elem_end) {
  PADDLE_ENFORCE_LT(level, NumLevels());
  PADDLE_ENFORCE_LT(elem_begin, NumElements(level));
  PADDLE_ENFORCE_LT(elem_end, NumElements(level) + 1);
Q
qijun 已提交
143

144
  auto abs_lod = framework::ToAbsOffset(lod());
Q
qijun 已提交
145 146
  auto new_lod = framework::SliceInLevel(lod_, level, elem_begin, elem_end);
  lod_ = new_lod;
147 148 149 150 151 152

  // slice the underlying tensor
  size_t begin = abs_lod[level][elem_begin];
  size_t end = abs_lod[level][elem_end];
  PADDLE_ENFORCE_LT(begin, end, "Cannot shrink, the result tensor is empty.");
  ShareDataWith(Slice(begin, end));
Q
qijun 已提交
153
}
154

155
using LoDAndOffset = std::pair<LoD, std::pair<size_t, size_t>>;
武毅 已提交
156
LoDAndOffset GetSubLoDAndAbsoluteOffset(const LoD &lod, size_t start_idx,
157 158 159 160 161 162
                                        size_t end_idx, size_t start_level) {
  LoD sub_lod;

  for (size_t level_idx = start_level; level_idx < lod.size(); ++level_idx) {
    PADDLE_ENFORCE_LE(start_idx, end_idx);
    PADDLE_ENFORCE_LT(end_idx, lod[level_idx].size());
163 164 165 166
    std::vector<size_t> level_lens;
    for (size_t i = start_idx; i < end_idx; ++i) {
      level_lens.push_back(lod[level_idx][i + 1] - lod[level_idx][i]);
    }
167
    sub_lod.emplace_back(level_lens);
168 169 170
    start_idx = lod[level_idx][start_idx];
    end_idx = lod[level_idx][end_idx];
  }
171 172

  return LoDAndOffset{sub_lod, {start_idx, end_idx}};
173 174
}

武毅 已提交
175
void AppendLoD(LoD *lod, const LoD &lod_length) {
176 177
  PADDLE_ENFORCE(
      lod->empty() || lod->size() == lod_length.size(),
178
      "The lod_length should has the same size with the appended lod.");
179 180 181
  if (lod->empty()) {
    *lod = LoD(lod_length.size(), std::vector<size_t>({0}));
  }
182
  for (size_t i = 0; i < lod->size(); ++i) {
武毅 已提交
183
    auto &level = (*lod)[i];
184 185 186 187 188 189
    for (size_t len : lod_length[i]) {
      level.push_back(level.back() + len);
    }
  }
}

武毅 已提交
190 191
void SerializeToStream(std::ostream &os, const LoDTensor &tensor,
                       const platform::DeviceContext &dev_ctx) {
192
  {  // the 1st field, uint32_t version for LoDTensor
武毅 已提交
193 194 195
    constexpr uint32_t version = 0;
    os.write(reinterpret_cast<const char *>(&version), sizeof(version));
  }
196 197 198 199 200 201
  {
    // the 2st field, LoD information
    // uint64_t lod_level
    // uint64_t lod_level_1 size in byte.
    // int*     lod_level_1 data
    // ...
武毅 已提交
202 203 204 205 206 207 208 209 210 211 212
    auto lod = tensor.lod();
    uint64_t size = lod.size();
    os.write(reinterpret_cast<const char *>(&size), sizeof(size));

    for (auto &each : lod) {
      size = each.size() * sizeof(framework::LoD::value_type::value_type);
      os.write(reinterpret_cast<const char *>(&size), sizeof(size));
      os.write(reinterpret_cast<const char *>(each.data()),
               static_cast<std::streamsize>(size));
    }
  }
213 214
  // the 3st field, Tensor
  SerializeToStream(os, static_cast<Tensor>(tensor), dev_ctx);
武毅 已提交
215 216 217
}

void DeserializeFromStream(std::istream &is, LoDTensor *tensor) {
218 219 220 221 222 223 224 225
  {
    // the 1st field, unit32_t version for SelectedRows
    uint32_t version;
    is.read(reinterpret_cast<char *>(&version), sizeof(version));
    PADDLE_ENFORCE_EQ(version, 0U, "Only version 0 is supported");
  }
  {
    // the 2st field, LoD information
武毅 已提交
226 227 228 229 230 231 232 233 234 235 236 237 238
    uint64_t lod_level;
    is.read(reinterpret_cast<char *>(&lod_level), sizeof(lod_level));
    auto &lod = *tensor->mutable_lod();
    lod.resize(lod_level);
    for (uint64_t i = 0; i < lod_level; ++i) {
      uint64_t size;
      is.read(reinterpret_cast<char *>(&size), sizeof(size));
      std::vector<size_t> tmp(size / sizeof(size_t));
      is.read(reinterpret_cast<char *>(tmp.data()),
              static_cast<std::streamsize>(size));
      lod[i] = tmp;
    }
  }
239 240
  // the 3st filed, Tensor
  DeserializeFromStream(is, static_cast<Tensor *>(tensor));
武毅 已提交
241 242
}

243 244
}  // namespace framework
}  // namespace paddle