lod_tensor.cpp 8.7 KB
Newer Older
W
wangliu 已提交
1
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
朔-望's avatar
朔-望 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15

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. */

#include "lod_tensor.h"
L
liuruilong 已提交
16 17
#include <stdint.h>
#include <string.h>
朔-望's avatar
朔-望 已提交
18 19
#include <algorithm>
#include <iterator>
朔-望's avatar
朔-望 已提交
20 21

namespace paddle_mobile {
朔-望's avatar
朔-望 已提交
22 23 24
namespace framework {

std::ostream &operator<<(std::ostream &os, const LoD &lod) {
25 26
  os << "{";
  for (auto &v : lod) {
朔-望's avatar
朔-望 已提交
27
    os << "{";
28 29 30 31 32 33 34 35
    bool is_first = true;
    for (auto &i : v) {
      if (is_first) {
        os << i;
        is_first = false;
      } else {
        os << ", " << i;
      }
朔-望's avatar
朔-望 已提交
36 37
    }
    os << "}";
38 39
  }
  os << "}";
朔-望's avatar
朔-望 已提交
40

41
  return os;
朔-望's avatar
朔-望 已提交
42 43 44
}

std::ostream &operator<<(std::ostream &os, const LoDTensor &t) {
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
  //  PADDLE_ENFORCE(t.type().hash_code() ==
  //  typeid(float).hash_code());

  //  if (!platform::is_cpu_place(t.place())) {
  //    LoDTensor tt;
  //    framework::TensorCopy(t, platform::CPUPlace(), &tt);
  //    platform::DeviceContextPool &pool =
  //    platform::DeviceContextPool::Instance(); auto &dev_ctx =
  //    *pool.Get(t.place()); dev_ctx.Wait();
  //
  //    os << tt;
  //    return os;
  //  }

  os << "dim: " << t.dims() << "\n";
  os << "lod: " << t.lod() << "\n";

  // only print first ten elements
  int64_t size = t.numel() < 10 ? t.numel() : 10;
  for (int64_t i = 0; i < size; ++i) {
    os << t.data<float>()[i] << " ";
  }

  return os;
朔-望's avatar
朔-望 已提交
69 70 71
}

std::string LoDToString(const LoD &lod) {
72 73 74
  std::ostringstream stream;
  stream << lod;
  return stream.str();
朔-望's avatar
朔-望 已提交
75 76 77 78
}

LoD SliceInLevel(const LoD &in, size_t level, size_t elem_begin,
                 size_t elem_end) {
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
  //  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++) {
    const auto &in_level = in[level + lvl];
    const auto &above_level = res[lvl - 1];
    auto &out_level = res[lvl];
    out_level.assign(in_level.begin() + above_level.front(),
                     in_level.begin() + above_level.back() + 1);
  }
  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();
    for (auto &ele : res[lvl]) {
      ele -= front;
朔-望's avatar
朔-望 已提交
101
    }
102 103
  }
  return res;
朔-望's avatar
朔-望 已提交
104 105 106
}

LoD ToAbsOffset(const LoD &in) {
107
  // the lowest level stores relative offsets
朔-望's avatar
朔-望 已提交
108
  if (in.empty() || in.size() == 1) return in;
109 110 111 112 113
  LoD result = in;
  for (auto level = static_cast<int>(in.size() - 2); level >= 0; level--) {
    for (size_t i = 0; i < in[level].size(); ++i) {
      size_t index = in[level][i];
      result[level][i] = result[level + 1][index];
朔-望's avatar
朔-望 已提交
114
    }
115 116
  }
  return result;
朔-望's avatar
朔-望 已提交
117 118 119
}

bool operator==(const LoD &a, const LoD &b) {
120 121 122 123 124 125 126 127 128
  if (a.size() != b.size()) {
    return false;
  }

  for (size_t i = 0; i < a.size(); i++) {
    const auto &a_level = a[i];
    const auto &b_level = b[i];
    if (a_level.size() != b_level.size()) {
      return false;
朔-望's avatar
朔-望 已提交
129
    }
130 131 132 133
    for (size_t j = 0; j < a_level.size(); j++) {
      if (a_level[j] != b_level[j]) {
        return false;
      }
朔-望's avatar
朔-望 已提交
134
    }
135 136
  }
  return true;
朔-望's avatar
朔-望 已提交
137 138 139
}

