io.cc 7.1 KB
Newer Older
1
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14

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

Y
Yi Wang 已提交
15
#include "paddle/fluid/inference/io.h"
16

17
#include <algorithm>
18
#include <fstream>
19
#include <vector>
Y
Yi Wang 已提交
20 21
#include "paddle/fluid/framework/block_desc.h"
#include "paddle/fluid/framework/feed_fetch_type.h"
22
#include "paddle/fluid/framework/op_registry.h"
X
version  
Xin Pan 已提交
23
#include "paddle/fluid/framework/version.h"
T
tensor-tang 已提交
24
#include "paddle/fluid/platform/cpu_helper.h"
25
#include "paddle/fluid/pybind/pybind.h"
26

W
wanghaoshuang 已提交
27
DEFINE_string(devices, "", "The devices to be used which is joined by comma.");
28 29
DEFINE_int32(math_num_threads, 1,
             "Number of threads used to run math functions.");
30

31
namespace paddle {
32
namespace inference {
33

34 35
void Init(const std::vector<std::string> argv) {
  framework::InitGflags(argv);
T
tensor-tang 已提交
36
  platform::SetNumThreads(FLAGS_math_num_threads);
37 38 39 40 41 42 43
  // init devices
  std::vector<int> devices;
  std::string token;
  std::istringstream tokenStream(FLAGS_devices);
  while (std::getline(tokenStream, token, ',')) {
    devices.push_back(std::stoi(token));
  }
44
  framework::InitDevices(devices);
45
}
46

47
void ReadBinaryFile(const std::string& filename, std::string* contents) {
48
  std::ifstream fin(filename, std::ios::in | std::ios::binary);
49 50 51
  PADDLE_ENFORCE_EQ(
      fin.is_open(), true,
      platform::errors::Unavailable("Failed to open file %s.", filename));
52
  fin.seekg(0, std::ios::end);
53 54
  contents->clear();
  contents->resize(fin.tellg());
55
  fin.seekg(0, std::ios::beg);
56
  fin.read(&(contents->at(0)), contents->size());
57
  fin.close();
58 59
}

L
Liu Yiqun 已提交
60 61
bool IsPersistable(const framework::VarDesc* var) {
  if (var->Persistable() &&
62
      var->GetType() != framework::proto::VarType::FEED_MINIBATCH &&
63 64
      var->GetType() != framework::proto::VarType::FETCH_LIST &&
      var->GetType() != framework::proto::VarType::RAW) {
L
Liu Yiqun 已提交
65
    return true;
66 67 68 69
  }
  return false;
}

70
void LoadPersistables(framework::Executor* executor, framework::Scope* scope,
71
                      const framework::ProgramDesc& main_program,
72
                      const std::string& dirname,
T
Tao Luo 已提交
73
                      const std::string& param_filename,
T
Tao Luo 已提交
74
                      bool model_from_memory = false) {
K
kexinzhao 已提交
75
  const framework::BlockDesc& global_block = main_program.Block(0);
76

77 78
  framework::ProgramDesc* load_program = new framework::ProgramDesc();
  framework::BlockDesc* load_block = load_program->MutableBlock(0);
79 80
  std::vector<std::string> paramlist;

K
kexinzhao 已提交
81
  for (auto* var : global_block.AllVars()) {
L
Liu Yiqun 已提交
82
    if (IsPersistable(var)) {
83
      VLOG(4) << "persistable variable's name: " << var->Name();
84 85

      framework::VarDesc* new_var = load_block->Var(var->Name());
F
fengjiayi 已提交
86
      new_var->SetShape(var->GetShape());
87 88
      new_var->SetDataType(var->GetDataType());
      new_var->SetType(var->GetType());
89 90 91 92 93 94

      if (var->GetType() !=
          framework::proto::VarType::Type::VarType_Type_SELECTED_ROWS) {
        new_var->SetLoDLevel(var->GetLoDLevel());
      }

95 96
      new_var->SetPersistable(true);

97 98 99 100 101 102 103 104 105 106
      if (!param_filename.empty()) {
        paramlist.push_back(new_var->Name());
      } else {
        // append_op
        framework::OpDesc* op = load_block->AppendOp();
        op->SetType("load");
        op->SetOutput("Out", {new_var->Name()});
        op->SetAttr("file_path", {dirname + "/" + new_var->Name()});
        op->CheckAttrs();
      }
107 108
    }
  }
109 110 111 112 113 114 115 116 117

  if (!param_filename.empty()) {
    // sort paramlist to have consistent ordering
    std::sort(paramlist.begin(), paramlist.end());
    // append just the load_combine op
    framework::OpDesc* op = load_block->AppendOp();
    op->SetType("load_combine");
    op->SetOutput("Out", paramlist);
    op->SetAttr("file_path", {param_filename});
T
Tao Luo 已提交
118
    op->SetAttr("model_from_memory", {model_from_memory});
119 120 121
    op->CheckAttrs();
  }

122
  executor->Run(*load_program, scope, 0, true, true);
123

124
  delete load_program;
125
}
126

127 128
std::unique_ptr<framework::ProgramDesc> Load(framework::Executor* executor,
                                             framework::Scope* scope,
K
kexinzhao 已提交
129
                                             const std::string& dirname) {
130 131
  std::string model_filename = dirname + "/__model__";
  std::string program_desc_str;
M
minqiyang 已提交
132
  VLOG(3) << "loading model from " << model_filename;
133
  ReadBinaryFile(model_filename, &program_desc_str);
134 135 136

  std::unique_ptr<framework::ProgramDesc> main_program(
      new framework::ProgramDesc(program_desc_str));
137 138 139 140
  PADDLE_ENFORCE_EQ(
      framework::IsProgramVersionSupported(main_program->Version()), true,
      platform::errors::Unavailable("Model version %ld is not supported.",
                                    main_program->Version()));
141

T
tianshuo78520a 已提交
142
  // model_from_memory is false in separate parameters.
T
Tao Luo 已提交
143
  LoadPersistables(executor, scope, *main_program, dirname, "",
T
Tao Luo 已提交
144
                   false /* model_from_memory */);
145 146 147
  return main_program;
}

T
Tao Luo 已提交
148 149 150
std::unique_ptr<framework::ProgramDesc> Load(
    framework::Executor* executor, framework::Scope* scope,
    const std::string& prog_filename, const std::string& param_filename) {
151
  std::string program_desc_str;
T
Tao Luo 已提交
152
  ReadBinaryFile(prog_filename, &program_desc_str);
153

K
kexinzhao 已提交
154 155
  std::unique_ptr<framework::ProgramDesc> main_program(
      new framework::ProgramDesc(program_desc_str));
156 157 158 159
  PADDLE_ENFORCE_EQ(
      framework::IsProgramVersionSupported(main_program->Version()), true,
      platform::errors::Unavailable("Model version %ld is not supported.",
                                    main_program->Version()));
160

T
Tao Luo 已提交
161
  LoadPersistables(executor, scope, *main_program, "", param_filename,
T
Tao Luo 已提交
162
                   false /* model_from_memory */);
163 164 165
  return main_program;
}

T
Tao Luo 已提交
166
std::unique_ptr<framework::ProgramDesc> LoadFromMemory(
T
Tao Luo 已提交
167
    framework::Executor* executor, framework::Scope* scope,
T
Tao Luo 已提交
168 169 170
    const std::string& prog_buffer, const std::string& param_buffer) {
  std::unique_ptr<framework::ProgramDesc> main_program(
      new framework::ProgramDesc(prog_buffer));
171 172 173 174
  PADDLE_ENFORCE_EQ(
      framework::IsProgramVersionSupported(main_program->Version()), true,
      platform::errors::Unavailable("Model version %ld is not supported.",
                                    main_program->Version()));
T
Tao Luo 已提交
175 176 177 178

  LoadPersistables(executor, scope, *main_program, "", param_buffer,
                   true /* model_filename */);
  return main_program;
T
Tao Luo 已提交
179 180
}

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
void SaveVars(const framework::Scope& scope,
              const std::vector<std::string>& vars, const std::string& dirname,
              bool predicate) {
  framework::ProgramDesc prog;
  auto* block = prog.MutableBlock(0);
  auto* op = block->AppendOp();
  op->SetType("save_combine");
  op->SetInput("X", vars);
  op->SetAttr("file_path", dirname + "/param");
  op->CheckAttrs();

  platform::CPUPlace place;
  framework::Executor exe(place);
  exe.Run(prog, const_cast<framework::Scope*>(&scope), 0, true, true);
}

197
}  // namespace inference
198
}  // namespace paddle