archive.h 19.8 KB
Newer Older
J
jiaqi 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// 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.
#pragma once

#if defined _WIN32 || defined __APPLE__
#else
#define _LINUX
#endif

#include <glog/logging.h>
22

J
jiaqi 已提交
23 24 25 26 27 28 29 30 31 32 33
#include <algorithm>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <valarray>
#include <vector>
34

J
jiaqi 已提交
35
#include "paddle/fluid/framework/expect.h"
36
#include "paddle/fluid/platform/enforce.h"
J
jiaqi 已提交
37 38 39 40 41 42 43 44 45 46 47

namespace paddle {
namespace framework {

// not a virtual class
class ArchiveBase {
 protected:
  ArchiveBase() {}

  // Archive is not copyable. But to allow move capture by function objects,
  // check it at runtime rather than at compile time.
48 49 50 51
  ArchiveBase(const ArchiveBase&) {
    PADDLE_THROW(platform::errors::Unavailable(
        "ArchiveBase class does not support copy construction."));
  }
J
jiaqi 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

  ArchiveBase(ArchiveBase&& other)
      : buffer_(other.buffer_),
        cursor_(other.cursor_),
        finish_(other.finish_),
        limit_(other.limit_),
        deleter_(std::move(other.deleter_)) {
    other.buffer_ = NULL;
    other.cursor_ = NULL;
    other.finish_ = NULL;
    other.limit_ = NULL;
    other.deleter_ = nullptr;
  }

  ~ArchiveBase() { FreeBuffer(); }

 public:
  ArchiveBase& operator=(const ArchiveBase&) {
70 71
    PADDLE_THROW(platform::errors::Unavailable(
        "ArchiveBase class does not support assignment construction."));
J
jiaqi 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
    return *this;
  }

  ArchiveBase& operator=(ArchiveBase&& other) {
    if (this != &other) {
      FreeBuffer();
      buffer_ = other.buffer_;
      cursor_ = other.cursor_;
      finish_ = other.finish_;
      limit_ = other.limit_;
      deleter_ = std::move(other.deleter_);
      other.buffer_ = NULL;
      other.cursor_ = NULL;
      other.finish_ = NULL;
      other.limit_ = NULL;
      other.deleter_ = nullptr;
    }
    return *this;
  }

  char* Buffer() { return buffer_; }

94 95
  void SetReadBuffer(char* buffer,
                     size_t length,
J
jiaqi 已提交
96 97 98 99
                     std::function<void(char*)>&& deleter) {
    SetBuffer(buffer, length, length, std::move(deleter));
  }

100 101
  void SetWriteBuffer(char* buffer,
                      size_t capacity,
J
jiaqi 已提交
102 103 104 105
                      std::function<void(char*)>&& deleter) {
    SetBuffer(buffer, 0, capacity, std::move(deleter));
  }

106 107 108
  void SetBuffer(char* buffer,
                 size_t length,
                 size_t capacity,
J
jiaqi 已提交
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
                 std::function<void(char*)>&& deleter) {
    CHECK(length <= capacity);
    FreeBuffer();
    buffer_ = buffer;
    cursor_ = buffer_;
    finish_ = buffer + length;
    limit_ = buffer + capacity;
    deleter_ = std::move(deleter);
  }

  char* Cursor() { return cursor_; }

  void SetCursor(char* cursor) {
    CHECK(cursor >= buffer_ && cursor <= finish_);
    cursor_ = cursor;
  }

  void AdvanceCursor(size_t offset) {
    CHECK(offset <= size_t(finish_ - cursor_));
    cursor_ += offset;
  }

  char* Finish() { return finish_; }

  void SetFinish(char* finish) {
    CHECK(finish >= cursor_ && finish <= limit_);
    finish_ = finish;
  }

  void AdvanceFinish(size_t offset) {
    CHECK(offset <= size_t(limit_ - finish_));
    finish_ += offset;
  }

  char* Limit() { return limit_; }

  size_t Position() { return cursor_ - buffer_; }

  size_t Length() { return finish_ - buffer_; }

  size_t Capacity() { return limit_ - buffer_; }

  bool Empty() { return finish_ == buffer_; }

  void Reset() {
    FreeBuffer();
    buffer_ = NULL;
    cursor_ = NULL;
    finish_ = NULL;
    limit_ = NULL;
  }

  void Clear() {
    cursor_ = buffer_;
    finish_ = buffer_;
  }

