device_worker.h 11.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* 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. */

#pragma once

H
hutuxian 已提交
17
#include <atomic>
18 19 20 21 22
#include <fstream>
#include <map>
#include <memory>
#include <mutex>  // NOLINT
#include <string>
X
xujiaqi01 已提交
23 24 25 26
#include <thread>         // NOLINT
#include <unordered_map>  // NOLINT
#include <unordered_set>  // NOLINT
#include <utility>        // NOLINT
27 28 29 30 31 32 33 34 35 36 37
#include <vector>

#include "paddle/fluid/framework/data_feed.h"
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/program_desc.h"
#include "paddle/fluid/framework/reader.h"
#include "paddle/fluid/framework/trainer_desc.pb.h"
#include "paddle/fluid/framework/variable_helper.h"
#include "paddle/fluid/operators/reader/blocking_queue.h"
#include "paddle/fluid/platform/place.h"
D
dongdaxiang 已提交
38
#include "paddle/fluid/platform/port.h"
39 40
#include "paddle/fluid/platform/timer.h"

41
#if defined(PADDLE_WITH_NCCL)
H
hutuxian 已提交
42 43 44
#include "paddle/fluid/platform/nccl_helper.h"
#endif

45 46 47
namespace paddle {
namespace framework {

48
std::string PrintLodTensor(Tensor* tensor, int64_t start, int64_t end);
49 50 51
std::pair<int64_t, int64_t> GetTensorBound(LoDTensor* tensor, int index);
bool CheckValidOutput(LoDTensor* tensor, size_t batch_size);

52 53
class FleetWrapper;

54 55 56 57 58 59
class PullDenseWorker {
 public:
  virtual ~PullDenseWorker() {}
  virtual void Initialize(const TrainerDesc& param);
  int Start();
  void Stop();
60
  void SetRootScope(Scope* scope) { root_scope_ = scope; }
61 62 63
  void IncreaseThreadVersion(int thread_id, uint64_t table_id);
  void ResetThreadVersion(uint64_t table_id);
  void Wait(std::vector<::std::future<int32_t>>* status_vec);
64
  void PullDense(bool force_update = false);
65 66
  int GetThreadIdByScope(const Scope* scope);
  void SetThreadIdByScope(const Scope* scope, int tid);
67 68 69 70 71 72 73
  static std::shared_ptr<PullDenseWorker> GetInstance() {
    if (NULL == s_instance_) {
      s_instance_.reset(new paddle::framework::PullDenseWorker());
    }
    return s_instance_;
  }

74 75
  static std::shared_ptr<PullDenseWorker> s_instance_;

76
 private:
77
  PullDenseWorker() : root_scope_(NULL) {}
78 79 80 81 82 83
  void Run();
  bool CheckUpdateParam(uint64_t table_id);

 private:
  std::shared_ptr<paddle::framework::FleetWrapper> fleet_ptr_;
  PullDenseWorkerParameter param_;
H
heqiaozhi 已提交
84
  DownpourWorkerParameter dwp_param_;
85 86 87
  Scope* root_scope_;
  bool running_;

D
dongdaxiang 已提交
88 89 90 91 92
  static std::map<uint64_t, uint64_t> last_versions_;
  static std::map<uint64_t, uint64_t> current_version_;
  static std::mutex mutex_for_version_;
  static std::map<uint64_t, std::vector<uint64_t>> training_versions_;
  static std::map<uint64_t, std::vector<std::string>> dense_value_names_;
93 94 95 96 97 98 99 100 101 102 103 104 105 106

  std::thread t_;
  int thread_num_;
  int sleep_time_ms_;
  int threshold_;

