hogwild_worker.cc 9.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2018 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. */

15
#include "paddle/fluid/framework/data_type.h"
16
#include "paddle/fluid/framework/device_worker.h"
17
#include "paddle/fluid/framework/device_worker_factory.h"
18
#include "paddle/fluid/operators/distributed/distributed.h"
19
#include "paddle/fluid/platform/cpu_helper.h"
D
dongdaxiang 已提交
20
#include "paddle/fluid/platform/lodtensor_printer.h"
21 22 23 24

namespace paddle {
namespace framework {

25
void HogwildWorker::Initialize(const TrainerDesc &desc) {
D
dongdaxiang 已提交
26
  fetch_config_ = desc.fetch_config();
27 28
  param_ = desc.hogwild_param();
  skip_ops_.resize(param_.skip_ops_size());
29
  for (int i = 0; i < param_.skip_ops_size(); ++i) {
30 31
    skip_ops_[i] = param_.skip_ops(i);
  }
32
  use_cvm_ = desc.use_cvm();
33
  thread_barrier_ = desc.thread_barrier();
34 35 36 37 38 39

  dump_fields_.resize(desc.dump_fields_size());
  for (int i = 0; i < desc.dump_fields_size(); ++i) {
    dump_fields_[i] = desc.dump_fields(i);
  }

40 41 42 43
  for (int i = 0; i < param_.stat_var_names_size(); ++i) {
    stat_var_name_map_[param_.stat_var_names(i)] = 1;
  }

44 45 46 47 48 49 50 51
  need_dump_param_ = false;
  dump_param_.resize(desc.dump_param_size());
  for (int i = 0; i < desc.dump_param_size(); ++i) {
    dump_param_[i] = desc.dump_param(i);
  }
  if (desc.dump_param_size() != 0) {
    need_dump_param_ = true;
  }
D
dongdaxiang 已提交
52 53
}

54 55
void HogwildWorker::CreateThreadOperators(const ProgramDesc &program) {
  auto &block = program.Block(0);
56
  op_names_.clear();
57
  for (auto &op_desc : block.AllOps()) {
58 59
    std::unique_ptr<OperatorBase> local_op = OpRegistry::CreateOp(*op_desc);
    op_names_.push_back(op_desc->Type());
60
    OperatorBase *local_op_ptr = local_op.release();
61 62 63 64 65
    ops_.push_back(local_op_ptr);
    continue;
  }
}

66 67
void HogwildWorker::CreateThreadScope(const ProgramDesc &program) {
  auto &block = program.Block(0);
68 69 70 71 72

  PADDLE_ENFORCE_NOT_NULL(
      root_scope_, "root_scope should be set before creating thread scope");

  thread_scope_ = &root_scope_->NewScope();
73 74

  for (auto &var : block.AllVars()) {
T
Thunderbrook 已提交
75
    all_param_.push_back(var->Name());
76
    if (var->Persistable()) {
77
      auto *ptr = root_scope_->Var(var->Name());
78
      InitializeVariable(ptr, var->GetType());
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
      if (stat_var_name_map_.find(var->Name()) != stat_var_name_map_.end() &&
          thread_id_ != 0) {
        int tensor_dim =
            root_scope_->FindVar(var->Name())->GetMutable<LoDTensor>()->numel();
        auto *ptr1 = thread_scope_->Var(var->Name());
        InitializeVariable(ptr1, var->GetType());
        LoDTensor *thread_tensor = ptr1->GetMutable<LoDTensor>();
        LoDTensor *root_tensor =
            root_scope_->FindVar(var->Name())->GetMutable<LoDTensor>();
#define MemsetCallback(cpp_type, proto_type)                     \
  do {                                                           \
    if (root_tensor->type() == proto_type) {                     \
      SetZero<cpp_type>(thread_tensor, root_tensor, tensor_dim); \
    }                                                            \
  } while (0)
        _ForEachDataType_(MemsetCallback);
      }
96
    } else {
97
      auto *ptr = thread_scope_->Var(var->Name());
98 99 100 101 102
      InitializeVariable(ptr, var->GetType());
    }
  }
}

103 104 105 106 107 108 109
template <typename T>
void HogwildWorker::SetZero(LoDTensor *tensor, LoDTensor *root_tensor,
                            int tensor_dim) {
  T *ptr = tensor->mutable_data<T>(root_tensor->dims(), platform::CPUPlace());
  memset(ptr, 0, sizeof(T) * tensor_dim);
}

110
void HogwildWorker::BindingDataFeedMemory() {
111
  const std::vector<std::string> &input_feed =
112
      device_reader_->GetUseSlotAlias();
113
  for (auto name : input_feed) {
114
    device_reader_->AddFeedVar(thread_scope_->FindVar(name), name);
115 116 117
  }
}

118
void HogwildWorker::CreateDeviceResource(const ProgramDesc &main_prog) {
119 120 121 122 123 124
  CreateThreadScope(main_prog);
  CreateThreadOperators(main_prog);
}

void HogwildWorker::TrainFilesWithProfiler() {
  platform::SetNumThreads(1);
125
  device_reader_->Start();
126 127
  std::vector<double> op_total_time;
  std::vector<std::string> op_name;
128
  for (auto &op : ops_) {
129 130 131 132 133 134 135 136 137 138 139 140
    op_name.push_back(op->Type());
  }
  op_total_time.resize(ops_.size());
  for (size_t i = 0; i < op_total_time.size(); ++i) {
    op_total_time[i] = 0.0;
  }
  platform::Timer timeline;
  double total_time = 0.0;
  double read_time = 0.0;
  int cur_batch;
  int batch_cnt = 0;
  timeline.Start();
D
dongdaxiang 已提交
141
  uint64_t total_inst = 0;
142
  while ((cur_batch = device_reader_->Next()) > 0) {
143
    VLOG(3) << "read a batch in thread " << thread_id_;
144 145 146 147
    timeline.Pause();
    read_time += timeline.ElapsedSec();
    total_time += timeline.ElapsedSec();
    for (size_t i = 0; i < ops_.size(); ++i) {
148 149 150 151 152 153 154
      bool need_skip = false;
      for (auto t = 0u; t < skip_ops_.size(); ++t) {
        if (ops_[i]->Type().find(skip_ops_[t]) != std::string::npos) {
          need_skip = true;
          break;
        }
      }
155
      timeline.Start();
156
      VLOG(3) << "Going to run op " << op_name[i];
157 158 159
      if (!need_skip) {
        ops_[i]->Run(*thread_scope_, place_);
      }
160
      VLOG(3) << "Op " << op_name[i] << " Finished";
161 162 163 164
      timeline.Pause();
      op_total_time[i] += timeline.ElapsedSec();
      total_time += timeline.ElapsedSec();
    }
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

    if (need_dump_field_) {
      size_t batch_size = device_reader_->GetCurBatchSize();
      std::vector<std::string> ars(batch_size);
      for (auto &ar : ars) {
        ar.clear();
      }
      auto &ins_id_vec = device_reader_->GetInsIdVec();
      auto &ins_content_vec = device_reader_->GetInsContentVec();
      for (size_t i = 0; i < ins_id_vec.size(); i++) {
        ars[i] += ins_id_vec[i];
        ars[i] = ars[i] + "\t" + ins_content_vec[i];
      }
      for (auto &field : dump_fields_) {
        Variable *var = thread_scope_->FindVar(field);
        if (var == nullptr) {
          continue;
        }
        LoDTensor *tensor = var->GetMutable<LoDTensor>();
        if (!CheckValidOutput(tensor, batch_size)) {
          continue;
        }
        for (size_t i = 0; i < batch_size; ++i) {
          auto output_dim = tensor->dims()[1];
          std::string output_dimstr =
              boost::lexical_cast<std::string>(output_dim);
          ars[i] = ars[i] + "\t" + field + ":" + output_dimstr;
          auto bound = GetTensorBound(tensor, i);
          ars[i] += PrintLodTensor(tensor, bound.first, bound.second);
        }
      }
      // #pragma omp parallel for
      for (size_t i = 0; i < ars.size(); i++) {
        if (ars[i].length() == 0) {
          continue;
        }
        writer_ << ars[i];
      }
      if (need_dump_param_ && thread_id_ == 0) {
        DumpParam(batch_cnt);
      }
    }

D
dongdaxiang 已提交
208
    total_inst += cur_batch;
209
    ++batch_cnt;
D
dongdaxiang 已提交
210
    PrintFetchVars();
211 212 213 214 215 216 217
    if (thread_id_ == 0) {
      if (batch_cnt > 0 && batch_cnt % 100 == 0) {
        for (size_t i = 0; i < ops_.size(); ++i) {
          fprintf(stderr, "op_name:[%zu][%s], op_mean_time:[%fs]\n", i,
                  op_name[i].c_str(), op_total_time[i] / batch_cnt);
        }
        fprintf(stderr, "mean read time: %fs\n", read_time / batch_cnt);
D
dongdaxiang 已提交
218
        fprintf(stderr, "IO percent: %f\n", read_time / total_time * 100);
D
dongdaxiang 已提交
219
        fprintf(stderr, "%6.2f instances/s\n", total_inst / total_time);
220 221
      }
    }
D
dongdaxiang 已提交
222
    thread_scope_->DropKids();
223 224
    timeline.Start();
  }
225 226 227 228 229

  if (need_dump_field_) {
    writer_.Flush();
  }

230 231 232 233 234 235
#ifdef PADDLE_WITH_DISTRIBUTE
  if (thread_barrier_) {
    operators::distributed::Communicator::GetInstance()
        ->BarrierTriggerDecrement();
  }
#endif
236 237
}

238 239 240 241
void HogwildWorker::SetChannelWriter(ChannelObject<std::string> *queue) {
  writer_.Reset(queue);
}

242 243 244 245
void HogwildWorker::TrainFiles() {
  platform::SetNumThreads(1);

  // how to accumulate fetched values here
246
  device_reader_->Start();
247
  int cur_batch;
248
  while ((cur_batch = device_reader_->Next()) > 0) {
249
    for (auto &op : ops_) {
250 251 252 253 254 255 256 257 258 259
      bool need_skip = false;
      for (auto t = 0u; t < skip_ops_.size(); ++t) {
        if (op->Type().find(skip_ops_[t]) != std::string::npos) {
          need_skip = true;
          break;
        }
      }
      if (!need_skip) {
        op->Run(*thread_scope_, place_);
      }
260 261
    }

D
dongdaxiang 已提交
262
    PrintFetchVars();
D
dongdaxiang 已提交
263
    thread_scope_->DropKids();
264
  }
265 266 267 268 269 270
#ifdef PADDLE_WITH_DISTRIBUTE
  if (thread_barrier_) {
    operators::distributed::Communicator::GetInstance()
        ->BarrierTriggerDecrement();
  }
#endif
271 272
}

D
dongdaxiang 已提交
273 274 275 276
void HogwildWorker::PrintFetchVars() {
  // call count
  batch_num_++;
  int batch_per_print = fetch_config_.print_period();
D
dongdaxiang 已提交
277
  if (thread_id_ == 0) {
D
dongdaxiang 已提交
278 279
    if (batch_num_ % batch_per_print == 0) {
      int fetch_var_num = fetch_config_.fetch_var_names_size();
D
dongdaxiang 已提交
280
      for (int i = 0; i < fetch_var_num; ++i) {
D
dongdaxiang 已提交
281
        platform::PrintVar(thread_scope_, fetch_config_.fetch_var_names(i),
D
dongdaxiang 已提交
282
                           fetch_config_.fetch_var_str_format(i));
D
dongdaxiang 已提交
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
void HogwildWorker::SetNeedDump(bool need_dump_field) {
  need_dump_field_ = need_dump_field;
}

void HogwildWorker::DumpParam(const int batch_id) {
  std::ostringstream os;
  for (auto &param : dump_param_) {
    os.str("");
    Variable *var = thread_scope_->FindVar(param);
    if (var == nullptr) {
      continue;
    }
    LoDTensor *tensor = var->GetMutable<LoDTensor>();
    int64_t len = tensor->numel();
    os << "(" << batch_id << "," << param << ")"
       << PrintLodTensor(tensor, 0, len);
    writer_ << os.str();
  }
}

308 309
}  // end namespace framework
}  // end namespace paddle