dist_multi_trainer.cc 6.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* 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 <string>
#include <vector>
17
#include "io/fs.h"
18
#include "paddle/fluid/framework/data_feed_factory.h"
D
dongdaxiang 已提交
19
#include "paddle/fluid/framework/data_set.h"
20 21 22 23 24 25
#include "paddle/fluid/framework/device_worker_factory.h"
#include "paddle/fluid/framework/trainer.h"

namespace paddle {
namespace framework {

26 27
void DistMultiTrainer::Initialize(const TrainerDesc &trainer_desc,
                                  Dataset *dataset) {
28
  thread_num_ = trainer_desc.thread_num();
29
  SetDataset(dataset);
D
dongdaxiang 已提交
30

31 32 33 34 35 36 37
  dump_fields_path_ = trainer_desc.dump_fields_path();
  dump_converter_ = trainer_desc.dump_converter();
  need_dump_field_ = false;
  if (trainer_desc.dump_fields_size() != 0 && dump_fields_path_ != "") {
    need_dump_field_ = true;
  }
  if (need_dump_field_) {
38
    auto &file_list = dataset->GetFileList();
39 40 41 42 43
    if (file_list.size() == 0) {
      need_dump_field_ = false;
    }
  }
  mpi_rank_ = trainer_desc.mpi_rank() / 2;
T
Thunderbrook 已提交
44 45
  mpi_size_ = trainer_desc.mpi_size() / 2;
  dump_file_num_ = trainer_desc.dump_file_num();
46
  const std::vector<paddle::framework::DataFeed *> readers =
47
      dataset->GetReaders();
48

49 50
  thread_num_ = readers.size();
  workers_.resize(thread_num_);
51 52 53 54 55
  for (int i = 0; i < trainer_desc.downpour_param().stat_var_names_size();
       i++) {
    need_merge_var_names_.push_back(
        trainer_desc.downpour_param().stat_var_names(i));
  }
56

57 58 59 60
  for (int i = 0; i < thread_num_; ++i) {
    workers_[i] = DeviceWorkerFactory::CreateDeviceWorker(
        trainer_desc.device_worker_name());
    workers_[i]->SetDeviceIndex(i);
D
dongdaxiang 已提交
61
    workers_[i]->SetDataFeed(readers[i]);
62
    workers_[i]->Initialize(trainer_desc);
63
    workers_[i]->SetNeedDump(need_dump_field_);
64 65
  }

D
dongdaxiang 已提交
66
  VLOG(3) << "going to initialize pull dense worker";
67 68
  pull_dense_worker_ = PullDenseWorker::GetInstance();
  pull_dense_worker_->Initialize(trainer_desc);
D
dongdaxiang 已提交
69
  VLOG(3) << "initialize pull dense worker";
70
  SetDebug(trainer_desc.debug());
71 72
}

T
Thunderbrook 已提交
73
void DistMultiTrainer::DumpWork(int tid) {
74
#ifdef _LINUX
T
Thunderbrook 已提交
75 76 77 78 79
  int err_no = 0;
  std::string path = string::format_string(
      "%s/part-%03d-%05d", dump_fields_path_.c_str(), mpi_rank_, tid);

  std::shared_ptr<FILE> fp = fs_open_write(path, &err_no, dump_converter_);
80 81 82 83 84 85
  while (1) {
    std::string out_str;
    if (!queue_->Get(out_str)) {
      break;
    }
    size_t write_count =
T
Thunderbrook 已提交
86
        fwrite_unlocked(out_str.data(), 1, out_str.length(), fp.get());
87 88 89 90
    if (write_count != out_str.length()) {
      VLOG(3) << "dump text failed";
      continue;
    }
T
Thunderbrook 已提交
91
    write_count = fwrite_unlocked("\n", 1, 1, fp.get());
92 93 94 95 96 97 98 99 100 101 102 103 104
    if (write_count != 1) {
      VLOG(3) << "dump text failed";
      continue;
    }
  }
#endif
}

void DistMultiTrainer::InitDumpEnv() {
  queue_ = paddle::framework::MakeChannel<std::string>();
  for (int i = 0; i < thread_num_; ++i) {
    workers_[i]->SetChannelWriter(queue_.get());
  }
T
Thunderbrook 已提交
105 106 107 108 109 110 111 112 113 114 115
  dump_thread_num_ = 1;
  if (dump_file_num_ > mpi_size_) {
    dump_thread_num_ = dump_file_num_ / mpi_size_;
    if (dump_file_num_ % mpi_size_ > mpi_rank_) {
      dump_thread_num_ += 1;
    }
  }
  for (int i = 0; i < dump_thread_num_; i++) {
    dump_thread_.push_back(
        std::thread(std::bind(&DistMultiTrainer::DumpWork, this, i)));
  }
116 117 118 119
}

void DistMultiTrainer::FinalizeDumpEnv() {
  queue_->Close();
T
Thunderbrook 已提交
120 121 122
  for (auto &th : dump_thread_) {
    th.join();
  }
123 124 125
  queue_.reset();
}

126
void DistMultiTrainer::InitOtherEnv(const ProgramDesc &main_program) {
127 128 129
  if (need_dump_field_) {
    InitDumpEnv();
  }
130
  pull_dense_worker_->SetRootScope(root_scope_);
131
  pull_dense_worker_->Start();
D
dongdaxiang 已提交
132
  VLOG(3) << "init other env done.";
133 134
}

135 136 137 138 139 140 141 142 143 144 145 146
void DistMultiTrainer::Run() {
  for (int thidx = 0; thidx < thread_num_; ++thidx) {
    if (!debug_) {
      threads_.push_back(
          std::thread(&DeviceWorker::TrainFiles, workers_[thidx].get()));
    } else {
      threads_.push_back(std::thread(&DeviceWorker::TrainFilesWithProfiler,
                                     workers_[thidx].get()));
    }
  }
}

147 148 149 150
Scope *DistMultiTrainer::GetWorkerScope(int thread_id) {
  return workers_[thread_id]->GetThreadScope();
}

151
void DistMultiTrainer::Finalize() {
152
  for (auto &th : threads_) {
153 154
    th.join();
  }
155
  for (size_t i = 0; i < need_merge_var_names_.size(); i++) {
156 157 158 159 160 161 162 163 164 165 166 167 168
    Variable *root_var = root_scope_->FindVar(need_merge_var_names_[i]);
    if (root_var == nullptr) {
      continue;
    }
    LoDTensor *root_tensor = root_var->GetMutable<LoDTensor>();
    for (int j = 1; j < thread_num_; j++) {
      Scope *cur_thread_scope = workers_[j]->GetThreadScope();
      Variable *thread_var =
          cur_thread_scope->FindVar(need_merge_var_names_[i]);
      LoDTensor *thread_tensor = thread_var->GetMutable<LoDTensor>();
      if (root_tensor->numel() != thread_tensor->numel()) {
        continue;
      }
169 170 171 172 173 174 175 176 177 178 179 180
#define MergeCallback(cpp_type, proto_type)                                    \
  do {                                                                         \
    if (root_tensor->type() == proto_type) {                                   \
      if (thread_tensor->type() != proto_type) {                               \
        VLOG(0) << "Error: thread id=" << j << ", need_merge_var_names_[" << i \
                << "] " << need_merge_var_names_[i]                            \
                << ", root tensor type=" << root_tensor->type()                \
                << ", thread tensor type=" << thread_tensor->type();           \
        exit(-1);                                                              \
      }                                                                        \
      MergeToRootScope<cpp_type>(root_tensor, thread_tensor);                  \
    }                                                                          \
181 182 183 184 185
  } while (0)
      _ForEachDataType_(MergeCallback);
    }
  }

186 187 188
  if (need_dump_field_) {
    FinalizeDumpEnv();
  }
189
  pull_dense_worker_->Stop();
190
  root_scope_->DropKids();
191 192 193 194

  // flush local client push queue
  auto fleet_ptr_ = FleetWrapper::GetInstance();
  fleet_ptr_->ClientFlush();
195 196
}

197 198 199 200 201 202 203 204 205
template <typename T>
void DistMultiTrainer::MergeToRootScope(LoDTensor *root_tensor,
                                        LoDTensor *tensor) {
  T *root_data = root_tensor->data<T>();
  T *data = tensor->data<T>();
  for (int i = 0; i < tensor->numel(); i++) {
    root_data[i] += data[i];
  }
}
206 207
}  // namespace framework
}  // namespace paddle