lod_tensor.cc 17.5 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
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
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

W
wanghuancoder 已提交
15
#include "paddle/fluid/framework/lod_tensor.h"
16

F
fengjiayi 已提交
17
#include <stdint.h>
18

X
refine  
Xin Pan 已提交
19
#include "paddle/fluid/framework/version.h"
20

W
wanghuancoder 已提交
21 22 23 24 25
namespace paddle {
namespace platform {
class DeviceContext;
}  // namespace platform
}  // namespace paddle
26

27 28 29
namespace paddle {
namespace framework {

武毅 已提交
30
std::ostream &operator<<(std::ostream &os, const LoD &lod) {
31
  os << "{";
武毅 已提交
32
  for (auto &v : lod) {
33
    os << "{";
L
Liu Yiqun 已提交
34
    bool is_first = true;
武毅 已提交
35
    for (auto &i : v) {
L
Liu Yiqun 已提交
36 37 38 39 40 41
      if (is_first) {
        os << i;
        is_first = false;
      } else {
        os << ", " << i;
      }
42 43 44 45 46 47 48 49
    }
    os << "}";
  }
  os << "}";

  return os;
}

Y
Yang Yang 已提交
50
std::ostream &operator<<(std::ostream &os, const LoDTensor &t) {
51 52 53 54
  if (t.lod().size() > 0) {
    os << "  - lod: " << t.lod() << "\n";
  }
  os << static_cast<Tensor>(t);
Y
Yang Yang 已提交
55 56 57
  return os;
}

Q
Qiao Longfei 已提交
58 59 60 61 62 63
std::string LoDToString(const LoD &lod) {
  std::ostringstream stream;
  stream << lod;
  return stream.str();
}

武毅 已提交
64
LoD SliceInLevel(const LoD &in, size_t level, size_t elem_begin,
Q
qijun 已提交
65
                 size_t elem_end) {
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
  PADDLE_ENFORCE_LT(level, in.size(),
                    platform::errors::InvalidArgument(
                        "The input LoDTensor's lod level should be less than "
                        "the LoD size, but received level is %d, LoD is %s.",
                        level, in));
  PADDLE_ENFORCE_LT(
      elem_begin, elem_end,
      platform::errors::InvalidArgument(
          "The index to start slicing should be less than the index to end "
          "slicing, but received start index is %d, end index is %d.",
          elem_begin, elem_end));
  PADDLE_ENFORCE_LT(
      elem_end, in[level].size(),
      platform::errors::InvalidArgument(
          "The index to end slicing should be less than the input LoD size, "
          "but received end index is %d, LoD size is %d.",
          elem_end, in[level].size()));
83 84 85 86 87 88 89

  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++) {
武毅 已提交
90 91 92
    const auto &in_level = in[level + lvl];
    const auto &above_level = res[lvl - 1];
    auto &out_level = res[lvl];
93 94
    out_level.assign(in_level.begin() + above_level.front(),
                     in_level.begin() + above_level.back() + 1);
95
  }
96 97 98 99
  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();
武毅 已提交
100
    for (auto &ele : res[lvl]) {
101 102 103 104 105 106
      ele -= front;
    }
  }
  return res;
}

武毅 已提交
107
LoD ToAbsOffset(const LoD &in) {
108 109 110
  // the lowest level stores relative offsets
  if (in.empty() || in.size() == 1) return in;
  LoD result = in;
Q
Qiao Longfei 已提交
111 112 113 114
  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];
115 116 117
    }
  }
  return result;
118 119
}

