naive_buffer.h 10.3 KB
Newer Older
Y
Yan Chunwei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 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 181 182 183 184 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 220 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 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
// 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
#include <memory>
#include <string>
#include <vector>
#include "lite/core/types.h"
#include "lite/utils/container.h"
#include "lite/utils/cp_logging.h"

/*
 * This file contains the implementation of NaiveBuffer. We implement the basic
 * interfaces for serialization and de-serialization for a PaddlePaddle model to
 * avoid using the third-party libraries such as protobuf, and make the lite
 * dependencies small and easy to compile and deploy.
 */

namespace paddle {
namespace lite {
namespace naive_buffer {

using core::Type;
using byte_t = uint8_t;

/*
 * BinaryTable is a binary buffer, it holds all the fields of a NaiveBuffer
 * object.
 * A BinaryTable can only support write or read in its lifetime, it is mutable
 * by default, but the `Load` method will get a readonly BinaryTable.
 */
struct BinaryTable {
 private:
  std::vector<byte_t> bytes_;
  size_t cursor_{};
  bool is_mutable_mode_{true};  // true for mutable, false for readonly.

 public:
  /// Require free memory of `size` bytes.
  void Require(size_t size);

  /// Consume some memory.
  void Consume(size_t bytes);

  /// The current position of cursor for save or load.
  byte_t* cursor() { return &bytes_[cursor_]; }
  const byte_t* data() const { return bytes_.data(); }
  size_t size() const { return bytes_.size(); }
  size_t free_size() const { return bytes_.size() - cursor_; }

  /// Serialize the table to a binary buffer.
  void SaveToFile(const std::string& filename) const;

  void LoadFromFile(const std::string& filename);
};

/*
 * Base class of all the fields.
 */
class FieldBuilder {
  BinaryTable* table_{};

 public:
  explicit FieldBuilder(BinaryTable* table) : table_(table) {}

  // Write data to table and update the overall cursor.
  virtual void Save() = 0;
  // Load data from table and update the overall cursor.
  virtual void Load() = 0;

  virtual Type type() const = 0;

  BinaryTable* table() { return table_; }

  virtual ~FieldBuilder() = default;
};

/*
 * Builder for all the primary types. int32, float, bool and so on.
 */
template <typename Primary>
class PrimaryBuilder : public FieldBuilder {
  Primary data_;

 public:
  using value_type = Primary;

  explicit PrimaryBuilder(BinaryTable* table) : FieldBuilder(table) {}
  PrimaryBuilder(BinaryTable* table, const Primary& val)
      : FieldBuilder(table), data_(val) {}

  /// Set data.
  void set(Primary x) { data_ = x; }

  Primary data() const { return data_; }

  /// Save information to the corresponding BinaryTable.
  void Save() override;

  /// Load information from the corresponding BinaryTable.
  void Load() override;

  Type type() const override { return core::StdTypeToRepr<Primary>(); }

  ~PrimaryBuilder() = default;
};

using BoolBuilder = PrimaryBuilder<bool>;
using CharBuilder = PrimaryBuilder<char>;
using Int32Builder = PrimaryBuilder<int32_t>;
using UInt32Builder = PrimaryBuilder<uint32_t>;
using Int64Builder = PrimaryBuilder<int64_t>;
using UInt64Builder = PrimaryBuilder<uint64_t>;
using Float32Builder = PrimaryBuilder<float>;
using Float64Builder = PrimaryBuilder<double>;

/*
 * Builder for all the primary types. int32, float, bool and so on.
 */
template <typename EnumType>
class EnumBuilder : public FieldBuilder {
  EnumType data_;

 public:
  using value_type = int32_t;

  explicit EnumBuilder(BinaryTable* table) : FieldBuilder(table) {}

  /// Set data.
  void set(EnumType x) { data_ = x; }

  EnumType data() const { return data_; }

  /// Save information to the corresponding BinaryTable.
  void Save() override;

  /// Load information from the corresponding BinaryTable.
  void Load() override;

  ~EnumBuilder() = default;

  Type type() const override { return Type::_enum; }
};

class StringBuilder : public FieldBuilder {
  std::string data_;

 public:
  explicit StringBuilder(BinaryTable* table) : FieldBuilder(table) {}
  StringBuilder(BinaryTable* table, const std::string& val)
      : FieldBuilder(table), data_(val) {}

  void set(const std::string& x) { data_ = x; }

  const std::string& data() const { return data_; }

  void Save() override;

  void Load() override;

  Type type() const override { return Type::_string; }
};

/*
 * This is a data structure. A composion of multiple fields.
 *
 * Usage:
 *
 * class MyStruct : public StructBuilder {
 *   public:
 *     MyStruct(BinaryTable* table) : StructBuilder(table) {
 *       NewStr("name");
 *       NewInt32("age");
 *     }
 * };
 *
 * One can retrive a field with the specific field name.
 * e.g.
 * GetField<Int32Builder>("age") will get the age field declared in `MyStruct`
 * GetMutableField<Int32Builder>("age") will get the mutable age field declared
 * in `MyStruct`
 */
class StructBuilder : public FieldBuilder {
  OrderedMap<std::unique_ptr<FieldBuilder>> field_builders_;

