async_executor.cc 7.6 KB
Newer Older
W
wangguibao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* Copyright (c) 2016 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 "paddle/fluid/framework/async_executor.h"
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
W
wangguibao 已提交
19 20
#include <sys/types.h>
#include <sys/stat.h>
W
wangguibao 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#include <unistd.h>
#include <fstream>
#include <iostream>
#include <map>
#include <algorithm>
#include "google/protobuf/message.h"
#include "google/protobuf/text_format.h"
#include "google/protobuf/io/zero_copy_stream_impl.h"

#include "gflags/gflags.h"
#include "paddle/fluid/framework/feed_fetch_method.h"
#include "paddle/fluid/framework/feed_fetch_type.h"
#include "paddle/fluid/framework/lod_rank_table.h"
#include "paddle/fluid/framework/lod_tensor_array.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/reader.h"
#include "paddle/fluid/platform/place.h"
W
wangguibao 已提交
38
#include "paddle/fluid/inference/io.h"
W
wangguibao 已提交
39 40
#include "paddle/fluid/framework/executor_thread_worker.h"
#include "paddle/fluid/framework/data_feed_factory.h"
W
wangguibao 已提交
41 42 43 44
#include "paddle/fluid/pybind/pybind.h"

namespace paddle {
namespace framework {
45

W
wangguibao 已提交
46
static void ReadBinaryFile(const std::string& filename,
W
wangguibao 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60
                             std::string* content) {
  std::string &contents = *content;
  std::ifstream fin(filename, std::ios::in | std::ios::binary);
  if (!fin.good()) {
    LOG(ERROR) << "Cannot open file " << filename.c_str();
  }
  fin.seekg(0, std::ios::end);
  contents.clear();
  contents.resize(fin.tellg());
  fin.seekg(0, std::ios::beg);
  fin.read(&contents[0], contents.size());
  fin.close();
}

W
wangguibao 已提交
61
static void SaveModel(
W
wangguibao 已提交
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
    const std::unique_ptr<ProgramDesc> & main_program,
    Scope* scope,
    const std::vector<std::string> & param_names,
    const std::string & model_name,
    bool save_combine) {
  auto place = platform::CPUPlace();
  const BlockDesc& global_block = main_program->Block(0);
  std::vector<std::string> paralist;

  for (auto* var : global_block.AllVars()) {
    bool is_model_param = false;
    for (auto param_name : param_names) {
      if (var->Name() == param_name) {
        is_model_param = true;
        break;
      }
    }

    if (!is_model_param)  continue;

    if (!save_combine) {
      LOG(ERROR) << "model var name: " << var->Name().c_str();

      paddle::framework::AttributeMap attrs;
      attrs.insert({"file_path", model_name + "/" + var->Name()});
      auto save_op = paddle::framework::OpRegistry::CreateOp(
                                                      "save",
                                                      {{"X", {var->Name()}}},
                                                      {},
                                                      attrs);
      save_op->Run(*scope, place);
    } else {
      paralist.push_back(var->Name());
    }
  }

  if (save_combine) {
    std::sort(paralist.begin(), paralist.end());
    paddle::framework::AttributeMap attrs;
    attrs.insert({"file_path", model_name});
    auto save_op = paddle::framework::OpRegistry::CreateOp(
                                                      "save_combine",
                                                      {{"X", paralist}},
                                                      {},
                                                      attrs);
107

W
wangguibao 已提交
108 109
    save_op->Run(*scope, place);
  }
W
wangguibao 已提交
110
}   // end SaveModel
W
wangguibao 已提交
111

W
wangguibao 已提交
112 113
AsyncExecutor::AsyncExecutor(Scope& scope, const platform::Place& place)
    : root_scope_(scope), place_(place) {}
W
wangguibao 已提交
114

W
wangguibao 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127
void AsyncExecutor::CreateThreads(
    ExecutorThreadWorker* worker,
    const ProgramDesc& main_program,
    const std::shared_ptr<DataFeed>& reader,
    const std::vector<std::string>& fetch_var_names,
    Scope& root_scope,
    const int thread_index) {
  worker->SetThreadId(thread_index);
  worker->SetRootScope(&root_scope);
  worker->CreateThreadResource(main_program, place_);
  worker->SetDataFeed(reader);
  worker->SetFetchVarNames(fetch_var_names);
  worker->BindingDataFeedMemory();
W
wangguibao 已提交
128 129
}

W
wangguibao 已提交
130 131 132 133
void AsyncExecutor::CheckFiles(
    const std::vector<std::string>& files) {
  // function for user to check file formats
  // should be exposed to users
W
wangguibao 已提交
134 135
}

W
wangguibao 已提交
136
void AsyncExecutor::SetModelPrefix(const std::string& model_prefix) {
W
wangguibao 已提交
137
  model_prefix_ = model_prefix;
W
wangguibao 已提交
138 139
}

W
wangguibao 已提交
140 141
std::vector<float> AsyncExecutor::RunFromFile(
    const ProgramDesc& main_program,
142
    const std::string& data_feed_desc_str,
W
wangguibao 已提交
143 144 145 146
    const std::vector<std::string>& filelist,
    const int thread_num,
    const std::vector<std::string>& fetch_var_names) {
  std::vector<std::thread> threads;
W
wangguibao 已提交
147

148 149
  DataFeedDesc data_feed_desc;
  google::protobuf::TextFormat::ParseFromString(data_feed_desc_str, &data_feed_desc);
W
wangguibao 已提交
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
  /*
    readerDesc: protobuf description for reader initlization
    argument: class_name, batch_size, use_slot, queue_size, buffer_size, padding_index
    
    reader: 
    1) each thread has a reader, reader will read input data and 
    put it into input queue
    2) each reader has a Next() iterface, that can fetch an instance
    from the input queue
   */
  // todo: should be factory method for creating datafeed
  std::vector<std::shared_ptr<DataFeed> > readers;
  readers.resize(thread_num);
  for (unsigned int i = 0; i < readers.size(); ++i) {
    readers[i] = DataFeedFactory::CreateDataFeed(data_feed_desc.name());
W
wangguibao 已提交
165 166
  }

W
wangguibao 已提交
167 168 169 170
  std::vector<std::shared_ptr<ExecutorThreadWorker> > workers;
  workers.resize(thread_num);
  for (auto& worker : workers) {
    worker.reset(new ExecutorThreadWorker);
W
wangguibao 已提交
171 172
  }

W
wangguibao 已提交
173 174 175 176
  // prepare thread resource here
  for (int thidx = 0; thidx < thread_num; ++thidx) {
    CreateThreads(workers[thidx].get(), main_program,
                  readers[thidx], fetch_var_names, root_scope_, thidx);
W
wangguibao 已提交
177 178
  }

W
wangguibao 已提交
179 180 181 182
  // start executing ops in multiple threads
  for (int thidx = 0; thidx < thread_num; ++thidx) {
    threads.push_back(std::thread(&ExecutorThreadWorker::TrainFiles,
                                  workers[thidx].get()));
W
wangguibao 已提交
183 184
  }

W
wangguibao 已提交
185
  for (auto& th : threads) {
W
wangguibao 已提交
186 187
    th.join();
  }
188

W
wangguibao 已提交
189 190
  std::vector<float> fetch_values;
  fetch_values.resize(fetch_var_names.size(), 0);
191

W
wangguibao 已提交
192 193 194 195
  std::vector<std::vector<float>*> fetch_value_vectors;
  fetch_value_vectors.resize(thread_num);
  for (int i = 0; i < thread_num; ++i) {
    fetch_value_vectors[i] = &workers[i]->GetFetchValues();
196 197
  }

W
wangguibao 已提交
198
  for (unsigned int i = 0; i < fetch_var_names.size(); ++i) {
199
    float value = 0.0;
W
wangguibao 已提交
200 201
    for (int j = 0; j < thread_num; ++j) {
      value += fetch_value_vectors[j]->at(i);
202
    }
W
wangguibao 已提交
203 204
    value /= thread_num;
    fetch_values[i] = value;
205 206
  }

W
wangguibao 已提交
207
  return fetch_values;
W
wangguibao 已提交
208 209
}

W
wangguibao 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
void AsyncExecutor::LoadInitModel() {
  auto place = paddle::platform::CPUPlace();
  auto* executor = new paddle::framework::Executor(place);

  std::string init_prog_file = model_path_ + "/" + init_prog_file_;
  std::string init_model_file = model_path_ + "/" + init_model_file_;

  struct stat stat_buf;

  if (stat(init_prog_file.c_str(), &stat_buf) == 0 &&
      S_ISREG(stat_buf.st_mode) &&
      stat(init_model_file.c_str(), &stat_buf) == 0 &&
      S_ISREG(stat_buf.st_mode)) {
    paddle::inference::Load(executor,
                          GetRootScope(),
                          model_path_ + "/" + init_prog_file_,
                          model_path_ + "/" + init_model_file_);
  }
}
}   // einit_modelnd namespace framework
W
wangguibao 已提交
230 231 232
}   // end namespace paddle

/* vim: set expandtab ts=2 sw=2 sts=2 tw=100: */