武毅 已提交
120
bool operator==(const LoD &a, const LoD &b) {
121 122 123 124 125
  if (a.size() != b.size()) {
    return false;
  }

  for (size_t i = 0; i < a.size(); i++) {
武毅 已提交
126 127
    const auto &a_level = a[i];
    const auto &b_level = b[i];
128 129 130 131 132 133 134 135 136 137
    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;
138 139
}

Y
Yan Chunwei 已提交
140 141 142 143 144 145 146
bool CheckLoD(const LoD &in, int tensor_height) {
  if (in.empty()) return true;
  for (const auto &level : in) {
    // check: there should be more than 2 offsets existing in each level.
    if (level.size() < 2) return false;
    // check: the first offset(the begin offset) of each level should be 0.
    if (level.front() != 0) return false;
147
    // check: all the offsets in a level should be non-descending
S
sneaxiy 已提交
148 149
    if (!std::is_sorted(level.begin(), level.end())) {
      return false;
Y
Yan Chunwei 已提交
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    }
  }
  // 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++) {
    if (in[level].back() != in[level + 1].size() - 1) return false;
  }
  return true;
}

bool CheckAbsLoD(const LoD &in, int tensor_height) {
  if (in.empty()) return true;
  for (const auto &level : in) {
    // check: all the offsets in a level should be ascending(no same items
171
    // allowed).
Y
Yan Chunwei 已提交
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
    if (!std::is_sorted(level.begin(), level.begin(), [](size_t a, size_t b) {
          if (a < b) return true;
          return false;
        })) {
      return false;
    }

    // check: there should be more than 2 offsets existing in each level.
    if (level.size() < 2) return false;

    // check: the first offset of each level should be 0, and the last should be
    // the same(the height of underlying tensor).
    if (level.front() != 0) return false;
    if (tensor_height < 0) {
      tensor_height = level.back();
    } else if ((size_t)tensor_height != level.back()) {
      return false;
    }
  }
  return true;
}

194
using LoDAndOffset = std::pair<LoD, std::pair<size_t, size_t>>;
武毅 已提交
195
LoDAndOffset GetSubLoDAndAbsoluteOffset(const LoD &lod, size_t start_idx,
196 197 198 199
                                        size_t end_idx, size_t start_level) {
  LoD sub_lod;

  for (size_t level_idx = start_level; level_idx < lod.size(); ++level_idx) {
200 201 202 203 204 205 206 207 208 209 210
    PADDLE_ENFORCE_LE(start_idx, end_idx,
                      platform::errors::InvalidArgument(
                          "The start index should be less than the end index, "
                          "but received start index is %d, end index is %d.",
                          start_idx, end_idx));
    PADDLE_ENFORCE_LT(
        end_idx, lod[level_idx].size(),
        platform::errors::InvalidArgument(
            "The end index should be less than the LoD level size, but "
            "received end index is %d, LoD level size is %d.",
            end_idx, lod[level_idx].size()));
211 212 213 214
    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]);
    }
215
    sub_lod.emplace_back(level_lens);
216 217 218
    start_idx = lod[level_idx][start_idx];
    end_idx = lod[level_idx][end_idx];
  }
219 220

  return LoDAndOffset{sub_lod, {start_idx, end_idx}};
221 222
}

武毅 已提交
223
void AppendLoD(LoD *lod, const LoD &lod_length) {
224 225
  PADDLE_ENFORCE(
      lod->empty() || lod->size() == lod_length.size(),
226 227 228 229
      platform::errors::InvalidArgument(
          "The input LoD length should be equal to the appended LoD size, but "
          "received input LoD length is %d, actual LoD size is %d.",
          lod_length, lod->size()));
230
  if (lod->empty()) {
Y
Yang Yu 已提交
231 232 233
    for (size_t i = 0; i < lod_length.size(); ++i) {
      lod->emplace_back(1, 0);  // size = 1, value = 0;
    }
234 235
    *lod = LoD(lod_length.size(), std::vector<size_t>({0}));
  }
236
  for (size_t i = 0; i < lod->size(); ++i) {
武毅 已提交
237
    auto &level = (*lod)[i];
238 239 240 241 242 243
    for (size_t len : lod_length[i]) {
      level.push_back(level.back() + len);
    }
  }
}