  char* Release() {
    char* buf = buffer_;
    buffer_ = NULL;
    cursor_ = NULL;
    finish_ = NULL;
    deleter_ = nullptr;
    return buf;
  }

  void Resize(size_t newsize) {
#ifdef _LINUX
    if (unlikely(newsize > Capacity())) {
#else
    if (newsize > Capacity()) {
#endif
181
      Reserve((std::max)(Capacity() * 2, newsize));
J
jiaqi 已提交
182 183
    }
    finish_ = buffer_ + newsize;
184
    cursor_ = (std::min)(cursor_, finish_);
J
jiaqi 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
  }

  void Reserve(size_t newcap) {
    if (newcap > Capacity()) {
      char* newbuf = NULL;
      newbuf = new char[newcap];
      CHECK(newbuf != nullptr) << "Reserve failed, out of memory";
      if (Length() > 0) {
        memcpy(newbuf, buffer_, Length());
      }
      cursor_ = newbuf + (cursor_ - buffer_);
      finish_ = newbuf + (finish_ - buffer_);
      limit_ = newbuf + newcap;
      FreeBuffer();
      buffer_ = newbuf;
      deleter_ = std::default_delete<char[]>();
    }
  }

  void PrepareRead(size_t size) {
#ifdef _LINUX
    if (unlikely(!(size <= size_t(finish_ - cursor_)))) {
#else
    if (!(size <= size_t(finish_ - cursor_))) {
#endif
      CHECK(size <= size_t(finish_ - cursor_));
    }
  }

  void PrepareWrite(size_t size) {
#ifdef _LINUX
    if (unlikely(size > size_t(limit_ - finish_))) {
#else
    if (size > size_t(limit_ - finish_)) {
#endif
220
      Reserve((std::max)(Capacity() * 2, Length() + size));
J
jiaqi 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
    }
  }

  void Read(void* data, size_t size) {
    if (size > 0) {
      PrepareRead(size);
      memcpy(data, cursor_, size);
      AdvanceCursor(size);
    }
  }

  void ReadBack(void* data, size_t size) {
    if (size > 0) {
      CHECK(size <= size_t(finish_ - cursor_));
      memcpy(data, finish_ - size, size);
      finish_ -= size;
    }
  }

  void Write(const void* data, size_t size) {
    if (size > 0) {
      PrepareWrite(size);
      memcpy(finish_, data, size);
      AdvanceFinish(size);
    }
  }

  template <class T>
  void GetRaw(T& x) {  // NOLINT
    PrepareRead(sizeof(T));
    memcpy(&x, cursor_, sizeof(T));
    AdvanceCursor(sizeof(T));
  }

  template <class T>
  T GetRaw() {
    T x;
    GetRaw<T>(x);
    return x;
  }

  template <class T>
  void PutRaw(const T& x) {
    PrepareWrite(sizeof(T));
    memcpy(finish_, &x, sizeof(T));
    AdvanceFinish(sizeof(T));
  }

 protected:
  char* buffer_ = NULL;
  char* cursor_ = NULL;
  char* finish_ = NULL;
  char* limit_ = NULL;
  std::function<void(char*)> deleter_ = nullptr;

  void FreeBuffer() {
    if (deleter_) {
      deleter_(buffer_);
    }
    deleter_ = nullptr;
  }
};  // NOLINT

template <class Type>
class Archive {};

class BinaryArchiveType {};

typedef Archive<BinaryArchiveType> BinaryArchive;

template <>
class Archive<BinaryArchiveType> : public ArchiveBase {
 public:
#define ARCHIVE_REPEAT(T)                 \
  BinaryArchive& operator>>(T& x) {       \
    GetRaw(x);                            \
    return *this;                         \
  }                                       \
  BinaryArchive& operator<<(const T& x) { \
    PutRaw(x);                            \
    return *this;                         \
  }

  ARCHIVE_REPEAT(int16_t)
  ARCHIVE_REPEAT(uint16_t)
  ARCHIVE_REPEAT(int32_t)
  ARCHIVE_REPEAT(uint32_t)
  ARCHIVE_REPEAT(int64_t)
  ARCHIVE_REPEAT(uint64_t)
  ARCHIVE_REPEAT(float)
  ARCHIVE_REPEAT(double)
  ARCHIVE_REPEAT(signed char)
  ARCHIVE_REPEAT(unsigned char)
  ARCHIVE_REPEAT(bool)

#undef ARCHIVE_REPEAT

  template <class T>
  T Get() {
    T x;
    *this >> x;
    return x;
  }
324 325 326 327 328 329

  template <class... ARGS>
  void Printf(const char* fmt, ARGS&&... args) {
    size_t temp = Limit() - Finish();
    int len = snprintf(Finish(), temp, fmt, args...);
    CHECK(len >= 0);  // NOLINT
330
    if (static_cast<size_t>(len) >= temp) {
331
      PrepareWrite(len + 1);
332 333
      CHECK(snprintf(Finish(), static_cast<size_t>(len) + 1, fmt, args...) ==
            len);
334 335 336
    }
    AdvanceFinish(len);
  }
J
jiaqi 已提交
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
};

template <class AR, class T, size_t N>
Archive<AR>& operator<<(Archive<AR>& ar, const T (&p)[N]) {
  for (size_t i = 0; i < N; i++) {
    ar << p[i];
  }
  return ar;
}

template <class AR, class T, size_t N>
Archive<AR>& operator>>(Archive<AR>& ar, T (&p)[N]) {
  for (size_t i = 0; i < N; i++) {
    ar >> p[i];
  }
  return ar;
}

template <class AR, class T>
Archive<AR>& operator<<(Archive<AR>& ar, const std::vector<T>& p) {
#ifdef _LINUX
358
  ar << static_cast<size_t>(p.size());
J
jiaqi 已提交
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
#else
  ar << (uint64_t)p.size();
#endif
  for (const auto& x : p) {
    ar << x;
  }
  return ar;
}

template <class AR, class T>
Archive<AR>& operator>>(Archive<AR>& ar, std::vector<T>& p) {
#ifdef _LINUX
  p.resize(ar.template Get<size_t>());
#else
  p.resize(ar.template Get<uint64_t>());
#endif
  for (auto& x : p) {
    ar >> x;
  }
  return ar;
}

template <class AR, class T>
Archive<AR>& operator<<(Archive<AR>& ar, const std::valarray<T>& p) {
#ifdef _LINUX
384
  ar << static_cast<size_t>(p.size());
J
jiaqi 已提交
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
#else
  ar << (uint64_t)p.size();
#endif
  for (const auto& x : p) {
    ar << x;
  }
  return ar;
}

template <class AR, class T>
Archive<AR>& operator>>(Archive<AR>& ar, std::valarray<T>& p) {
#ifdef _LINUX
  p.resize(ar.template Get<size_t>());
#else
  p.resize(ar.template Get<uint64_t>());
#endif
  for (auto& x : p) {
    ar >> x;
  }
  return ar;
}

inline BinaryArchive& operator<<(BinaryArchive& ar, const std::string& s) {
#ifdef _LINUX
409
  ar << static_cast<size_t>(s.length());
J
jiaqi 已提交
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
#else
  ar << (uint64_t)s.length();
#endif
  ar.Write(&s[0], s.length());
  return ar;
}

inline BinaryArchive& operator>>(BinaryArchive& ar, std::string& s) {
#ifdef _LINUX
  size_t len = ar.template Get<size_t>();
#else
  size_t len = ar.template Get<uint64_t>();
#endif
  ar.PrepareRead(len);
  s.assign(ar.Cursor(), len);
  ar.AdvanceCursor(len);
  return ar;
}

template <class AR, class T1, class T2>
Archive<AR>& operator<<(Archive<AR>& ar, const std::pair<T1, T2>& x) {
  return ar << x.first << x.second;
}

template <class AR, class T1, class T2>
Archive<AR>& operator>>(Archive<AR>& ar, std::pair<T1, T2>& x) {  // NOLINT
  return ar >> x.first >> x.second;
}

#ifdef _LINUX
template <class AR, class... T>
Archive<AR>& SerializeTuple(Archive<AR>& ar,                        // NOLINT
                            const std::tuple<T...>& x,              // NOLINT
                            std::integral_constant<size_t, 0> n) {  // NOLINT
  return ar;
}
#else
template <class AR, class... T>
Archive<AR>& SerializeTuple(Archive<AR>& ar,                          // NOLINT
                            const std::tuple<T...>& x,                // NOLINT
                            std::integral_constant<uint64_t, 0> n) {  // NOLINT
  return ar;
}
#endif

#ifdef _LINUX
template <class AR, class... T, size_t N>
Archive<AR>& serialize_tuple(Archive<AR>& ar,                        // NOLINT
                             const std::tuple<T...>& x,              // NOLINT
                             std::integral_constant<size_t, N> n) {  // NOLINT
  return SerializeTuple(ar, x, std::integral_constant<size_t, N - 1>())
         << std::get<N - 1>(x);
}
#else
template <class AR, class... T, uint64_t N>
Archive<AR>& serialize_tuple(Archive<AR>& ar,                          // NOLINT
                             const std::tuple<T...>& x,                // NOLINT
                             std::integral_constant<uint64_t, N> n) {  // NOLINT
  return SerializeTuple(ar, x, std::integral_constant<uint64_t, N - 1>())
         << std::get<N - 1>(x);
}
#endif

#ifdef _LINUX
template <class AR, class... T>
Archive<AR>& operator<<(Archive<AR>& ar, const std::tuple<T...>& x) {
  const size_t size = std::tuple_size<std::tuple<T...>>::value;
  return SerializeTuple(ar, x, std::integral_constant<size_t, size>());
}
#else
template <class AR, class... T>
Archive<AR>& operator<<(Archive<AR>& ar, const std::tuple<T...>& x) {
  const uint64_t size = std::tuple_size<std::tuple<T...>>::value;
  return SerializeTuple(ar, x, std::integral_constant<uint64_t, size>());
}
#endif

#ifdef _LINUX
template <class AR, class... T>
489 490
Archive<AR>& DeserializeTuple(const Archive<AR>& ar,
                              std::tuple<T...>& x,  // NOLINT
J
jiaqi 已提交
491 492 493 494 495
                              std::integral_constant<size_t, 0> n) {
  return ar;
}
#else
template <class AR, class... T>
496 497
Archive<AR>& DeserializeTuple(const Archive<AR>& ar,
                              std::tuple<T...>& x,  // NOLINT
J
jiaqi 已提交
498 499 500 501 502 503 504
                              std::integral_constant<uint64_t, 0> n) {
  return ar;
}
#endif

#ifdef _LINUX
template <class AR, class... T, size_t N>
505 506
Archive<AR>& DeserializeTuple(const Archive<AR>& ar,
                              std::tuple<T...>& x,  // NOLINT
J
jiaqi 已提交
507 508 509 510 511 512
                              std::integral_constant<size_t, N> n) {
  return DeserializeTuple(ar, x, std::integral_constant<size_t, N - 1>()) >>
         std::get<N - 1>(x);
}
#else
template <class AR, class... T, uint64_t N>
513 514
Archive<AR>& DeserializeTuple(const Archive<AR>& ar,
                              std::tuple<T...>& x,  // NOLINT
J
jiaqi 已提交
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
                              std::integral_constant<uint64_t, N> n) {
  return DeserializeTuple(ar, x, std::integral_constant<uint64_t, N - 1>()) >>
         std::get<N - 1>(x);
}
#endif

#ifdef _LINUX
template <class AR, class... T>
Archive<AR>& operator>>(Archive<AR>& ar, std::tuple<T...>& x) {
  const size_t size = std::tuple_size<std::tuple<T...>>::value;
  return DeserializeTuple(ar, x, std::integral_constant<size_t, size>());
}
#else
template <class AR, class... T>
Archive<AR>& operator>>(Archive<AR>& ar, std::tuple<T...>& x) {
  const uint64_t size = std::tuple_size<std::tuple<T...>>::value;
  return DeserializeTuple(ar, x, std::integral_constant<uint64_t, size>());
}
#endif

#ifdef _LINUX
#define ARCHIVE_REPEAT(MAP_TYPE, RESERVE_STATEMENT)                            \
  template <class AR, class KEY, class VALUE, class... ARGS>                   \
  Archive<AR>& operator<<(Archive<AR>& ar,                                     \
                          const MAP_TYPE<KEY, VALUE, ARGS...>& p) {            \
540
    ar << static_cast<size_t>(p.size());                                       \
J
jiaqi 已提交
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
    for (auto it = p.begin(); it != p.end(); ++it) {                           \
      ar << *it;                                                               \
    }                                                                          \
    return ar;                                                                 \
  }                                                                            \
  template <class AR, class KEY, class VALUE, class... ARGS>                   \
  Archive<AR>& operator>>(Archive<AR>& ar, MAP_TYPE<KEY, VALUE, ARGS...>& p) { \
    size_t size = ar.template get<size_t>();                                   \
    p.clear();                                                                 \
    RESERVE_STATEMENT;                                                         \
    for (size_t i = 0; i < size; i++) {                                        \
      p.insert(ar.template get<std::pair<KEY, VALUE>>());                      \
    }                                                                          \
    return ar;                                                                 \
  }
#else
#define ARCHIVE_REPEAT(MAP_TYPE, RESERVE_STATEMENT)                            \
  template <class AR, class KEY, class VALUE, class... ARGS>                   \
  Archive<AR>& operator<<(Archive<AR>& ar,                                     \
                          const MAP_TYPE<KEY, VALUE, ARGS...>& p) {            \
    ar << (uint64_t)p.size();                                                  \
    for (auto it = p.begin(); it != p.end(); ++it) {                           \
      ar << *it;                                                               \
    }                                                                          \
    return ar;                                                                 \
  }                                                                            \
  template <class AR, class KEY, class VALUE, class... ARGS>                   \
  Archive<AR>& operator>>(Archive<AR>& ar, MAP_TYPE<KEY, VALUE, ARGS...>& p) { \
    size_t size = ar.template get<uint64_t>();                                 \
    p.clear();                                                                 \
    RESERVE_STATEMENT;                                                         \
    for (size_t i = 0; i < size; i++) {                                        \
      p.insert(ar.template get<std::pair<KEY, VALUE>>());                      \
    }                                                                          \
    return ar;                                                                 \
  }
#endif

ARCHIVE_REPEAT(std::map, )
ARCHIVE_REPEAT(std::multimap, )
ARCHIVE_REPEAT(std::unordered_map, p.reserve(size))
ARCHIVE_REPEAT(std::unordered_multimap, p.reserve(size))

#undef ARCHIVE_REPEAT

#ifdef _LINUX
#define ARCHIVE_REPEAT(SET_TYPE, RESERVE_STATEMENT)                           \
  template <class AR, class KEY, class... ARGS>                               \
  Archive<AR>& operator<<(Archive<AR>& ar, const SET_TYPE<KEY, ARGS...>& p) { \
590
    ar << static_cast<size_t>(p.size());                                      \
J
jiaqi 已提交
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
    for (auto it = p.begin(); it != p.end(); ++it) {                          \
      ar << *it;                                                              \
    }                                                                         \
    return ar;                                                                \
  }                                                                           \
  template <class AR, class KEY, class... ARGS>                               \
  Archive<AR>& operator>>(Archive<AR>& ar, SET_TYPE<KEY, ARGS...>& p) {       \
    size_t size = ar.template get<size_t>();                                  \
    p.clear();                                                                \
    RESERVE_STATEMENT;                                                        \
    for (size_t i = 0; i < size; i++) {                                       \
      p.insert(ar.template get<KEY>());                                       \
    }                                                                         \
    return ar;                                                                \
  }
#else
#define ARCHIVE_REPEAT(SET_TYPE, RESERVE_STATEMENT)                           \
  template <class AR, class KEY, class... ARGS>                               \
  Archive<AR>& operator<<(Archive<AR>& ar, const SET_TYPE<KEY, ARGS...>& p) { \
    ar << (uint64_t)p.size();                                                 \
    for (auto it = p.begin(); it != p.end(); ++it) {                          \
      ar << *it;                                                              \
    }                                                                         \
    return ar;                                                                \
  }                                                                           \
  template <class AR, class KEY, class... ARGS>                               \
  Archive<AR>& operator>>(Archive<AR>& ar, SET_TYPE<KEY, ARGS...>& p) {       \
    size_t size = ar.template get<uint64_t>();                                \
    p.clear();                                                                \
    RESERVE_STATEMENT;                                                        \
    for (size_t i = 0; i < size; i++) {                                       \
      p.insert(ar.template get<KEY>());                                       \
    }                                                                         \
    return ar;                                                                \
  }
#endif

ARCHIVE_REPEAT(std::set, )
ARCHIVE_REPEAT(std::multiset, )
ARCHIVE_REPEAT(std::unordered_set, p.reserve(size))
ARCHIVE_REPEAT(std::unordered_multiset, p.reserve(size))

#undef ARCHIVE_REPEAT

}  // namespace framework
}  // namespace paddle