  std::vector<::std::future<int32_t>> pull_dense_status_;
  uint32_t pull_dense_fail_times_ = 0;
  std::vector<float> base_norm_param_;
  std::vector<float> mean_;
  std::vector<float> scale_;
  float squared_sum_epsilon_ = 1e-4;
  std::mutex mutex_for_mean_scale_;
  float total_batch_num_ = 0;
107
  std::unordered_map<const Scope*, int> scope_to_thread_id_;
108 109 110 111 112
};

// should incorporate different type of device
class DeviceWorker {
 public:
113 114 115 116
  DeviceWorker() {
    no_cvm_ = true;
    use_cvm_ = false;
  }
117 118
  virtual ~DeviceWorker() {}
  virtual void Initialize(const TrainerDesc& desc) = 0;
H
hutuxian 已提交
119
  virtual void InitRandomDumpConfig(const TrainerDesc& desc);
120 121
  virtual void SetDeviceIndex(int tid) = 0;
  virtual void TrainFiles() = 0;
D
dongdaxiang 已提交
122
  virtual void PrintFetchVars() = 0;
123 124 125 126 127
  virtual void TrainFilesWithProfiler() = 0;
  virtual void CreateDeviceResource(const ProgramDesc& main_prog) = 0;
  // will make this zero copy in the future
  virtual void BindingDataFeedMemory() = 0;
  virtual void SetRootScope(Scope* root_scope);
J
jiaqi 已提交
128
  virtual void SetDataFeed(DataFeed* data_feed);
H
hutuxian 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
  virtual void SetNeedDumpField(bool need_dump_field) {
    need_dump_field_ = need_dump_field;
  }
  virtual void SetNeedDumpParam(bool need_dump_param) {
    need_dump_param_ = need_dump_param;
  }
  virtual void SetDumpFieldVector(const std::vector<std::string>& dump_fields) {
    dump_fields_ = &dump_fields;
  }
  virtual void SetDumpParamVector(const std::vector<std::string>& dump_param) {
    dump_param_ = &dump_param;
  }
  virtual void SetChannelWriter(ChannelObject<std::string>* queue) {
    writer_.Reset(queue);
  }
144 145 146
  virtual void SetPlace(const paddle::platform::Place& place) {
    place_ = place;
  }
147 148 149
  virtual void SetReaderPlace(const paddle::platform::Place& place) {
    device_reader_->SetPlace(place);
  }
150
  virtual Scope* GetThreadScope() { return thread_scope_; }
151 152

 protected:
H
hutuxian 已提交
153 154 155
  virtual void DumpParam(const Scope& scope, const int batch_id);
  virtual void DumpField(const Scope& scope, int dump_mode,
                         int dump_interval = 10000);
J
jiaqi 已提交
156
  Scope* root_scope_ = nullptr;
157
  Scope* thread_scope_;
158
  paddle::platform::Place place_;
J
jiaqi 已提交
159
  DataFeed* device_reader_ = nullptr;
D
dongdaxiang 已提交
160 161
  int64_t batch_num_;
  FetchConfig fetch_config_;
162
  bool use_cvm_;
163
  bool no_cvm_;
H
hutuxian 已提交
164 165 166 167 168 169

  // dump params or grads for debug
  bool need_dump_param_;
  bool need_dump_field_;
  const std::vector<std::string>* dump_param_;
  const std::vector<std::string>* dump_fields_;
170
  std::vector<std::string> all_param_;
H
hutuxian 已提交
171 172 173 174

  int dump_mode_ = 0;
  int dump_interval_ = 10000;
  ChannelWriter<std::string> writer_;
175 176 177 178 179 180 181 182 183
};

class CPUWorkerBase : public DeviceWorker {
 public:
  CPUWorkerBase() {}
  virtual ~CPUWorkerBase() {}
  virtual void SetDeviceIndex(int tid) { thread_id_ = tid; }
  virtual void TrainFiles() = 0;
  virtual void TrainFilesWithProfiler() {}
D
dongdaxiang 已提交
184
  virtual void PrintFetchVars() {}
185 186 187 188 189 190 191 192 193
  virtual void CreateDeviceResource(const ProgramDesc& main_prog) {}