武毅 已提交
244 245
void SerializeToStream(std::ostream &os, const LoDTensor &tensor,
                       const platform::DeviceContext &dev_ctx) {
246
  {  // the 1st field, uint32_t version for LoDTensor
X
refine  
Xin Pan 已提交
247 248
    os.write(reinterpret_cast<const char *>(&kCurTensorVersion),
             sizeof(kCurTensorVersion));
武毅 已提交
249
  }
250 251 252 253 254 255
  {
    // the 2st field, LoD information
    // uint64_t lod_level
    // uint64_t lod_level_1 size in byte.
    // int*     lod_level_1 data
    // ...
武毅 已提交
256 257 258 259 260 261 262 263 264 265 266
    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));
    }
  }
267
  // the 3st field, Tensor
Y
Yi Wang 已提交
268
  TensorToStream(os, static_cast<Tensor>(tensor), dev_ctx);
武毅 已提交
269 270
}

271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
void SerializeToStream(std::ostream &os, const LoDTensor &tensor) {
  platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
  const platform::DeviceContext *dev_ctx;
  auto place = tensor.place();
  dev_ctx = pool.Get(place);
  SerializeToStream(os, tensor, *dev_ctx);
}

void DeserializeFromStream(std::ifstream &os, LoDTensor *tensor) {
  platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
  const platform::DeviceContext *dev_ctx;
  dev_ctx = pool.Get(platform::CPUPlace());
  DeserializeFromStream(os, tensor, *dev_ctx);
}

T
tangwei12 已提交
286 287 288 289 290 291 292 293 294 295
void DeserializeFromStream(std::istream &is, LoDTensor *tensor,
                           const platform::DeviceContext &dev_ctx,
                           const size_t &seek,
                           const std::vector<int64_t> &shape) {
  {
    // the 1st field, unit32_t version for LoDTensor
    uint32_t version;
    is.read(reinterpret_cast<char *>(&version), sizeof(version));
    PADDLE_ENFORCE_EQ(framework::IsTensorVersionSupported(version), true,
                      platform::errors::InvalidArgument(
296
                          "Tensor version %u is not supported.", version));
T
tangwei12 已提交
297 298 299
    PADDLE_ENFORCE_EQ(
        version, 0U,
        platform::errors::InvalidArgument(
300 301
            "Deserialize to tensor failed, maybe the loaded file is "
            "not a paddle model(expected file format: 0, but %u found).",
T
tangwei12 已提交
302 303 304 305 306 307 308 309 310 311 312 313 314
            version));
  }
  {
    // 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);
  }
  // the 3st filed, Tensor
  TensorFromStream(is, static_cast<Tensor *>(tensor), dev_ctx, seek, shape);
}

Y
Yancey 已提交
315 316
void DeserializeFromStream(std::istream &is, LoDTensor *tensor,
                           const platform::DeviceContext &dev_ctx) {
317
  {
Y
Yancey 已提交
318
    // the 1st field, unit32_t version for LoDTensor
319 320
    uint32_t version;
    is.read(reinterpret_cast<char *>(&version), sizeof(version));
T
tangwei12 已提交
321 322
    PADDLE_ENFORCE_EQ(framework::IsTensorVersionSupported(version), true,
                      platform::errors::InvalidArgument(
323
                          "Tensor version %u is not supported.", version));
T
tangwei12 已提交
324 325 326
    PADDLE_ENFORCE_EQ(
        version, 0U,
        platform::errors::InvalidArgument(
327 328
            "Deserialize to tensor failed, maybe the loaded file is "
            "not a paddle model(expected file format: 0, but %u found).",
T
tangwei12 已提交
329
            version));
武毅 已提交
330
  }
331 332
  {
    // the 2st field, LoD information
武毅 已提交
333 334 335 336 337 338 339 340 341 342 343 344 345
    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;
    }
  }
346
  // the 3st filed, Tensor
Y
Yi Wang 已提交
347
  TensorFromStream(is, static_cast<Tensor *>(tensor), dev_ctx);
武毅 已提交
348 349
}

