model_parser.cc 38.1 KB
Newer Older
Y
Yan Chunwei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// 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.

#include "lite/model_parser/model_parser.h"
#include <algorithm>
#include <fstream>
#include <limits>
Y
Yan Chunwei 已提交
19
#include <set>
20

Y
Yan Chunwei 已提交
21 22 23
#include "lite/core/scope.h"
#include "lite/core/tensor.h"
#include "lite/core/variable.h"
24
#include "lite/core/version.h"
25
#include "lite/model_parser/base/apis.h"
26
#include "lite/model_parser/flatbuffers/io.h"
27
#ifndef LITE_ON_TINY_PUBLISH
Y
Yan Chunwei 已提交
28
#include "lite/model_parser/naive_buffer/combined_params_desc.h"
Y
Yan Chunwei 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
#include "lite/model_parser/naive_buffer/param_desc.h"
#include "lite/model_parser/naive_buffer/program_desc.h"
#include "lite/model_parser/naive_buffer/var_desc.h"
#include "lite/model_parser/pb/program_desc.h"
#include "lite/model_parser/pb/var_desc.h"
#endif
#include "lite/utils/io.h"

namespace paddle {
namespace lite {

#ifndef LITE_ON_TINY_PUBLISH
int SizeOfType(framework::proto::VarType::Type type) {
  using Type = framework::proto::VarType::Type;
  switch (static_cast<int>(type)) {
#define DO(desc, type)            \
  case Type::VarType_Type_##desc: \
    return sizeof(type);
    DO(BOOL, bool);
    DO(FP16, float);
    DO(FP32, float);
    DO(INT8, int8_t);
J
juncaipeng 已提交
51
    DO(INT16, int16_t);
Y
Yan Chunwei 已提交
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
    DO(INT32, int);
    DO(INT64, int64_t);
#undef DO
    default:
      LOG(FATAL) << "unknown data type " << type;
  }
  return -1;
}

void TensorFromStream(std::istream &is, lite::Tensor *tensor) {
  using Type = framework::proto::VarType::Type;
  uint32_t version;
  is.read(reinterpret_cast<char *>(&version), sizeof(version));
  CHECK_EQ(version, 0U) << "Only version 0 is supported";
  // read tensor desc
  framework::proto::VarType::TensorDesc desc;
  {
    // int32_t size
    // proto buffer
    int32_t size;
    is.read(reinterpret_cast<char *>(&size), sizeof(size));
    std::unique_ptr<char[]> buf(new char[size]);
    is.read(reinterpret_cast<char *>(buf.get()), size);
    CHECK(desc.ParseFromArray(buf.get(), size)) << "Cannot parse tensor desc";
  }

  // read tensor
  std::vector<int64_t> dims_vec;
  std::copy(
      desc.dims().begin(), desc.dims().end(), std::back_inserter(dims_vec));
  lite::DDim dims(dims_vec);
  tensor->Resize(dims);
  void *buf;
  size_t size = tensor->dims().production() * SizeOfType(desc.data_type());
  // alllocate memory
  switch (static_cast<int>(desc.data_type())) {
88 89 90 91 92 93 94 95 96 97 98 99 100
#define SET_TENSOR(desc, type, precision) \
  case Type::VarType_Type_##desc:         \
    buf = tensor->mutable_data<type>();   \
    tensor->set_precision(precision);     \
    break

    // SET_TENSOR(BOOL, bool, PRECISION(kBool));
    SET_TENSOR(FP32, float, PRECISION(kFloat));
    SET_TENSOR(INT8, int8_t, PRECISION(kInt8));
    SET_TENSOR(INT16, int16_t, PRECISION(kInt16));
    SET_TENSOR(INT32, int32_t, PRECISION(kInt32));
    SET_TENSOR(INT64, int64_t, PRECISION(kInt64));
#undef SET_TENSOR
Y
Yan Chunwei 已提交
101 102 103
    default:
      LOG(FATAL) << "unknown type " << desc.data_type();
  }
104
  tensor->set_persistable(true);
Y
Yan Chunwei 已提交
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

  is.read(static_cast<char *>(buf), size);
}

void LoadLoDTensor(std::istream &is, Variable *var) {
  auto *tensor = var->GetMutable<lite::Tensor>();
  uint32_t version{};
  is.read(reinterpret_cast<char *>(&version), sizeof(version));
  VLOG(3) << "model version " << version;

  // Load 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<uint64_t> tmp(size / sizeof(uint64_t));
    is.read(reinterpret_cast<char *>(tmp.data()),
            static_cast<std::streamsize>(size));
    lod[i] = tmp;
  }