 protected:
  int thread_id_;
};

class HogwildWorker : public CPUWorkerBase {
 public:
  HogwildWorker() {}
194 195 196 197 198 199
  virtual ~HogwildWorker() {
    for (OperatorBase* op : ops_) {
      delete op;
    }
    std::vector<OperatorBase*>().swap(ops_);
  }
D
dongdaxiang 已提交
200
  virtual void Initialize(const TrainerDesc& desc);
201 202
  virtual void TrainFiles();
  virtual void TrainFilesWithProfiler();
D
dongdaxiang 已提交
203
  virtual void PrintFetchVars();
204 205
  virtual void CreateDeviceResource(const ProgramDesc& main_prog);
  virtual void BindingDataFeedMemory();
206 207
  template <typename T>
  void SetZero(LoDTensor* tensor, LoDTensor* root_tensor, int tensor_dim);
208 209 210 211

 protected:
  void CreateThreadOperators(const ProgramDesc& program);
  void CreateThreadScope(const ProgramDesc& program);
212

213 214
  std::vector<std::string> op_names_;
  std::vector<OperatorBase*> ops_;
215
  bool thread_barrier_;
216
  // Scope* thread_scope_;
217 218
  HogwildWorkerParameter param_;
  std::vector<std::string> skip_ops_;
219
  std::map<std::string, int> stat_var_name_map_;
220 221 222 223 224 225
};

class DownpourWorker : public HogwildWorker {
 public:
  DownpourWorker() {}
  virtual ~DownpourWorker() {}
226
  virtual void Initialize(const TrainerDesc& desc);
227
  virtual void TrainFiles();
228
  virtual void TrainFilesWithProfiler();
229 230 231 232 233 234 235

 protected:
  std::shared_ptr<paddle::framework::FleetWrapper> fleet_ptr_;
  std::shared_ptr<paddle::framework::PullDenseWorker> pull_dense_worker_;
  void FillSparseValue(size_t table_id);
  void PushGradients();
  void CollectLabelInfo(size_t table_id);
236
  void AdjustInsWeight();
X
xujiaqi01 已提交
237 238 239
  void CopySparseTable();
  void CopyDenseTable();
  void CopyDenseVars();
240

241
  DownpourWorkerParameter param_;
242 243 244 245
  // copy table
  CopyTableConfig copy_table_config_;
  std::vector<std::pair<uint64_t, uint64_t>> copy_sparse_tables_;
  std::unordered_map<uint64_t, std::unordered_set<uint64_t>> feasign_set_;
246 247
  // actually pushed feasign of each table
  std::map<uint64_t, std::vector<uint64_t>> sparse_push_keys_;
248
  std::map<uint64_t, std::vector<std::string>> sparse_key_names_;
249 250 251 252
  // feasign
  std::map<uint64_t, std::vector<uint64_t>> features_;
  // feasign embedding
  std::map<uint64_t, std::vector<std::vector<float>>> feature_values_;
253 254 255 256 257 258 259 260 261
  std::map<uint64_t, std::vector<std::string>> sparse_value_names_;
  // adjust ins weight
  AdjustInsWeightConfig adjust_ins_weight_config_;
  // check nan and inf during training
  std::vector<std::string> check_nan_var_names_;
  bool need_to_push_sparse_;
  // feasign stats
  std::map<uint64_t, std::vector<float>> feature_labels_;
  std::map<uint64_t, std::vector<std::string>> sparse_grad_names_;
262 263
  // feasign embedding gradient
  std::map<uint64_t, std::vector<std::vector<float>>> feature_grads_;
264 265 266 267 268 269
  std::vector<::std::future<int32_t>> push_sparse_status_;
  bool dump_slot_;
  bool need_to_push_dense_;
  std::map<uint64_t, std::vector<std::string>> dense_grad_names_;
  float scale_datanorm_;
  std::vector<::std::future<int32_t>> push_dense_status_;
270 271
  // skipped ops
  std::vector<std::string> skip_ops_;
272 273 274 275 276 277 278 279 280 281 282
  // just save the value in param_ for easy access
  std::map<uint64_t, std::string> label_var_name_;
  std::map<uint64_t, std::vector<std::string>> dense_value_names_;
  std::map<uint64_t, uint64_t> table_dependency_;
  std::vector<std::pair<uint64_t, uint64_t>> copy_dense_tables_;