Y
Yang Yang 已提交
350 351
std::vector<LoDTensor> LoDTensor::SplitLoDTensor(
    const std::vector<platform::Place> places) const {
352 353
  PADDLE_ENFORCE_GT(places.size(), 0,
                    platform::errors::InvalidArgument(
354
                        "Place number cannot be empty when splitting."));
Y
Yang Yang 已提交
355
  check_memory_size();
356 357
  size_t batch_size =
      lod().empty() ? static_cast<size_t>(dims()[0]) : lod()[0].size() - 1;
Y
Yu Yang 已提交
358

359
  // if batch_size is 0, just return #places.size() copys of empty
360
  // tensors.
361 362 363
  if (batch_size == 0) {
    std::vector<LoDTensor> empty_results;
    empty_results.reserve(places.size());
364 365 366 367 368 369 370
    for (size_t i = 0; i < places.size(); ++i) {
      LoDTensor dst;
      dst.Resize(dims());
      dst.mutable_data(places[i], type());
      if (!lod().empty()) {
        dst.set_lod(lod());
      }
371
      empty_results.emplace_back(std::move(dst));
372
    }
373
    return empty_results;
374 375
  }

376 377 378 379 380
  auto step_width = (batch_size + places.size() - 1) / places.size();
  auto result_size = (batch_size + step_width - 1) / step_width;
  std::vector<LoDTensor> results;
  results.reserve(result_size);

Y
Yu Yang 已提交
381
  for (size_t i = 0; i < result_size; ++i) {
382 383 384 385
    auto begin = i * step_width;
    auto end = std::min<size_t>((i + 1) * step_width, batch_size);
    PADDLE_ENFORCE_LT(begin, end,
                      platform::errors::InvalidArgument(
386 387 388
                          "The begin index must be less than the end index, "
                          "but received begin index is %d, end index is %d.",
                          begin, end));
Y
Yang Yang 已提交
389

390
    LoDTensor dst;
Y
Yang Yang 已提交
391 392
    if (lod().empty()) {
      auto src = Slice(begin, end);
Y
Yang Yang 已提交
393
      auto &dst_place = places[i];
Y
Yi Wang 已提交
394
      framework::TensorCopy(src, dst_place, &dst);
Y
Yang Yang 已提交
395 396 397 398 399
    } else {
      auto lod_and_offset = GetSubLoDAndAbsoluteOffset(lod(), begin, end, 0);

      auto &offset = lod_and_offset.second;
      auto src = Slice(offset.first, offset.second);
Y
Yang Yang 已提交
400
      auto &dst_place = places[i];
Y
Yi Wang 已提交
401
      framework::TensorCopy(src, dst_place, &dst);
Y
Yang Yang 已提交
402 403 404 405 406 407 408 409 410 411 412

      LoD my_lod;
      for (auto &l : lod_and_offset.first) {
        std::vector<size_t> v{0};
        for (auto &ll : l) {
          v.push_back(ll + v.back());
        }
        my_lod.emplace_back(v);
      }
      dst.set_lod(my_lod);
    }
413
    results.emplace_back(std::move(dst));
Y
Yang Yang 已提交
414 415
  }

Y
Yu Yang 已提交
416
  return results;
Y
Yang Yang 已提交
417 418
}