  TensorFromStream(is, tensor);
}

void ReadBinaryFile(const std::string &filename, std::string *contents) {
  std::ifstream fin(filename, std::ios::in | std::ios::binary);
  CHECK(fin.is_open()) << "Cannot open file: " << filename;
  fin.seekg(0, std::ios::end);
  auto size = fin.tellg();
  contents->clear();
  contents->resize(size);
  fin.seekg(0, std::ios::beg);
  fin.read(&(contents->at(0)), contents->size());
  fin.close();
}

std::unique_ptr<framework::proto::ProgramDesc> LoadProgram(
145
    const std::string &path, bool program_from_memory) {
Y
Yan Chunwei 已提交
146 147
  std::unique_ptr<framework::proto::ProgramDesc> main_program(
      new framework::proto::ProgramDesc);
148 149 150 151 152 153 154
  if (!program_from_memory) {
    std::string desc_str;
    ReadBinaryFile(path, &desc_str);
    main_program->ParseFromString(desc_str);
  } else {
    main_program->ParseFromString(path);
  }
Y
Yan Chunwei 已提交
155 156 157 158 159 160 161 162 163 164 165 166
  return main_program;
}

void LoadParams(const std::string &path) {}

// Load directly to CPU, and latter transfer to other devices.
void LoadParam(const std::string &path, Variable *out) {
  std::ifstream fin(path, std::ios::binary);
  CHECK(fin.is_open()) << "failed to open file " << path;
  LoadLoDTensor(fin, out);
}

167 168 169 170 171 172 173 174 175 176 177
bool IsPersistable(const cpp::VarDesc &var) {
  if (var.Persistable() && var.GetType() != VarDescAPI::Type::FEED_MINIBATCH &&
      var.GetType() != VarDescAPI::Type::FETCH_LIST &&
      var.GetType() != VarDescAPI::Type::RAW) {
    return true;
  }
  return false;
}

void LoadCombinedParamsPb(const std::string &path,
                          lite::Scope *scope,
178 179
                          const cpp::ProgramDesc &cpp_prog,
                          bool params_from_memory) {
180
  CHECK(scope);
181
  auto &prog = cpp_prog;
182 183 184 185 186 187 188 189 190
  auto &main_block_desc = *prog.GetBlock<cpp::BlockDesc>(0);

  // Get vars
  std::vector<std::string> paramlist;
  for (size_t i = 0; i < main_block_desc.VarsSize(); ++i) {
    auto &var = *main_block_desc.GetVar<cpp::VarDesc>(i);
    if (!IsPersistable(var)) continue;
    paramlist.push_back(var.Name());
  }
191
  std::stable_sort(paramlist.begin(), paramlist.end());
192 193

  // Load vars
194 195 196 197 198 199 200 201 202 203
  auto load_var_func = [&](std::istream &is) {
    for (size_t i = 0; i < paramlist.size(); ++i) {
      auto *var = scope->Var(paramlist[i]);
      // Error checking
      CHECK(static_cast<bool>(is))
          << "There is a problem with loading model parameters";
      LoadLoDTensor(is, var);
    }
    is.peek();
    CHECK(is.eof()) << "You are not allowed to load partial data via"
204
                    << " LoadCombinedParamsPb, use LoadParam instead.";
205 206 207 208 209 210 211 212 213 214
  };

  if (params_from_memory) {
    std::stringstream fin(path, std::ios::in | std::ios::binary);
    load_var_func(fin);
  } else {
    std::ifstream fin(path, std::ios::binary);
    CHECK(fin.is_open());
    load_var_func(fin);
  }
215 216
}

Y
Yan Chunwei 已提交
217
void LoadModelPb(const std::string &model_dir,
218 219
                 const std::string &model_file,
                 const std::string &param_file,
Y
Yan Chunwei 已提交
220
                 Scope *scope,
221
                 cpp::ProgramDesc *cpp_prog,
222 223
                 bool combined,
                 bool model_from_memory) {
Y
Yan Chunwei 已提交
224 225 226 227 228
  CHECK(cpp_prog);
  CHECK(scope);
  cpp_prog->ClearBlocks();

  // Load model
229
  VLOG(4) << "Start load model program...";
230 231 232 233
  std::string prog_path = model_dir + "/__model__";
  if (combined) {
    prog_path = model_file;
  }
234 235
  framework::proto::ProgramDesc pb_proto_prog =
      *LoadProgram(prog_path, model_from_memory);
Y
Yan Chunwei 已提交
236 237 238 239 240 241
  pb::ProgramDesc pb_prog(&pb_proto_prog);
  // Transform to cpp::ProgramDesc
  TransformProgramDescAnyToCpp(pb_prog, cpp_prog);

  // Load Params
  // NOTE: Only main block be used now.
242 243 244 245 246
  VLOG(4) << "Start load model params...";
  CHECK(!(!combined && model_from_memory))
      << "If you want use the model_from_memory,"
      << " you should load the combined model using cfg.set_model_buffer "
         "interface.";
247
  if (combined) {
248
    LoadCombinedParamsPb(param_file, scope, *cpp_prog, model_from_memory);
249 250 251 252 253
  } else {
    auto main_block = pb_proto_prog.blocks(0);
    for (auto &var : main_block.vars()) {
      if (var.name() == "feed" || var.name() == "fetch" || !var.persistable())
        continue;
Y
Yan Chunwei 已提交
254

255 256
      std::string file_path = model_dir + "/" + var.name();
      VLOG(4) << "reading weight " << var.name();
Y
Yan Chunwei 已提交
257

258
      std::ifstream file(file_path, std::ios::binary);
259 260 261 262 263 264 265
      switch (var.type().type()) {
        case framework::proto::VarType_Type_LOD_TENSOR:
          LoadLoDTensor(file, scope->Var(var.name()));
          break;
        default:
          CHECK(false) << "unknown weight type";
      }
Y
Yan Chunwei 已提交
266 267
    }
  }
268

Y
Yan Chunwei 已提交
269 270 271 272 273
  VLOG(4) << "Load protobuf model in '" << model_dir << "'' successfully";
}

void SaveModelPb(const std::string &model_dir,
                 const Scope &exec_scope,
274 275
                 const cpp::ProgramDesc &cpp_prog,
                 bool combined) {
Y
Yan Chunwei 已提交
276 277 278 279 280 281
  MkDirRecur(model_dir);
  // Save program
  framework::proto::ProgramDesc pb_proto_prog;
  pb::ProgramDesc pb_prog(&pb_proto_prog);
  TransformProgramDescCppToAny(cpp_prog, &pb_prog);

282 283 284 285
  std::string prog_path = model_dir + "/__model__";
  if (combined) {
    prog_path = model_dir + "/model";
  }
Y
Yan Chunwei 已提交
286 287 288 289 290 291 292 293
  std::ofstream model_ostream(prog_path, std::ios_base::binary);
  CHECK(model_ostream.is_open());
  const std::string pb_str = pb_proto_prog.SerializeAsString();
  model_ostream.write(pb_str.c_str(), pb_str.size());
  model_ostream.close();

  // Save Params
  // NOTE: Only main block be used now.
294 295 296 297 298 299 300 301 302 303 304 305 306 307
  if (combined) {
    const std::string combined_params_path = model_dir + "/params";
    SaveCombinedParamsPb(combined_params_path, exec_scope, cpp_prog);
  } else {
    for (auto &item : pb_proto_prog.blocks(0).vars()) {
      if (item.name() == "feed" || item.name() == "fetch" ||
          !item.persistable())
        continue;
      const std::string path = model_dir + "/" + item.name();
      std::ofstream var_ostream(path, std::ios::binary);
      CHECK(var_ostream.is_open());
      SerializeTensor(var_ostream, exec_scope, item.name());
      var_ostream.close();
    }
Y
Yan Chunwei 已提交
308 309 310 311
  }
  VLOG(4) << "Save protobuf model in '" << model_dir << "'' successfully";
}

312 313 314
void SaveCombinedParamsPb(const std::string &path,
                          const lite::Scope &exec_scope,
                          const cpp::ProgramDesc &cpp_prog) {
315
  auto &prog = cpp_prog;
316 317 318 319 320 321 322 323 324
  auto &main_block_desc = *prog.GetBlock<cpp::BlockDesc>(0);

  // Get vars
  std::vector<std::string> paramlist;
  for (size_t i = 0; i < main_block_desc.VarsSize(); ++i) {
    auto &var = *main_block_desc.GetVar<cpp::VarDesc>(i);
    if (!IsPersistable(var)) continue;
    paramlist.push_back(var.Name());
  }
325
  std::stable_sort(paramlist.begin(), paramlist.end());
326 327

  // Load vars
328
  std::ofstream file(path, std::ios::binary);
329 330 331 332 333 334 335
  CHECK(file.is_open());
  for (size_t i = 0; i < paramlist.size(); ++i) {
    SerializeTensor(file, exec_scope, paramlist[i]);
  }
  file.close();
}

Y
Yan Chunwei 已提交
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
void TensorToStream(std::ostream &os, const lite::Tensor &tensor) {
  // the 1st field, uint32_t version
  constexpr uint32_t version = 0;
  os.write(reinterpret_cast<const char *>(&version), sizeof(version));

  {
    uint64_t size = tensor.lod().size();
    // the 2st field, LoD information
    // uint64_t lod_level
    // uint64_t lod_level_1 size in byte.
    // int*     lod_level_1 data
    // ...
    os.write(reinterpret_cast<const char *>(&size), sizeof(size));

    for (auto &each : tensor.lod()) {
      size = each.size() * sizeof(each.front());
      os.write(reinterpret_cast<const char *>(&size), sizeof(size));
      os.write(reinterpret_cast<const char *>(each.data()),
               static_cast<std::streamsize>(size));
    }
  }

  // There are two version fields in a LoDTensor.
  os.write(reinterpret_cast<const char *>(&version), sizeof(version));

  {  // the 2nd field, tensor description
    // int32_t  size
    // void*    protobuf message
    framework::proto::VarType::TensorDesc desc;
    // TODO(Superjomn) support other data types.
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
    switch (tensor.precision()) {
#define SET_DATA_TYPE(precision, type_desc) \
  case precision:                           \
    desc.set_data_type(type_desc);          \
    break

      SET_DATA_TYPE(PRECISION(kFloat), framework::proto::VarType_Type_FP32);
      SET_DATA_TYPE(PRECISION(kInt8), framework::proto::VarType_Type_INT8);
      SET_DATA_TYPE(PRECISION(kInt16), framework::proto::VarType_Type_INT16);
      SET_DATA_TYPE(PRECISION(kInt32), framework::proto::VarType_Type_INT32);
      SET_DATA_TYPE(PRECISION(kInt64), framework::proto::VarType_Type_INT64);
#undef SET_DATA_TYPE
      default:
        LOG(FATAL) << "unknown precision type: "
                   << PrecisionToStr(tensor.precision());
    }
Y
Yan Chunwei 已提交
382 383 384 385 386
    auto dims = tensor.dims();
    auto *pb_dims = desc.mutable_dims();
    pb_dims->Resize(static_cast<int>(dims.size()), 0);
    auto dims_vec = dims.Vectorize();
    std::copy(dims_vec.begin(), dims_vec.end(), pb_dims->begin());
387
    int32_t size = desc.ByteSizeLong();
Y
Yan Chunwei 已提交
388 389 390 391 392 393
    os.write(reinterpret_cast<const char *>(&size), sizeof(size));
    auto out = desc.SerializeAsString();
    os.write(out.data(), size);
  }
  {  // the 3rd field, tensor data
    uint64_t size = tensor.memory_size();
394
    CHECK_LT(size, (std::numeric_limits<std::streamsize>::max)())
Y
Yan Chunwei 已提交
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
        << "Index overflow when writing tensor";

#ifdef LITE_WITH_CUDA
    if (tensor.target() == TARGET(kCUDA)) {
      std::unique_ptr<char> tmp_buffer(new char[size]);
      TargetWrapperCuda::MemcpySync(tmp_buffer.get(),
                                    tensor.data<float>(),
                                    tensor.data_size(),
                                    IoDirection::DtoH);
      os.write(static_cast<const char *>(tmp_buffer.get()),
               static_cast<std::streamsize>(size));
    } else  // NOLINT
#endif      // LITE_WITH_CUDA
    {
      os.write(static_cast<const char *>(tensor.data<void>()),
               static_cast<std::streamsize>(size));
    }
  }
}

void SerializeTensor(std::ostream &os,
                     const lite::Scope &scope,
                     const std::string &var_name) {
  // Store all the persistable vars.
  auto *var = scope.FindVar(var_name);
  const auto &tensor = var->Get<lite::Tensor>();
  TensorToStream(os, tensor);
}

/// For navie buffer
Y
Yan Chunwei 已提交
425 426 427 428 429 430
void SetParamInfoNaive(naive_buffer::ParamDesc *param_desc,
                       const lite::Scope &scope,
                       const std::string &var_name) {
  CHECK(param_desc);
  auto &desc = *param_desc;

Y
Yan Chunwei 已提交
431 432 433 434 435 436
  // the 1st field, uint32_t version
  constexpr uint32_t version = 0;

  auto *var = scope.FindVar(var_name);
  const auto &tensor = var->Get<lite::Tensor>();

Y
Yan Chunwei 已提交
437
  desc.SetName(var_name);
Y
Yan Chunwei 已提交
438 439 440 441 442 443 444 445

  desc.SetModelVersion(version);
  desc.SetTensorVersion(version);

  desc.SetLoDLevel(tensor.lod().size());
  desc.SetLoD(tensor.lod());

  // TODO(sangoly): support other data types.
446 447 448 449
  switch (tensor.precision()) {
#define SET_DATA_TYPE(precision, type_desc) \
  case precision:                           \
    desc.SetDataType(type_desc);            \
450
    break;
451 452 453 454 455 456 457 458 459 460 461

    SET_DATA_TYPE(PRECISION(kFloat), VarDescAPI::VarDataType::FP32);
    SET_DATA_TYPE(PRECISION(kInt8), VarDescAPI::VarDataType::INT8);
    SET_DATA_TYPE(PRECISION(kInt16), VarDescAPI::VarDataType::INT16);
    SET_DATA_TYPE(PRECISION(kInt32), VarDescAPI::VarDataType::INT32);
    SET_DATA_TYPE(PRECISION(kInt64), VarDescAPI::VarDataType::INT64);
#undef SET_DATA_TYPE
    default:
      LOG(FATAL) << "unknown precision type: "
                 << PrecisionToStr(tensor.precision());
  }
Y
Yan Chunwei 已提交
462 463
  desc.SetDim(tensor.dims().Vectorize());
  uint64_t size = tensor.memory_size();
464
  CHECK_LT(size, (std::numeric_limits<std::streamsize>::max)())
Y
Yan Chunwei 已提交
465 466 467 468
      << "Index overflow when writing tensor";

#ifdef LITE_WITH_CUDA
  if (tensor.target() == TARGET(kCUDA)) {
469 470
    switch (tensor.precision()) {
#define DO(precision, type)                                         \
471
  case precision: {                                                 \
472 473 474 475 476 477
    std::unique_ptr<type> tmp_buffer(new type[tensor.data_size()]); \
    TargetWrapperCuda::MemcpySync(tmp_buffer.get(),                 \
                                  tensor.data<type>(),              \
                                  tensor.data_size(),               \
                                  IoDirection::DtoH);               \
    desc.SetData<type>(tmp_buffer.get(), tensor.data_size());       \
478
  } break;
479 480 481 482 483 484 485 486 487 488
      DO(PRECISION(kFloat), float);
      DO(PRECISION(kInt8), int8_t);
      DO(PRECISION(kInt16), int16_t);
      DO(PRECISION(kInt32), int32_t);
      DO(PRECISION(kInt64), int64_t);
#undef DO
      default:
        LOG(FATAL) << "unknown precision type: "
                   << PrecisionToStr(tensor.precision());
    }
Y
Yan Chunwei 已提交
489 490 491
  } else  // NOLINT
#endif    // LITE_WITH_CUDA
  {
492 493 494 495
    switch (tensor.precision()) {
#define DO(precision, type)                                      \
  case precision:                                                \
    desc.SetData<type>(tensor.data<type>(), tensor.data_size()); \
496
    break;
497 498 499 500 501 502 503 504 505 506
      DO(PRECISION(kFloat), float);
      DO(PRECISION(kInt8), int8_t);
      DO(PRECISION(kInt16), int16_t);
      DO(PRECISION(kInt32), int32_t);
      DO(PRECISION(kInt64), int64_t);
#undef DO
      default:
        LOG(FATAL) << "unknown precision type: "
                   << PrecisionToStr(tensor.precision());
    }
Y
Yan Chunwei 已提交
507
  }
Y
Yan Chunwei 已提交
508 509 510 511 512 513 514 515 516 517
}

void SaveParamNaive(const std::string &path,
                    const lite::Scope &scope,
                    const std::string &var_name) {
  naive_buffer::BinaryTable table;
  naive_buffer::proto::ParamDesc pt_desc(&table);
  naive_buffer::ParamDesc desc(&pt_desc);

  SetParamInfoNaive(&desc, scope, var_name);
Y
Yan Chunwei 已提交
518 519 520 521 522 523

  // Save param
  pt_desc.Save();
  table.SaveToFile(path);
}

Y
Yan Chunwei 已提交
524 525 526 527 528 529 530
void SaveCombinedParamsNaive(const std::string &path,
                             const lite::Scope &exec_scope,
                             const cpp::ProgramDesc &cpp_prog) {
  naive_buffer::BinaryTable table;
  naive_buffer::proto::CombinedParamsDesc pt_desc(&table);
  naive_buffer::CombinedParamsDesc desc(&pt_desc);

531
  auto &prog = cpp_prog;
Y
Yan Chunwei 已提交
532
  auto &main_block_desc = *prog.GetBlock<cpp::BlockDesc>(0);
533
  // set unique_var_names to avoid saving shared params repeatedly
534
  std::set<std::string> unique_var_names;
Y
Yan Chunwei 已提交
535 536
  for (size_t i = 0; i < main_block_desc.VarsSize(); ++i) {
    auto &var = *main_block_desc.GetVar<cpp::VarDesc>(i);
537 538
    if (var.Name() == "feed" || var.Name() == "fetch" || !var.Persistable() ||
        unique_var_names.count(var.Name()) > 0)
Y
Yan Chunwei 已提交
539 540 541
      continue;
    naive_buffer::ParamDesc param_desc(desc.AddParam());
    SetParamInfoNaive(&param_desc, exec_scope, var.Name());
542
    unique_var_names.emplace(var.Name());
Y
Yan Chunwei 已提交
543 544 545
  }

  pt_desc.Save();
546
  table.AppendToFile(path);
Y
Yan Chunwei 已提交
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
////////////////////////////////////////////////////////////////////////////////////
// Save model: meta_version = 1
// Flatbuffer model + params
////////////////////////////////////////////////////////////////////////////////////
// Create a new file and write data into it.
void WriteToFile(const std::string &filename,
                 const void *src,
                 size_t byte_size) {
  CHECK(src);
  FILE *file = fopen(filename.c_str(), "wb");
  CHECK(file);
  CHECK(fwrite(src, sizeof(char), byte_size, file) == byte_size);
  fclose(file);
}
// Append data into an existed file.
void AppendToFile(const std::string &filename,
                  const void *src,
                  size_t byte_size) {
  CHECK(src);
  FILE *fp = fopen(filename.c_str(), "ab");
  CHECK(fp) << "Unable to open file: " << filename;
  if (fwrite(reinterpret_cast<const char *>(src), 1, byte_size, fp) !=
      byte_size) {
    fclose(fp);
    LOG(FATAL) << "Write file error: " << filename;
  }
  fclose(fp);
}
/* ---------- Flatbuffers ---------- */
void SaveModelNaive(const std::string &model_file,
Y
Yan Chunwei 已提交
579
                    const Scope &exec_scope,
580 581 582
                    const cpp::ProgramDesc &cpp_prog) {
  /* 1. Save model to model.fbs */
  const std::string prog_path = model_file + ".nb";
583
  // Save meta_version(uint16) into file
584 585
  uint16_t meta_version = 1;
  WriteToFile(prog_path, &meta_version, sizeof(uint16_t));
586 587 588 589

  // Save lite_version(char[16]) into file
  const int paddle_version_length = 16 * sizeof(char);
  std::string paddle_version = version();
590
  AppendToFile(prog_path, paddle_version.c_str(), paddle_version_length);
591
  VLOG(4) << "paddle_version:" << paddle_version;
592

593 594
  fbs::ProgramDesc fbs_prog;
  TransformProgramDescCppToAny(cpp_prog, &fbs_prog);
595 596 597 598 599
  uint64_t topology_size = (fbs_prog.data()).size();
  AppendToFile(prog_path, &topology_size, sizeof(uint64_t));
  /* 1. Save model to model.fbs */
  AppendToFile(prog_path, (fbs_prog.data()).data(), topology_size);
  VLOG(4) << "save topology_size:" << topology_size;
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615

  /* 2. Get param names from cpp::ProgramDesc */
  auto &main_block_desc = *cpp_prog.GetBlock<cpp::BlockDesc>(0);
  // set unique_var_names to avoid saving shared params repeatedly
  std::set<std::string> unique_var_names;
  for (size_t i = 0; i < main_block_desc.VarsSize(); ++i) {
    auto &var = *main_block_desc.GetVar<cpp::VarDesc>(i);
    if (var.Name() == "feed" || var.Name() == "fetch" || !var.Persistable() ||
        unique_var_names.count(var.Name()) > 0)
      continue;
    unique_var_names.emplace(var.Name());
  }

  /* 3. Save combined params to params.fbs */
  fbs::CombinedParamsDesc params_prog;
  fbs::SetCombinedParamsWithScope(exec_scope, unique_var_names, &params_prog);
616 617
  AppendToFile(
      prog_path, (params_prog.data()).data(), (params_prog.data()).size());
618

619
  LOG(INFO) << "Save naive buffer model in '" << prog_path << " successfully";
620
}
621

Y
Yan Chunwei 已提交
622 623 624 625 626 627 628 629 630
template <typename T>
void SetTensorDataNaive(T *out, size_t size, const std::vector<T> &src) {
  CHECK(out);
  CHECK(size == src.size());
  for (size_t i = 0; i < size; ++i) {
    out[i] = src[i];
  }
}

Y
Yan Chunwei 已提交
631 632 633
void GetParamInfoNaive(const naive_buffer::ParamDesc &desc,
                       lite::Scope *scope,
                       const std::string &name) {
Y
Yan Chunwei 已提交
634
  CHECK(scope);
Y
Yan Chunwei 已提交
635 636 637
  CHECK_EQ(desc.Name(), name)
      << "Var name not equal: ParamDesc.name=" << desc.Name()
      << "vs filename=" << name;
Y
Yan Chunwei 已提交
638

Y
Yan Chunwei 已提交
639
  auto *tensor = scope->Var(name)->GetMutable<lite::Tensor>();
Y
Yan Chunwei 已提交
640 641 642 643 644 645 646 647 648 649 650 651 652 653

  VLOG(3) << "model version " << desc.ModelVersion();
  CHECK_EQ(desc.TensorVersion(), 0U) << "Only version 0 is supported";

  // Load LoD info
  auto *tgt_lod = tensor->mutable_lod();
  auto desc_lod = desc.LoD();
  tgt_lod->assign(desc_lod.begin(), desc_lod.end());

  // Load Dim info
  tensor->Resize(lite::DDim(desc.Dim()));

  // Load data
  switch (desc.GetDataType()) {
654
#define SET_TENSOR(data_type__, T, precision)                            \
Y
Yan Chunwei 已提交
655 656 657
  case VarDescAPI::VarDataType::data_type__:                             \
    SetTensorDataNaive<T>(                                               \
        tensor->mutable_data<T>(), tensor->data_size(), desc.Data<T>()); \
658
    tensor->set_precision(precision);                                    \
Y
Yan Chunwei 已提交
659 660
    break

661 662 663 664 665 666 667
    // SET_TENSOR(BOOL, bool, PRECISION(kBool));
    SET_TENSOR(FP32, float, PRECISION(kFloat));
    SET_TENSOR(INT8, int8_t, PRECISION(kInt8));
    SET_TENSOR(INT16, int16_t, PRECISION(kInt16));
    SET_TENSOR(INT32, int32_t, PRECISION(kInt32));
    SET_TENSOR(INT64, int64_t, PRECISION(kInt64));
#undef SET_TENSOR
Y
Yan Chunwei 已提交
668 669 670
    default:
      LOG(FATAL) << "unknown type";
  }
671
  tensor->set_persistable(true);
Y
Yan Chunwei 已提交
672 673
}

Y
Yan Chunwei 已提交
674 675 676 677 678 679 680 681 682 683 684 685 686
void LoadParamNaive(const std::string &path,
                    lite::Scope *scope,
                    const std::string &name) {
  // Load param
  naive_buffer::BinaryTable table;
  table.LoadFromFile(path);
  naive_buffer::proto::ParamDesc pt_desc(&table);
  pt_desc.Load();
  naive_buffer::ParamDesc desc(&pt_desc);
  GetParamInfoNaive(desc, scope, name);
}

void LoadCombinedParamsNaive(const std::string &path,
687
                             const uint64_t &offset,
Y
Yan Chunwei 已提交
688
                             lite::Scope *scope,
689 690
                             const cpp::ProgramDesc &cpp_prog,
                             bool params_from_memory) {
Y
Yan Chunwei 已提交
691
  naive_buffer::BinaryTable table;
692
  if (params_from_memory) {
693
    table.LoadFromMemory(path.c_str() + offset, path.length() - offset);
694
  } else {
695
    table.LoadFromFile(path, offset, 0);
696
  }
Y
Yan Chunwei 已提交
697 698 699 700 701 702 703 704 705 706 707 708
  naive_buffer::proto::CombinedParamsDesc pt_desc(&table);
  pt_desc.Load();
  naive_buffer::CombinedParamsDesc desc(&pt_desc);

  std::set<std::string> param_names;
  for (size_t i = 0; i < desc.ParamsSize(); ++i) {
    naive_buffer::ParamDesc param_desc(desc.GetParam(i));
    GetParamInfoNaive(param_desc, scope, param_desc.Name());
    param_names.insert(param_desc.Name());
  }

  // Check all params loaded
709
  auto &prog = cpp_prog;
Y
Yan Chunwei 已提交
710 711 712 713 714 715 716 717 718
  auto &main_block_desc = *prog.GetBlock<cpp::BlockDesc>(0);
  for (size_t i = 0; i < main_block_desc.VarsSize(); ++i) {
    auto &var = *main_block_desc.GetVar<cpp::VarDesc>(i);
    if (var.Name() == "feed" || var.Name() == "fetch" || !var.Persistable())
      continue;
    CHECK(param_names.count(var.Name())) << "Persistable var[" << var.Name()
                                         << "] not found";
  }
}
719

720 721 722 723
///////////////////////////////////////////////////////////////////////////////
/* Old Method of loading and saving model, before V2.3.0                     */
/* Warning: this is an old inference and will be abandened in release/v3.0.0 */
///////////////////////////////////////////////////////////////////////////////
Y
Yan Chunwei 已提交
724 725
void LoadModelNaive(const std::string &model_dir,
                    Scope *scope,
Y
Yan Chunwei 已提交
726 727
                    cpp::ProgramDesc *cpp_prog,
                    bool combined) {
Y
Yan Chunwei 已提交
728 729 730 731
  CHECK(cpp_prog);
  CHECK(scope);
  cpp_prog->ClearBlocks();

732 733 734 735 736 737 738
  LOG(WARNING)
      << "WARNING: MobileConfig::set_model_dir and "
         "MobileConfig::set_model_buffer are deprecated APIs "
         "and will be removed in latter release. \n"
         "    MobileConfig::set_model_from_file(const std::string& model_file)"
         " and MobileConfig::set_model_from_buffer(const std::string& "
         "model_buffer) are recommended.";
Y
Yan Chunwei 已提交
739
  // Load model
Y
Yan Chunwei 已提交
740
  const std::string prog_path = model_dir + "/__model__.nb";
Y
Yan Chunwei 已提交
741 742 743 744 745 746 747 748 749 750 751
  naive_buffer::BinaryTable table;
  table.LoadFromFile(prog_path);
  naive_buffer::proto::ProgramDesc nb_proto_prog(&table);
  nb_proto_prog.Load();
  naive_buffer::ProgramDesc nb_prog(&nb_proto_prog);

  // Transform to cpp::ProgramDesc
  TransformProgramDescAnyToCpp(nb_prog, cpp_prog);

  // Load Params
  // NOTE: Only main block be used now.
Y
Yan Chunwei 已提交
752 753
  if (combined) {
    const std::string combined_params_path = model_dir + "/param.nb";
754
    LoadCombinedParamsNaive(combined_params_path, 0, scope, *cpp_prog, false);
Y
Yan Chunwei 已提交
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
  } else {
    auto &prog = *cpp_prog;
    auto &main_block_desc = *prog.GetBlock<cpp::BlockDesc>(0);
    for (size_t i = 0; i < main_block_desc.VarsSize(); ++i) {
      auto &var = *main_block_desc.GetVar<cpp::VarDesc>(i);
      if (var.Name() == "feed" || var.Name() == "fetch" || !var.Persistable())
        continue;

      std::string file_path = model_dir + "/" + var.Name() + ".nb";
      VLOG(4) << "reading weight " << var.Name();

      switch (var.GetType()) {
        case VarDescAPI::Type::LOD_TENSOR:
          LoadParamNaive(file_path, scope, var.Name());
          break;
        default:
          CHECK(false) << "unknown weight type";
      }
Y
Yan Chunwei 已提交
773 774 775 776 777 778
    }
  }

  VLOG(4) << "Load naive buffer model in '" << model_dir << "' successfully";
}

779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
void LoadModelNaiveFromMemory(const std::string &model_buffer,
                              const std::string &param_buffer,
                              Scope *scope,
                              cpp::ProgramDesc *cpp_prog) {
  CHECK(cpp_prog);
  CHECK(scope);
  cpp_prog->ClearBlocks();

  // Load model
  naive_buffer::BinaryTable table;
  table.LoadFromMemory(model_buffer.c_str(), model_buffer.length());

  naive_buffer::proto::ProgramDesc nb_proto_prog(&table);
  nb_proto_prog.Load();
  naive_buffer::ProgramDesc nb_prog(&nb_proto_prog);

  // Transform to cpp::ProgramDesc
  TransformProgramDescAnyToCpp(nb_prog, cpp_prog);

  // Load Params
  LoadCombinedParamsNaive(param_buffer, 0, scope, *cpp_prog, true);

  VLOG(4) << "Load model from naive buffer memory successfully";
}
803
#endif  // LITE_ON_TINY_PUBLISH
804 805 806 807 808 809 810 811
//////////////////////////////////////////////////////////////////////

// usage: LoadModelNaiveFromFile is used for loading model from file.
template <typename T>
void ReadModelDataFromFile(T *data,
                           const std::string &prog_path,
                           uint64_t *offset,
                           const uint64_t &size) {
812 813
  std::vector<char> prog_data = lite::fbs::LoadFile(prog_path, *offset, size);
  memcpy(data, prog_data.data(), size);
814 815
  *offset = *offset + size;
}
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
/*
 * Binary structure of naive_buffer model: model.nb
 * ----------------------------------------------------------
 * |       |    PART         |   Precision |   Length(byte) |
 * |   1   |  meta_version   |   uint16_t  |       2        |
 * |   2   |  opt_version    |   char[16]  |      16        |
 * |   3   |  topo_size      |   uint64_t  |       8        |
 * |   4   |  topo_data      |   char[]    | topo_size byte |
 * |   5   |  param_data     |   char[]    |                |
 * ----------------------------------------------------------
 *  Meaning of each part:
 *      meta_version: meata_version, 0 default.
 *      opt_version:  lite_version of opt tool that transformed this model.
 *      topo_size:    length of `topo_data`.
 *      topo_data:    contains model's topology data.
 *      param_data:   contains model's params data.
*/

void LoadModelNaiveFromFile(const std::string &filename,
                            Scope *scope,
                            cpp::ProgramDesc *cpp_prog) {
  CHECK(cpp_prog);
  CHECK(scope);
  // ModelFile
  const std::string prog_path = filename;

  // Offset
  uint64_t offset = 0;

  // (1)get meta version
  uint16_t meta_version;
  ReadModelDataFromFile<uint16_t>(
      &meta_version, prog_path, &offset, sizeof(uint16_t));
  VLOG(4) << "Meta_version:" << meta_version;

851 852
  switch (meta_version) {
    case 0:
853
#ifndef LITE_ON_TINY_PUBLISH
854
      LoadModelNaiveV0FromFile(filename, scope, cpp_prog);
855 856 857
#else
      LOG(FATAL) << "Error, this model file is not supported.";
#endif
858 859 860 861 862 863 864 865 866
      break;
    case 1:
      LoadModelFbsFromFile(filename, scope, cpp_prog);
      break;
    default:
      LOG(FATAL) << "Error, this model file is not supported.";
      break;
  }
}
867
#ifndef LITE_ON_TINY_PUBLISH
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
void LoadModelNaiveV0FromFile(const std::string &filename,
                              Scope *scope,
                              cpp::ProgramDesc *cpp_prog) {
  CHECK(cpp_prog);
  CHECK(scope);
  cpp_prog->ClearBlocks();
  // ModelFile
  const std::string prog_path = filename;

  // Offset
  uint64_t offset = 0;

  // (1)get meta version
  uint16_t meta_version;
  ReadModelDataFromFile<uint16_t>(
      &meta_version, prog_path, &offset, sizeof(uint16_t));
  VLOG(4) << "Meta_version:" << meta_version;

886 887
  // (2)get opt version
  char opt_version[16];
888
  const uint64_t opt_version_length = 16 * sizeof(char);
889
  ReadModelDataFromFile<char>(
890
      opt_version, prog_path, &offset, opt_version_length);
891
  VLOG(4) << "Opt_version:" << static_cast<const char *>(opt_version);
892

893 894 895 896
  // check version, opt's version should be consistent with current Paddle-Lite
  // version.
  const std::string paddle_version = version();
  const std::string opt_version_str = opt_version;
H
huzhiqiang 已提交
897
  if (paddle_version != opt_version_str) {
898 899 900
    LOG(WARNING) << "warning: the version of opt that transformed this model "
                    "is not consistent with current Paddle-Lite version."
                    "\n      version of opt:"
901
                 << static_cast<const char *>(opt_version)
902 903 904
                 << "\n      version of current Paddle-Lite:" << paddle_version;
  }

905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
  // (3)get topo_size
  uint64_t topo_size;
  ReadModelDataFromFile<uint64_t>(
      &topo_size, prog_path, &offset, sizeof(uint64_t));

  // (4)get topo data
  naive_buffer::BinaryTable topo_table;
  topo_table.LoadFromFile(prog_path, offset, topo_size);
  offset = offset + topo_size;
  // transform topo_data into cpp::ProgramDesc
  naive_buffer::proto::ProgramDesc nb_proto_prog(&topo_table);
  nb_proto_prog.Load();
  naive_buffer::ProgramDesc nb_prog(&nb_proto_prog);
  TransformProgramDescAnyToCpp(nb_prog, cpp_prog);

  // (5)Load Params
  LoadCombinedParamsNaive(prog_path, offset, scope, *cpp_prog, false);

  VLOG(4) << "Load naive buffer model in '" << filename << "' successfully";
}
925
#endif  // LITE_ON_TINY_PUBLISH
926 927 928
void LoadModelFbsFromFile(const std::string &filename,
                          Scope *scope,
                          cpp::ProgramDesc *cpp_prog) {
929 930
  CHECK(cpp_prog);
  CHECK(scope);
931
  CHECK_EQ(cpp_prog->BlocksSize(), 0);
932 933
  // Offset
  uint64_t offset = sizeof(uint16_t);
934

935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
  // get opt version
  char opt_version[16];
  const uint64_t opt_version_length = 16 * sizeof(char);
  ReadModelDataFromFile<char>(
      opt_version, filename, &offset, opt_version_length);
  VLOG(4) << "Opt_version:" << static_cast<const char *>(opt_version);
  // check version, opt's version should be consistent with current Paddle-Lite
  // version.
  const std::string paddle_version = version();
  const std::string opt_version_str = opt_version;
  if (paddle_version != opt_version_str) {
    LOG(WARNING) << "warning: the version of opt that transformed this model "
                    "is not consistent with current Paddle-Lite version."
                    "\n      version of opt:"
                 << static_cast<const char *>(opt_version)
                 << "\n      version of current Paddle-Lite:" << paddle_version;
  }
  // (3)get topo_size
  uint64_t topo_size;
  ReadModelDataFromFile<uint64_t>(
      &topo_size, filename, &offset, sizeof(uint64_t));
956

957 958 959 960 961 962 963 964 965 966
#ifdef LITE_ON_FLATBUFFERS_DESC_VIEW
  cpp_prog->Init(fbs::LoadFile(filename, offset, topo_size));
#elif LITE_ON_TINY_PUBLISH
  LOG(FATAL) << "Since no data structure of Flatbuffers has been constructed, "
                "the model cannot be loaded.";
#else
  fbs::ProgramDesc program(fbs::LoadFile(filename, offset, topo_size));
  TransformProgramDescAnyToCpp(program, cpp_prog);
#endif
  offset = offset + topo_size;
967

968 969 970
  /* 2. Load scope from params.fbs */
  fbs::CombinedParamsDescView params(fbs::LoadFile(filename, offset));
  fbs::SetScopeWithCombinedParams(scope, params);
971

972
  VLOG(4) << "Load naive buffer model in '" << filename << "' successfully";
973 974 975 976 977 978 979 980
}

// usage: LoadModelNaiveFromMemory is used for loading naive model from memory
template <typename T>
void ReadModelDataFromBuffer(T *data,
                             const std::string &model_buffer,
                             uint64_t *offset,
                             const uint64_t &size) {
981
  memcpy(data, model_buffer.c_str() + *offset, size);
982 983
  *offset = *offset + size;
}
984

985 986 987 988 989 990 991 992 993 994 995 996 997
void LoadModelNaiveFromMemory(const std::string &model_buffer,
                              Scope *scope,
                              cpp::ProgramDesc *cpp_prog) {
  CHECK(cpp_prog);
  CHECK(scope);
  cpp_prog->ClearBlocks();

  uint64_t offset = 0;
  // (1)get meta version
  uint16_t meta_version;
  ReadModelDataFromBuffer<uint16_t>(
      &meta_version, model_buffer, &offset, sizeof(uint16_t));
  VLOG(4) << "Meta_version:" << meta_version;
998 999
  switch (meta_version) {
    case 0:
1000
#ifndef LITE_ON_TINY_PUBLISH
1001
      LoadModelNaiveV0FromMemory(model_buffer, scope, cpp_prog);
1002
#else
1003 1004 1005
      LOG(FATAL) << "Paddle-Lite v2.7 has upgraded the naive-buffer model "
                    "format. Please use the OPT to generate a new model. "
                    "Thanks!";
1006
#endif
1007 1008 1009 1010 1011
      break;
    case 1:
      LoadModelNaiveV1FromMemory(model_buffer, scope, cpp_prog);
      break;
    default:
1012 1013
      LOG(FATAL) << "The model format cannot be recognized. Please make sure "
                    "you use the correct interface and model file.";
1014 1015 1016
      break;
  }
}
1017
#ifndef LITE_ON_TINY_PUBLISH
1018 1019 1020 1021 1022
void LoadModelNaiveV0FromMemory(const std::string &model_buffer,
                                Scope *scope,
                                cpp::ProgramDesc *cpp_prog) {
  // Offset
  uint64_t offset = sizeof(uint16_t);
1023 1024 1025 1026 1027 1028

  // (2)get opt version
  char opt_version[16];
  const uint64_t paddle_version_length = 16 * sizeof(char);
  ReadModelDataFromBuffer<char>(
      opt_version, model_buffer, &offset, paddle_version_length);
1029
  VLOG(4) << "Opt_version:" << static_cast<const char *>(opt_version);
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049

  // (3)get topo_size and topo_data
  uint64_t topo_size;
  ReadModelDataFromBuffer<uint64_t>(
      &topo_size, model_buffer, &offset, sizeof(uint64_t));
  naive_buffer::BinaryTable table;
  table.LoadFromMemory(model_buffer.c_str() + offset, topo_size);
  offset = offset + topo_size;

  naive_buffer::proto::ProgramDesc nb_proto_prog(&table);
  nb_proto_prog.Load();
  naive_buffer::ProgramDesc nb_prog(&nb_proto_prog);

  // Transform to cpp::ProgramDesc
  TransformProgramDescAnyToCpp(nb_prog, cpp_prog);

  // Load Params
  // NOTE: Only main block be used now.
  // only combined Params are supported in Loading Model from memory
  LoadCombinedParamsNaive(model_buffer, offset, scope, *cpp_prog, true);
1050 1051 1052

  VLOG(4) << "Load model from naive buffer memory successfully";
}
1053
#endif
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
///////////////////////////////////////////////////////////////////
// Meta_version=1
///////////////////////////////////////////////////////////////////
void LoadModelNaiveV1FromMemory(const std::string &model_buffer,
                                Scope *scope,
                                cpp::ProgramDesc *cpp_prog) {
  // Offset
  uint64_t offset = sizeof(uint16_t);

  // (2)get opt version
  char opt_version[16];
  const uint64_t paddle_version_length = 16 * sizeof(char);
  ReadModelDataFromBuffer<char>(
      opt_version, model_buffer, &offset, paddle_version_length);
  VLOG(4) << "Opt_version:" << static_cast<const char *>(opt_version);

  // (3)get prog_size and prog_data
  uint64_t prog_size;
  ReadModelDataFromBuffer<uint64_t>(
      &prog_size, model_buffer, &offset, sizeof(uint64_t));
  VLOG(4) << "prog_size:" << prog_size;

  std::vector<char> prog_data(prog_size);
  memcpy(prog_data.data(), model_buffer.c_str() + offset, prog_size);
#ifdef LITE_ON_FLATBUFFERS_DESC_VIEW
  cpp_prog->Init(prog_data);
#elif LITE_ON_TINY_PUBLISH
  LOG(FATAL) << "Since no data structure of Flatbuffers has been constructed, "
                "the model cannot be loaded.";
#else
  fbs::ProgramDesc program(prog_data);
  TransformProgramDescAnyToCpp(program, cpp_prog);
#endif
  offset = offset + prog_size;
  VLOG(4) << "param_size:" << model_buffer.length() - offset;

  std::vector<char> params_data(model_buffer.length() - offset);
  memcpy(params_data.data(),
         model_buffer.c_str() + offset,
         model_buffer.length() - offset);

  fbs::CombinedParamsDescView params(params_data);
  fbs::SetScopeWithCombinedParams(scope, params);

  VLOG(4) << "Load model from naive buffer memory successfully";
}

Y
Yan Chunwei 已提交
1101 1102
}  // namespace lite
}  // namespace paddle