bool CheckLoD(const LoD &in, int tensor_height) {
朔-望's avatar
朔-望 已提交
140
  if (in.empty()) return true;
141 142 143
  for (const auto &level : in) {
    // check: there should be more than 2 offsets existing in each
    // level.
朔-望's avatar
朔-望 已提交
144
    if (level.size() < 2) return false;
145 146
    // check: the first offset(the begin offset) of each level
    // should be 0.
朔-望's avatar
朔-望 已提交
147
    if (level.front() != 0) return false;
148 149 150 151
    // check: all the offsets in a level should be ascending(no same
    // items
    // allows).
    if (!std::is_sorted(level.begin(), level.begin(), [](size_t a, size_t b) {
朔-望's avatar
朔-望 已提交
152
          if (a < b) return true;
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
          return false;
        })) {
      std::cout << "ascending error";
      return false;
    }
  }
  // check: the lowest level's last offset should equals
  // `tensor_height` if
  //        tensor_height>0.
  if (tensor_height > 0 && (size_t)tensor_height != in.back().back())
    return false;

  // check: the higher level's last offset should equals the lower
  // level's
  // size-1.
  // NOTE LoD store the levels from top to bottom, so the higher level
  // goes
  // first.
  for (size_t level = 0; level < in.size() - 1; level++) {
朔-望's avatar
朔-望 已提交
172
    if (in[level].back() != in[level + 1].size() - 1) return false;
173 174
  }
  return true;
朔-望's avatar
朔-望 已提交
175 176 177
}

bool CheckAbsLoD(const LoD &in, int tensor_height) {
朔-望's avatar
朔-望 已提交
178
  if (in.empty()) return true;
179 180 181 182 183
  for (const auto &level : in) {
    // check: all the offsets in a level should be ascending(no same
    // items
    // allows).
    if (!std::is_sorted(level.begin(), level.begin(), [](size_t a, size_t b) {
朔-望's avatar
朔-望 已提交
184
          if (a < b) return true;
185 186 187 188 189 190 191
          return false;
        })) {
      return false;
    }

    // check: there should be more than 2 offsets existing in each
    // level.
朔-望's avatar
朔-望 已提交
192
    if (level.size() < 2) return false;
193 194 195 196

    // check: the first offset of each level should be 0, and the
    // last should be
    // the same(the height of underlying tensor).
朔-望's avatar
朔-望 已提交
197
    if (level.front() != 0) return false;
198 199 200 201 202 203 204
    if (tensor_height < 0) {
      tensor_height = level.back();
    } else if ((size_t)tensor_height != level.back()) {
      return false;
    }
  }
  return true;
朔-望's avatar
朔-望 已提交
205 206 207 208 209 210
}

using LoDAndOffset = std::pair<LoD, std::pair<size_t, size_t>>;

LoDAndOffset GetSubLoDAndAbsoluteOffset(const LoD &lod, size_t start_idx,
                                        size_t end_idx, size_t start_level) {
211 212 213 214 215 216 217 218
  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());
    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]);
朔-望's avatar
朔-望 已提交
219
    }
220 221 222 223
    sub_lod.emplace_back(level_lens);
    start_idx = lod[level_idx][start_idx];
    end_idx = lod[level_idx][end_idx];
  }
朔-望's avatar
朔-望 已提交
224

225
  return LoDAndOffset{sub_lod, {start_idx, end_idx}};
朔-望's avatar
朔-望 已提交
226 227 228
}

void AppendLoD(LoD *lod, const LoD &lod_length) {
229 230 231 232 233 234
  //  PADDLE_ENFORCE(
  //      lod->empty() || lod->size() == lod_length.size(),
  //      "The lod_length should has the same size with the appended
  //      lod.");
  if (lod->empty()) {
    for (size_t i = 0; i < lod_length.size(); ++i) {
朔-望's avatar
朔-望 已提交
235
      lod->emplace_back(1, 0);  // size = 1, value = 0;
朔-望's avatar
朔-望 已提交
236
    }
237 238 239 240 241 242
    *lod = LoD(lod_length.size(), std::vector<size_t>({0}));
  }
  for (size_t i = 0; i < lod->size(); ++i) {
    auto &level = (*lod)[i];
    for (size_t len : lod_length[i]) {
      level.push_back(level.back() + len);
朔-望's avatar
朔-望 已提交
243
    }
244
  }
朔-望's avatar
朔-望 已提交
245 246 247
}

void SerializeToStream(std::ostream &os, const LoDTensor &tensor) {
朔-望's avatar
朔-望 已提交
248
  {  // the 1st field, uint32_t version for LoDTensor
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
    constexpr uint32_t version = 0;
    os.write(reinterpret_cast<const char *>(&version), sizeof(version));
  }
  {
    // the 2st field, LoD information
    // uint64_t lod_level
    // uint64_t lod_level_1 size in byte.
    // int*     lod_level_1 data
    // ...
    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));
朔-望's avatar
朔-望 已提交
267
    }
268 269 270
  }
  // the 3st field, Tensor
  TensorToStream(os, static_cast<Tensor>(tensor));
朔-望's avatar
朔-望 已提交
271 272 273
}

void DeserializeFromStream(std::istream &is, LoDTensor *tensor) {
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
  {
    // the 1st field, unit32_t version for LoDTensor
    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
    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;
朔-望's avatar
朔-望 已提交
294
    }
295 296 297
  }
  // the 3st filed, Tensor
  TensorFromStream(is, static_cast<Tensor *>(tensor));
朔-望's avatar
朔-望 已提交
298
}
299

朔-望's avatar
朔-望 已提交
300 301
}  // namespace framework
}  // namespace paddle_mobile