Y
Yang Yang 已提交
419
void LoDTensor::MergeLoDTensor(
420 421
    const std::vector<const LoDTensor *> &lod_tensors,
    platform::Place dst_place) {
422 423 424
  PADDLE_ENFORCE_EQ(lod_tensors.empty(), false,
                    platform::errors::InvalidArgument(
                        "The LoDTensors to be merged are empty."));
Y
Yang Yang 已提交
425

Y
Yang Yang 已提交
426
  framework::DDim new_dim = lod_tensors[0]->dims();
427
  proto::VarType::Type new_type = proto::VarType::FP32;
Y
Yang Yang 已提交
428
  framework::DataLayout new_layout = lod_tensors[0]->layout();
429 430 431 432 433 434 435 436 437
  for (auto *t : lod_tensors) {
    if (t->numel() && t->IsInitialized()) {
      new_dim = t->dims();
      new_type = t->type();
      new_layout = t->layout();
      break;
    }
  }

Y
Yang Yang 已提交
438
  LoD new_lod = lod_tensors[0]->lod();
439

Y
Yang Yang 已提交
440 441
  for (size_t i = 1; i < lod_tensors.size(); ++i) {
    auto *t = lod_tensors[i];
442
    if (t->numel() && t->IsInitialized()) {
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
      PADDLE_ENFORCE_EQ(
          new_type, t->type(),
          platform::errors::InvalidArgument(
              "LoDTensor data type does not match, expected type is %s, actual "
              "type is %s.",
              DataTypeToString(new_type), DataTypeToString(t->type())));
      PADDLE_ENFORCE_EQ(
          new_layout, t->layout(),
          platform::errors::InvalidArgument(
              "LoDTensor layout does not match, expected layout is %s, "
              "actual layout is %s.",
              DataLayoutToString(new_layout), DataLayoutToString(t->layout())));
      PADDLE_ENFORCE_EQ(
          framework::product(new_dim) / new_dim[0],
          framework::product(t->dims()) / t->dims()[0],
          platform::errors::InvalidArgument(
              "LoDTensor dimension does not match, all dimensions except the "
              "first dimension need to be equal,"
              "but expected dimension is %s, actual dimension is %s.",
              new_dim, t->dims()));
463 464
      new_dim[0] += t->dims()[0];
    }
Y
Yang Yang 已提交
465 466

    auto &lod = t->lod();
467 468 469 470 471
    PADDLE_ENFORCE_EQ(new_lod.size(), lod.size(),
                      platform::errors::InvalidArgument(
                          "The LoD information of LoDTensor does not match, "
                          "expected LoD is %s, actual LoD is %s.",
                          new_lod, lod));
Y
Yang Yang 已提交
472 473
    for (size_t j = 0; j < lod.size(); ++j) {
      auto &sub_lod = new_lod[j];
C
chengduo 已提交
474
      size_t offset = sub_lod.back();
Y
Yang Yang 已提交
475 476 477 478
      for (size_t k = 1; k < lod[j].size(); ++k) {
        sub_lod.push_back(lod[j][k] + offset);
      }
    }
Y
Yang Yang 已提交
479 480
  }
  Resize(new_dim);
481
  set_layout(new_layout);
Y
Yang Yang 已提交
482
  set_lod(new_lod);
483
  mutable_data(dst_place, new_type);
Y
Yang Yang 已提交
484

485
  int begin = 0;
Y
Yang Yang 已提交
486
  for (auto *src : lod_tensors) {
487
    int end = begin + src->dims()[0];
488 489 490
    if (end == begin) {
      continue;
    }
491
    auto dst = Slice(begin, end);
Y
Yi Wang 已提交
492
    framework::TensorCopy(*src, dst_place, &dst);
493
    begin = end;
Y
Yang Yang 已提交
494 495 496
  }
}

497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
LoD ConvertToLengthBasedLoD(const LoD &offset_lod) {
  LoD length_lod;
  length_lod.reserve(offset_lod.size());
  for (size_t lvl = 0; lvl < offset_lod.size(); ++lvl) {
    std::vector<size_t> level;
    if (offset_lod[lvl].size() > 0) {
      level.reserve(offset_lod[lvl].size() - 1);
    }
    for (size_t idx = 0; idx < offset_lod[lvl].size() - 1; ++idx) {
      level.push_back(offset_lod[lvl][idx + 1] - offset_lod[lvl][idx]);
    }
    length_lod.push_back(level);
  }
  return length_lod;
}

LoD ConvertToOffsetBasedLoD(const LoD &length_lod) {
  LoD offset_lod;
  offset_lod.reserve(length_lod.size());
  for (size_t lvl = 0; lvl < length_lod.size(); ++lvl) {
    std::vector<size_t> level;
    level.reserve(length_lod[lvl].size() + 1);
    size_t tmp = 0;
    level.push_back(tmp);
    for (size_t idx = 0; idx < length_lod[lvl].size(); ++idx) {
      tmp += length_lod[lvl][idx];
      level.push_back(tmp);
    }
    offset_lod.push_back(level);
  }
  return offset_lod;
}

530 531
}  // namespace framework
}  // namespace paddle