 private:
  // std::vector<std::string> dump_param_;
  // just save the value in param_ for easy access
  // std::map<uint64_t, std::string> label_var_name_;
  // std::map<uint64_t, std::vector<std::string>> dense_value_names_;
283 284

  std::shared_ptr<PullDenseWorker> _pull_dense_worker;
285 286

  std::vector<float> nid_show_;
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
  // std::map<uint64_t, uint64_t> table_dependency_;
  // std::vector<std::pair<uint64_t, uint64_t>> copy_dense_tables_;
};

class DownpourWorkerOpt : public DownpourWorker {
 public:
  DownpourWorkerOpt() {}
  virtual ~DownpourWorkerOpt() {}
  virtual void CreateDeviceResource(const ProgramDesc& main_prog);
  virtual void Initialize(const TrainerDesc& desc);
  virtual void TrainFiles();

 protected:
  void CreateThreadOperatorsWithRerank(const ProgramDesc& program);
  std::vector<std::vector<OperatorBase*>> loss_ops_;
  std::vector<std::vector<std::string>> loss_op_names_;
  std::vector<std::string> loss_names_;
  std::string async_wait_name_;
  int async_index_ = -1;
  uint64_t async_tid_ = 0;
307 308
};

309
#if defined(PADDLE_WITH_NCCL)
H
hutuxian 已提交
310 311
class SectionWorker : public DeviceWorker {
 public:
L
lilong12 已提交
312
  SectionWorker() { local_batch_id_ = 0; }
H
hutuxian 已提交
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
  ~SectionWorker() override {}

  void Initialize(const TrainerDesc& desc) override;

  void BindingDataFeedMemory() override {}
  void CreateDeviceResource(const ProgramDesc& main_prog) override{};

  void TrainFiles() override;
  void TrainFilesWithProfiler() override;

  void PrintFetchVars() override {}

  const platform::Place& place() const { return place_; }

  void SetSectionIndex(int section_id) { section_id_ = section_id; }
L
lilong12 已提交
328
  void SetDeviceIndex(int tid) override {}
H
hutuxian 已提交
329
  void SetThreadIndex(int thread_id) { thread_id_ = thread_id; }
L
lilong12 已提交
330 331 332
  void SetMicrobatchNum(int num) { num_microbatches_ = num; }
  void SetMicrobatchScopes(const std::vector<Scope*>& scope) {
    microbatch_scopes_ = scope;
H
hutuxian 已提交
333
  }
L
lilong12 已提交
334 335 336
  void SetMinibatchScope(const Scope* scope) { minibatch_scope_ = scope; }
  void SetSkipVars(const std::vector<std::string>& skip_vars) {
    skip_vars_ = skip_vars;
H
hutuxian 已提交
337 338 339 340 341 342 343 344
  }

  static std::atomic<int> cpu_id_;

 protected:
  void AutoSetCPUAffinity(bool reuse);
  int section_id_;
  int thread_id_;
L
lilong12 已提交
345 346 347 348
  int num_microbatches_;
  std::vector<Scope*> microbatch_scopes_;
  std::vector<std::string> skip_vars_;
  const Scope* minibatch_scope_;
H
hutuxian 已提交
349 350

  std::vector<std::unique_ptr<OperatorBase>> ops_;
L
lilong12 已提交
351
  static std::mutex thread_mutex;
S
update  
sandyhouse 已提交
352
  static std::mutex cout_mutex;
L
lilong12 已提交
353 354 355 356 357
  static std::condition_variable thread_condition;
  static bool threads_completed;
  std::shared_ptr<framework::ProgramDesc> program_;
  static uint64_t batch_id_;
  uint64_t local_batch_id_;
H
hutuxian 已提交
358 359 360 361

  platform::DeviceContext* dev_ctx_ = nullptr;
};
#endif
L
lilong12 已提交
362

363 364
}  // namespace framework
}  // namespace paddle