 public:
  explicit StructBuilder(BinaryTable* table) : FieldBuilder(table) {}

#define NEW_PRIMARY_BUILDER_DECLARE(T, name__, dft_val__) \
  PrimaryBuilder<T>* New##name__(const std::string& name, T val = dft_val__);
  NEW_PRIMARY_BUILDER_DECLARE(bool, Bool, false);
  NEW_PRIMARY_BUILDER_DECLARE(char, Char, 0);
  NEW_PRIMARY_BUILDER_DECLARE(int32_t, Int32, 0);
  NEW_PRIMARY_BUILDER_DECLARE(uint32_t, UInt32, 0);
  NEW_PRIMARY_BUILDER_DECLARE(int64_t, Int64, 0);
  NEW_PRIMARY_BUILDER_DECLARE(uint64_t, UInt64, 0);
  NEW_PRIMARY_BUILDER_DECLARE(float, Float32, 0.0);
  NEW_PRIMARY_BUILDER_DECLARE(double, Float64, 0.0);
#undef NEW_PRIMARY_BUILDER_DECLARE

  /// Create a string field called `name`.
  StringBuilder* NewStr(const std::string& name, const std::string& val = "");

  /// Create a user-defined field, this can build a complex composed struct.
  template <typename CustomBuilder>
  CustomBuilder* New(const std::string& name);

  /// Save the fields' information to the corresponding BinaryTable.
  void Save() override;

  /// Load the fields' information from the corresponding BinaryTable.
  void Load() override;

  /// Type of this struct.
  // TODO(Superjomn) The customized type is not supported yet.
  Type type() const override { return Type::_unk; }

  /// Get a field by `name`.
  template <typename T>
  const T& GetField(const std::string& name) const {
    auto& builder = field_builders_.Get(name);
    return *(static_cast<const T*>(builder.get()));
  }

  /// Get a mutable field by `name`.
  template <typename T>
  T* GetMutableField(const std::string& name) {
    auto& builder = field_builders_.GetMutable(name);
    return static_cast<T*>(builder.get());
  }
};

/*
 * Builder of a Struct List.
 *
 * Such as
 *
 * ListBuilder<Int32Builder> is equal to a vector<int32>
 */
template <typename Builder>
class ListBuilder : public FieldBuilder {
  std::vector<Builder> builders_;

 public:
  explicit ListBuilder(BinaryTable* table) : FieldBuilder(table) {}

  // Create a new element.
  Builder* New() {
    builders_.emplace_back(table());
    return &builders_.back();
  }

  // Get i-th element.
  const Builder& Get(int i) const {
    CHECK_LT(i, builders_.size());
    return builders_[i];
  }

  Builder* GetMutable(int i) {
    CHECK_LT(i, builders_.size());
    return &builders_[i];
  }

  typename std::vector<Builder>::iterator begin() { return builders_.begin(); }

  typename std::vector<Builder>::iterator end() { return builders_.end(); }

  typename std::vector<Builder>::const_iterator begin() const {
    return builders_.begin();
  }

  typename std::vector<Builder>::const_iterator end() const {
    return builders_.end();
  }

  // Get element type.
  Type type() const override { return Type::_list; }

  /// Persist information to the corresponding BinaryTable.
  void Save() override;

  /// Load information from the corresponding BinaryTable.
  void Load() override;

  /// Number of elements.
  size_t size() const { return builders_.size(); }

  /// clear builders
  void Clear() { builders_.clear(); }
};

template <typename Builder>
void ListBuilder<Builder>::Save() {
  // store number of elements in the head.
  size_t num_elems = size();
  table()->Require(sizeof(size_t));
  memcpy(table()->cursor(), &num_elems, sizeof(size_t));
  table()->Consume(sizeof(size_t));

  // Save all the elements.
  for (auto& elem : builders_) {
    elem.Save();
  }
}

template <typename Builder>
void ListBuilder<Builder>::Load() {
  CHECK(builders_.empty()) << "Duplicate load";
  // Load number of elements first.
  size_t num_elems{};
  memcpy(&num_elems, table()->cursor(), sizeof(num_elems));
  table()->Consume(sizeof(size_t));

  // Load all the elements.
  for (size_t i = 0; i < num_elems; i++) {
    builders_.emplace_back(table());
    builders_.back().Load();
  }
}

template <typename Primary>
void PrimaryBuilder<Primary>::Save() {
  table()->Require(sizeof(value_type));
  memcpy(
      table()->cursor(), reinterpret_cast<byte_t*>(&data_), sizeof(value_type));
  table()->Consume(sizeof(value_type));
}

template <typename Primary>
void PrimaryBuilder<Primary>::Load() {
  memcpy(&data_, table()->cursor(), sizeof(value_type));
  table()->Consume(sizeof(value_type));
}

template <typename EnumType>
void EnumBuilder<EnumType>::Save() {
  value_type holder = static_cast<value_type>(data_);
  table()->Require(sizeof(value_type));
  memcpy(table()->cursor(),
         reinterpret_cast<byte_t*>(&holder),
         sizeof(value_type));
  table()->Consume(sizeof(value_type));
}

template <typename EnumType>
void EnumBuilder<EnumType>::Load() {
  value_type holder;
  memcpy(&holder, table()->cursor(), sizeof(value_type));
  table()->Consume(sizeof(value_type));
  data_ = static_cast<EnumType>(holder);
}

template <typename CustomBuilder>
CustomBuilder* StructBuilder::New(const std::string& name) {
  using type = CustomBuilder;
  field_builders_.Set(name, std::unique_ptr<CustomBuilder>(new type(table())));
  return static_cast<type*>(field_builders_.GetMutable(name).get());
}

}  // namespace naive_buffer
}  // namespace lite
}  // namespace paddle