device_worker.h 28.7 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
#include <fstream>
#include <map>
#include <memory>
#include <mutex>  // NOLINT
Z
zhang wenhui 已提交
22
#include <set>
23
#include <string>
X
xujiaqi01 已提交
24 25 26 27
#include <thread>         // NOLINT
#include <unordered_map>  // NOLINT
#include <unordered_set>  // NOLINT
#include <utility>        // NOLINT
28 29
#include <vector>

30 31 32
#if defined(PADDLE_WITH_PSCORE)
#include "paddle/fluid/distributed/ps/wrapper/fleet.h"
#endif
33
#include "paddle/fluid/framework/barrier.h"
34
#include "paddle/fluid/framework/data_feed.h"
35
#include "paddle/fluid/framework/executor_gc_helper.h"
T
Thunderbrook 已提交
36
#include "paddle/fluid/framework/heter_util.h"
37 38 39 40 41 42 43 44 45
#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"
#include "paddle/fluid/platform/timer.h"
46
#include "paddle/phi/backends/dynload/port.h"
47
#include "paddle/phi/core/macros.h"
48

W
wanghuancoder 已提交
49 50 51 52 53 54 55
namespace paddle {
namespace framework {
class ProgramDesc;
class Scope;
}  // namespace framework
}  // namespace paddle

56
#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
57
#include "paddle/fluid/platform/device/gpu/nccl_helper.h"
H
hutuxian 已提交
58 59
#endif

60 61 62
namespace paddle {
namespace framework {

63
std::string PrintLodTensor(phi::DenseTensor* tensor,
D
danleifeng 已提交
64 65 66 67
                           int64_t start,
                           int64_t end,
                           char separator = ',',
                           bool need_leading_separator = false);
68
void PrintLodTensor(phi::DenseTensor* tensor,
D
danleifeng 已提交
69 70
                    int64_t start,
                    int64_t end,
71
                    std::string& output_str,  // NOLINT
D
danleifeng 已提交
72 73
                    char separator = ',',
                    bool need_leading_separator = false);
74 75
std::pair<int64_t, int64_t> GetTensorBound(phi::DenseTensor* tensor, int index);
bool CheckValidOutput(phi::DenseTensor* tensor, size_t batch_size);
76

77 78
class FleetWrapper;

T
Thunderbrook 已提交
79
#if defined(PADDLE_WITH_PSLIB) && !defined(PADDLE_WITH_HETERPS)
T
Thunderbrook 已提交
80 81 82
class HeterWrapper;
#endif

83 84 85 86
class PullDenseWorker {
 public:
  virtual ~PullDenseWorker() {}
  virtual void Initialize(const TrainerDesc& param);
87 88
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
  void AddStream(const gpuStream_t stream) { copy_streams_.push_back(stream); }
T
Thunderbrook 已提交
89
#endif
T
Thunderbrook 已提交
90

91 92
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) || \
    defined(PADDLE_WITH_XPU)
T
Thunderbrook 已提交
93 94 95 96 97 98
  void AddPlace(const paddle::platform::Place place) {
    places_.push_back(place);
  }

  void AddThreadScope(Scope* scope) { thread_scopes_.push_back(scope); }
#endif
99 100
  int Start();
  void Stop();
101
  void SetRootScope(Scope* scope) { root_scope_ = scope; }
102 103 104
  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);
105
  void PullDense(bool force_update = false);
T
Thunderbrook 已提交
106
  void CreatePinVar();
T
Thunderbrook 已提交
107
  void MergeDenseParam();
108 109
  int GetThreadIdByScope(const Scope* scope);
  void SetThreadIdByScope(const Scope* scope, int tid);
110 111 112 113 114 115 116
  static std::shared_ptr<PullDenseWorker> GetInstance() {
    if (NULL == s_instance_) {
      s_instance_.reset(new paddle::framework::PullDenseWorker());
    }
    return s_instance_;
  }

117 118
  static std::shared_ptr<PullDenseWorker> s_instance_;

119
 private:
120
  PullDenseWorker() : root_scope_(NULL) {}
121 122 123 124
  void Run();
  bool CheckUpdateParam(uint64_t table_id);

 private:
125 126 127
#if defined(PADDLE_WITH_PSCORE)
  std::shared_ptr<paddle::distributed::FleetWrapper> fleet_ptr_;
#else
128
  std::shared_ptr<paddle::framework::FleetWrapper> fleet_ptr_;
129 130
#endif

131
  PullDenseWorkerParameter param_;
H
heqiaozhi 已提交
132
  DownpourWorkerParameter dwp_param_;
133 134 135
  Scope* root_scope_;
  bool running_;

D
dongdaxiang 已提交
136 137 138 139 140
  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_;
141 142 143 144 145 146 147 148 149 150 151 152 153 154

  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;
155
  std::unordered_map<const Scope*, int> scope_to_thread_id_;
T
Thunderbrook 已提交
156

157 158
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
  std::vector<gpuStream_t> copy_streams_;
T
Thunderbrook 已提交
159
#endif
T
Thunderbrook 已提交
160 161
  std::vector<paddle::platform::Place> places_;
  std::vector<Scope*> thread_scopes_;
162 163 164 165 166
};

// should incorporate different type of device
class DeviceWorker {
 public:
167 168 169 170
  DeviceWorker() {
    no_cvm_ = true;
    use_cvm_ = false;
  }
171 172
  virtual ~DeviceWorker() {}
  virtual void Initialize(const TrainerDesc& desc) = 0;
H
hutuxian 已提交
173
  virtual void InitRandomDumpConfig(const TrainerDesc& desc);
174 175
  virtual void SetDeviceIndex(int tid) = 0;
  virtual void TrainFiles() = 0;
D
dongdaxiang 已提交
176
  virtual void PrintFetchVars() = 0;
177 178 179 180 181
  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 已提交
182
  virtual void SetDataFeed(DataFeed* data_feed);
183 184
  virtual void SetWorkerNum(int num UNUSED) {}
  virtual void CacheProgram(const ProgramDesc& main_program UNUSED) {}
T
Thunderbrook 已提交
185
  virtual void ProduceTasks() {}
T
Thunderbrook 已提交
186
  virtual void GetXpuOpIndex() {}
187
  virtual void Schedule(int taskid UNUSED) {}
188
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
189 190
  virtual void SetStream(const gpuStream_t stream UNUSED) {}
  virtual void SetEvent(const gpuEvent_t event UNUSED) {}
T
Thunderbrook 已提交
191
#endif
H
hutuxian 已提交
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
  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);
  }
207 208 209
  virtual void SetPlace(const paddle::platform::Place& place) {
    place_ = place;
  }
210 211 212
  virtual void SetReaderPlace(const paddle::platform::Place& place) {
    device_reader_->SetPlace(place);
  }
213 214 215
  virtual void SetDeviceContext(platform::DeviceContext* dev_ctx) {
    dev_ctx_ = dev_ctx;
  }
216 217 218

  virtual void SetThreadNum(int thread_num) { thread_num_ = thread_num; }

219
  virtual Scope* GetThreadScope() { return thread_scope_; }
T
Thunderbrook 已提交
220
  DataFeed* device_reader_ = nullptr;
221 222

 protected:
H
hutuxian 已提交
223
  virtual void DumpParam(const Scope& scope, const int batch_id);
224 225
  virtual void DumpField(const Scope& scope,
                         int dump_mode,
H
hutuxian 已提交
226
                         int dump_interval = 10000);
J
jiaqi 已提交
227
  Scope* root_scope_ = nullptr;
228
  Scope* thread_scope_;
229
  paddle::platform::Place place_;
T
tangwei12 已提交
230
  int64_t batch_num_ = 0;
D
dongdaxiang 已提交
231
  FetchConfig fetch_config_;
232
  bool use_cvm_;
233
  bool no_cvm_;
234
  bool scale_sparse_gradient_with_batch_size_;
T
Thunderbrook 已提交
235
  TrainerDesc trainer_desc_;
H
hutuxian 已提交
236 237 238 239 240 241

  // 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_;
242
  std::vector<std::string> all_param_;
H
hutuxian 已提交
243 244 245 246

  int dump_mode_ = 0;
  int dump_interval_ = 10000;
  ChannelWriter<std::string> writer_;
D
danleifeng 已提交
247
  const size_t tensor_iterator_thread_num = 16;
248
  platform::DeviceContext* dev_ctx_ = nullptr;
L
lxsbupt 已提交
249
  int thread_num_;
250 251 252 253 254 255 256 257 258
};

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 已提交
259
  virtual void PrintFetchVars() {}
260
  virtual void CreateDeviceResource(const ProgramDesc& main_prog UNUSED) {}
261 262 263 264 265 266 267 268

 protected:
  int thread_id_;
};

class HogwildWorker : public CPUWorkerBase {
 public:
  HogwildWorker() {}
269 270 271 272 273 274
  virtual ~HogwildWorker() {
    for (OperatorBase* op : ops_) {
      delete op;
    }
    std::vector<OperatorBase*>().swap(ops_);
  }
D
dongdaxiang 已提交
275
  virtual void Initialize(const TrainerDesc& desc);
276 277
  virtual void TrainFiles();
  virtual void TrainFilesWithProfiler();
D
dongdaxiang 已提交
278
  virtual void PrintFetchVars();
279 280
  virtual void CreateDeviceResource(const ProgramDesc& main_prog);
  virtual void BindingDataFeedMemory();
281
  template <typename T>
282 283 284
  void SetZero(phi::DenseTensor* tensor,
               phi::DenseTensor* root_tensor,
               int tensor_dim);
285 286 287 288

 protected:
  void CreateThreadOperators(const ProgramDesc& program);
  void CreateThreadScope(const ProgramDesc& program);
289 290
  // check batch num
  bool CheckBatchNum(int flag);
291

292 293
  std::vector<std::string> op_names_;
  std::vector<OperatorBase*> ops_;
294
  bool thread_barrier_;
295
  // Scope* thread_scope_;
296 297
  HogwildWorkerParameter param_;
  std::vector<std::string> skip_ops_;
298
  std::map<std::string, int> stat_var_name_map_;
299
  static std::atomic<bool> quit_flag_;
300
  phi::DenseTensor sync_stat_;
301 302 303 304 305 306
};

class DownpourWorker : public HogwildWorker {
 public:
  DownpourWorker() {}
  virtual ~DownpourWorker() {}
307
  virtual void Initialize(const TrainerDesc& desc);
308
  virtual void TrainFiles();
309
  virtual void TrainFilesWithProfiler();
310 311 312 313 314 315 316

 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);
317
  void AdjustInsWeight();
X
xujiaqi01 已提交
318 319 320
  void CopySparseTable();
  void CopyDenseTable();
  void CopyDenseVars();
321

322
  DownpourWorkerParameter param_;
323 324 325 326
  // 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_;
327 328
  // actually pushed feasign of each table
  std::map<uint64_t, std::vector<uint64_t>> sparse_push_keys_;
329
  std::map<uint64_t, std::vector<std::string>> sparse_key_names_;
330 331 332 333
  // feasign
  std::map<uint64_t, std::vector<uint64_t>> features_;
  // feasign embedding
  std::map<uint64_t, std::vector<std::vector<float>>> feature_values_;
334 335 336 337 338 339 340 341 342
  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_;
343 344
  // feasign embedding gradient
  std::map<uint64_t, std::vector<std::vector<float>>> feature_grads_;
345 346 347 348 349 350
  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_;
351 352
  // skipped ops
  std::vector<std::string> skip_ops_;
353 354 355 356 357
  // 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_;
Z
zhang wenhui 已提交
358 359 360 361
  // multitask
  std::map<int32_t, uint64_t> cond2table_map_;
  std::set<uint64_t> condvalue_set_;
  bool flag_partial_push_;
362 363 364 365 366 367

 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_;
368 369

  std::shared_ptr<PullDenseWorker> _pull_dense_worker;
370 371

  std::vector<float> nid_show_;
372 373 374 375
  // std::map<uint64_t, uint64_t> table_dependency_;
  // std::vector<std::pair<uint64_t, uint64_t>> copy_dense_tables_;
};

376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
// Based on DownpourWorker,remove push pull code into operator
#if defined(PADDLE_WITH_PSCORE)
class DownpourLiteWorker : public HogwildWorker {
 public:
  DownpourLiteWorker() {}
  virtual ~DownpourLiteWorker() {}
  virtual void Initialize(const TrainerDesc& desc);
  virtual void TrainFiles();
  virtual void TrainFilesWithProfiler();

 protected:
  std::shared_ptr<paddle::distributed::FleetWrapper> fleet_ptr_;
  std::shared_ptr<paddle::framework::PullDenseWorker> pull_dense_worker_;
  void PushGradients();
  void CopySparseTable();
  void CopyDenseTable();
  void CopyDenseVars();

  DownpourWorkerParameter param_;
  // 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_;
  // actually pushed feasign of each table
  std::map<uint64_t, std::vector<uint64_t>> sparse_push_keys_;
  std::map<uint64_t, std::vector<std::string>> sparse_key_names_;
  // feasign
  std::map<uint64_t, std::vector<uint64_t>> features_;
  // feasign embedding
  std::map<uint64_t, std::vector<std::vector<float>>> feature_values_;
  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_;
  // feasign embedding gradient
  std::map<uint64_t, std::vector<std::vector<float>>> feature_grads_;
  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_;
  // skipped ops
  std::vector<std::string> skip_ops_;
  // 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_;
  // multitask
  std::map<int32_t, uint64_t> cond2table_map_;
  std::set<uint64_t> condvalue_set_;
  bool flag_partial_push_;

 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_;

  std::shared_ptr<PullDenseWorker> _pull_dense_worker;

  std::vector<float> nid_show_;
  // std::map<uint64_t, uint64_t> table_dependency_;
  // std::vector<std::pair<uint64_t, uint64_t>> copy_dense_tables_;
};
#endif

449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
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;
465 466
};

T
Thunderbrook 已提交
467
#if defined(PADDLE_WITH_PSLIB) && !defined(PADDLE_WITH_HETERPS)
T
Thunderbrook 已提交
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
class HeterCpuWorker : public HogwildWorker {
 public:
  HeterCpuWorker() {}
  virtual ~HeterCpuWorker() {}
  virtual void Initialize(const TrainerDesc& desc);
  virtual void TrainFiles();
  virtual void TrainFilesWithProfiler();
  virtual void SetNeedDump(bool need_dump_field);
  virtual void SetChannelWriter(ChannelObject<std::string>* queue);
  virtual void SetWorkerNum(int num) { worker_num_ = num; }
  virtual void Schedule(int taskid);
  virtual void JumpContext(std::shared_ptr<HeterTask> task);
  virtual void CacheProgram(const ProgramDesc& main_program) {
    new (&program_) ProgramDesc(main_program);
  }
  virtual void GetXpuOpIndex();

 protected:
  std::shared_ptr<paddle::framework::FleetWrapper> fleet_ptr_;
  std::shared_ptr<paddle::framework::HeterWrapper> heter_ptr_;
  std::shared_ptr<paddle::framework::PullDenseWorker> pull_dense_worker_;
  void FillSparseValue(std::shared_ptr<HeterTask> task, size_t table_id);
  void PushGradients();
  void CollectLabelInfo(std::shared_ptr<HeterTask> task, size_t table_id);
  void AdjustInsWeight(std::shared_ptr<HeterTask> task);
  void DumpParam();
  void CopySparseTable();
  void CopyDenseTable();
  void CopyDenseVars();

 private:
  int mpi_rank_;
  int worker_num_;
  int xpu_begin_op_index_;
  int xpu_end_op_index_;
  ProgramDesc program_;
  HeterObjectPool<HeterTask> object_pool_;
  HeterList<int, std::shared_ptr<HeterTask>> run_queue_;
  HeterList<int, std::shared_ptr<HeterTask>> wait_queue_;
  bool need_dump_param_;
  std::vector<std::string> dump_param_;
  bool need_to_push_dense_;
  bool need_dump_field_;
  bool dump_slot_;
  bool need_to_push_sparse_;
  std::vector<std::string> dump_fields_;
  ChannelWriter<std::string> writer_;
  DownpourWorkerParameter param_;
  float scale_datanorm_;
  // 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>> sparse_key_names_;
  std::map<uint64_t, std::vector<std::string>> sparse_value_names_;
  std::map<uint64_t, std::vector<std::string>> sparse_grad_names_;
  std::map<uint64_t, std::vector<std::string>> dense_value_names_;
  std::map<uint64_t, std::vector<std::string>> dense_grad_names_;
  platform::Place root_place_;
  // actually pushed feasign of each table
  std::map<uint64_t, std::vector<uint64_t>> sparse_push_keys_;

  // skipped ops
  std::vector<std::string> skip_ops_;

  std::vector<::std::future<int32_t>> push_sparse_status_;
  std::vector<::std::future<int32_t>> push_dense_status_;

  // adjust ins weight
  AdjustInsWeightConfig adjust_ins_weight_config_;
  std::vector<float> nid_show_;
  // check nan and inf during training
  std::vector<std::string> check_nan_var_names_;
  // copy table
  CopyTableConfig copy_table_config_;
  std::map<uint64_t, uint64_t> table_dependency_;
  std::vector<std::pair<uint64_t, uint64_t>> copy_sparse_tables_;
  std::vector<std::pair<uint64_t, uint64_t>> copy_dense_tables_;
  std::unordered_map<uint64_t, std::unordered_set<uint64_t>> feasign_set_;
};
#endif

F
Fan Zhang 已提交
548 549
#if (defined PADDLE_WITH_NCCL || defined PADDLE_WITH_RCCL || \
     defined PADDLE_WITH_XPU_BKCL) &&                        \
550
    (defined PADDLE_WITH_PSLIB)
T
Thunderbrook 已提交
551 552 553
class PSGPUWorker : public HogwildWorker {
 public:
  PSGPUWorker() {}
P
pangengzheng 已提交
554
  virtual ~PSGPUWorker();
T
Thunderbrook 已提交
555 556
  virtual void Initialize(const TrainerDesc& desc);
  virtual void TrainFiles();
557
  virtual void TrainFilesWithProfiler();
T
Thunderbrook 已提交
558 559 560 561 562
  virtual void SetChannelWriter(ChannelObject<std::string>* queue);
  virtual void SetWorkerNum(int num) { worker_num_ = num; }
  virtual void CacheProgram(const ProgramDesc& main_program) {
    new (&program_) ProgramDesc(main_program);
  }
563
  void ProduceTasks() override;
F
Fan Zhang 已提交
564
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
565 566
  virtual void SetStream(const gpuStream_t stream) { copy_stream_ = stream; }
  virtual void SetEvent(const gpuEvent_t event) { event_ = event; }
F
Fan Zhang 已提交
567
#endif
T
Thunderbrook 已提交
568 569
  void ResetStat();

P
pangengzheng 已提交
570 571 572 573
  // async infershape
  virtual void CreateDeviceResource(const ProgramDesc& main_prog);
  virtual void BindingDataFeedMemory();

T
Thunderbrook 已提交
574 575 576 577 578 579
 protected:
  void PushGradients();
  void CopySparseTable();
  void CopyDenseTable();
  void CopyDenseVars();

P
pangengzheng 已提交
580 581 582 583 584 585 586 587 588 589 590
  struct InferShapeCheckData {
    std::vector<std::vector<DDim>> pre_dims;
    std::vector<std::vector<LoD>> pre_lods;
    std::vector<std::vector<DDim>> after_dims;
    std::vector<std::vector<LoD>> after_lods;
  };

  int OpRunAndShapeCheck(OperatorBase& op,  // NOLINT
                         const Scope& scope,
                         const platform::Place& place);

T
Thunderbrook 已提交
591 592 593 594 595 596 597 598 599 600 601 602 603 604
 private:
  int mpi_rank_;
  std::mutex mutex_;
  int worker_num_;
  ProgramDesc program_;
  HeterObjectPool<HeterTask> object_pool_;
  bool need_to_push_dense_;
  bool dump_slot_;
  bool need_to_push_sparse_;
  DownpourWorkerParameter param_;
  float scale_datanorm_;
  // 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>> sparse_key_names_;
T
Thunderbrook 已提交
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
  std::map<uint64_t, std::vector<std::string>> sparse_value_names_;
  std::map<uint64_t, std::vector<std::string>> sparse_grad_names_;
  std::map<uint64_t, std::vector<std::string>> dense_value_names_;
  std::map<uint64_t, std::vector<std::string>> dense_grad_names_;
  platform::Place root_place_;
  // actually pushed feasign of each table
  std::map<uint64_t, std::vector<uint64_t>> sparse_push_keys_;

  // skipped ops
  std::vector<std::string> skip_ops_;

  std::vector<::std::future<int32_t>> push_sparse_status_;
  std::vector<::std::future<int32_t>> push_dense_status_;

  // adjust ins weight
  AdjustInsWeightConfig adjust_ins_weight_config_;
  std::vector<float> nid_show_;
  // check nan and inf during training
  std::vector<std::string> check_nan_var_names_;
  // copy table
  CopyTableConfig copy_table_config_;
  std::map<uint64_t, uint64_t> table_dependency_;
  std::vector<std::pair<uint64_t, uint64_t>> copy_sparse_tables_;
  std::vector<std::pair<uint64_t, uint64_t>> copy_dense_tables_;
  std::unordered_map<uint64_t, std::unordered_set<uint64_t>> feasign_set_;
  paddle::framework::Channel<std::shared_ptr<HeterTask>> pull_queue_;
  paddle::framework::Channel<std::shared_ptr<HeterTask>> push_queue_;
F
Fan Zhang 已提交
632
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
633 634
  gpuEvent_t event_;
  gpuStream_t copy_stream_;
F
Fan Zhang 已提交
635
#endif
T
Thunderbrook 已提交
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
  int batch_cnt_{0};
  std::atomic<int> done_cnt_{0};

  double total_time_;
  double read_time_;
  double pack_time_;
  double pull_sparse_local_time_;
  double op_all_time_;
  double xpu_op_time_;
  double xpu_wait_time_;
  double cpu_op_time_;
  double collect_label_time_;
  double fill_sparse_time_;
  double push_sparse_time_;
  double gpu_2_cpu_time_;
  double cpu_2_gpu_time_;
  uint64_t total_inst_;
P
pangengzheng 已提交
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674

  // async infershape
  int task_threads_num_{6};
  int scope_num_{task_threads_num_ + 1};
  std::atomic<int> thread_count_{0};
  std::atomic<bool> stop_token_{false};
  std::atomic<bool> pack_is_end_{false};
  std::vector<std::thread> task_threads_;
  std::vector<Scope*> thread_scope_vec_;
  std::map<Scope*, std::vector<Variable*>> need_reuse_var_vec_;
  std::vector<Variable*> need_reuse_var_;

  struct TaskData {
    int ins_num;
    Scope* scope;
    MiniBatchGpuPack* pack;
  };
  paddle::framework::BlockingQueue<TaskData> free_task_queue_;
  paddle::framework::BlockingQueue<TaskData> using_task_queue_;

  static std::atomic<int> shape_check_count_;
  static std::atomic<bool> shape_check_flag_;
T
Thunderbrook 已提交
675 676 677
};
#endif

678
#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
H
hutuxian 已提交
679 680
class SectionWorker : public DeviceWorker {
 public:
681
  SectionWorker() {}
H
hutuxian 已提交
682 683 684
  ~SectionWorker() override {}

  void Initialize(const TrainerDesc& desc) override;
685
  void PrepareUnusedVar();
H
hutuxian 已提交
686 687

  void BindingDataFeedMemory() override {}
688
  void CreateDeviceResource(const ProgramDesc& main_prog UNUSED) override{};
H
hutuxian 已提交
689 690

  void TrainFiles() override;
691
  void TrainFilesWithProfiler() override{};
H
hutuxian 已提交
692 693 694 695 696

  void PrintFetchVars() override {}

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

697
  void SetDeviceIndex(int tid UNUSED) override {}
H
hutuxian 已提交
698
  void SetThreadIndex(int thread_id) { thread_id_ = thread_id; }
L
lilong12 已提交
699
  void SetMicrobatchNum(int num) { num_microbatches_ = num; }
700 701 702
  void SetPipelineStageNum(int num) { num_pipeline_stages_ = num; }
  void SetPipelineStage(int stage) { pipeline_stage_ = stage; }
  void SetScheduleMode(int mode) { schedule_mode_ = mode; }
L
lilong12 已提交
703 704
  void SetMicrobatchScopes(const std::vector<Scope*>& scope) {
    microbatch_scopes_ = scope;
H
hutuxian 已提交
705
  }
L
lilong12 已提交
706 707 708
  void SetMinibatchScope(const Scope* scope) { minibatch_scope_ = scope; }
  void SetSkipVars(const std::vector<std::string>& skip_vars) {
    skip_vars_ = skip_vars;
H
hutuxian 已提交
709
  }
710
  void RunBackward(
711 712
      int micro_id,
      std::unique_ptr<GarbageCollector>&,
713 714
      std::unordered_map<const OperatorBase*, std::vector<std::string>>&);
  void RunForward(
715 716
      int micro_id,
      std::unique_ptr<GarbageCollector>&,
717 718 719 720
      std::unordered_map<const OperatorBase*, std::vector<std::string>>&);
  void RunUpdate(
      std::unique_ptr<GarbageCollector>&,
      std::unordered_map<const OperatorBase*, std::vector<std::string>>&);
721 722
  void RunFThenB(std::unique_ptr<GarbageCollector>&);
  void Run1F1B(std::unique_ptr<GarbageCollector>&);
H
hutuxian 已提交
723 724 725 726

 protected:
  int section_id_;
  int thread_id_;
L
lilong12 已提交
727
  int num_microbatches_;
728 729 730
  int num_pipeline_stages_;
  int pipeline_stage_;
  int schedule_mode_;  // 0 for F-then-B and 1 for 1F1B
L
lilong12 已提交
731 732
  std::vector<Scope*> microbatch_scopes_;
  const Scope* minibatch_scope_;
H
hutuxian 已提交
733

734 735 736 737
  // skip&backward vars are only used in 1F1B
  std::vector<std::string> skip_vars_;
  std::vector<std::string> backward_send_vars_;

H
hutuxian 已提交
738
  std::vector<std::unique_ptr<OperatorBase>> ops_;
739 740 741 742
  std::vector<OperatorBase*> forward_and_lr_ops_;
  std::vector<OperatorBase*> forward_ops_;
  std::vector<OperatorBase*> backward_ops_;
  std::vector<OperatorBase*> optimizer_ops_;
L
lilong12 已提交
743
  std::shared_ptr<framework::ProgramDesc> program_;
744 745
  std::unordered_map<const OperatorBase*, std::vector<std::string>>
      unused_vars_;
L
lilong12 已提交
746
  static uint64_t batch_id_;
H
hutuxian 已提交
747 748 749 750

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

752 753 754 755 756 757 758
#if defined(PADDLE_WITH_PSCORE)
class HeterSectionWorker : public DeviceWorker {
 public:
  HeterSectionWorker() {}
  ~HeterSectionWorker() override {}

  void Initialize(const TrainerDesc& desc) override;
759
  void CreateDeviceResource(const ProgramDesc& main_prog UNUSED) override{};
760 761 762 763 764 765 766 767 768 769

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

  void BindingDataFeedMemory() override {}
  void BindingDataFeedMemory(int micro_id);
  void PrintFetchVars() override;
  const platform::Place& place() const { return place_; }

  void SetDeviceIndex(int tid) override { thread_id_ = tid; }
770
  // void SetThreadNum(int thread_num) { thread_num_ = thread_num; }
771 772 773 774 775 776
  void SetMicrobatchNum(int num) { num_microbatches_ = num; }
  void SetPipelineStageNum(int num) { num_pipeline_stages_ = num; }
  void SetPipelineStage(int stage) { pipeline_stage_ = stage; }
  std::shared_ptr<std::vector<Scope*>> GetMicrobatchScopes() {
    return microbatch_scopes_;
  }
777 778 779 780
  void SetMicrobatchScopes(
      std::shared_ptr<std::vector<Scope*>> microbatch_scopes) {
    microbatch_scopes_ = microbatch_scopes;
  }
781 782 783 784
  using SHARED_THREAD_QUEUE = std::shared_ptr<
      ::paddle::framework::BlockingQueue<std::pair<std::string, int>>>;

  SHARED_THREAD_QUEUE GetThreadQueue() { return thread_queue_; }
785 786 787
  void SetThreadQueue(SHARED_THREAD_QUEUE thread_queue) {
    thread_queue_ = thread_queue;
  }
788 789
  void CopyParameters(int microbatch_id,
                      const ProgramDesc& program,
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
                      const platform::Place& place);
  void SetMinibatchScope(Scope* scope) { minibatch_scope_ = scope; }
  void SetTrainerId(int trainer_id) { this->trainer_id_ = trainer_id; }
  void SetTrainers(int trainers) { this->trainers_ = trainers; }
  void CreateMicrobatchScopes();
  void RunForward(int micro_id);
  void RunBackward(int micro_id);
  void RunListen();
  void MiniBatchBarrier();
  void Run();
  void BatchPostProcess();
  void SetDebug(bool debug) { debug_ = debug; }
  Scope* GetThreadScope() override { return minibatch_scope_; }

  // multi-stream
  // #if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
  //  void SetStream(const gpuStream_t stream) override {}
  //  void SetEvent(const gpuEvent_t event) override {}
  // #endif

 protected:
  int trainer_id_;
  int trainers_;
813
  // int thread_num_;
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
  int thread_id_;
  int num_microbatches_;
  int num_pipeline_stages_;
  int pipeline_stage_;
  bool epoch_finish_;

  std::shared_ptr<std::vector<Scope*>> microbatch_scopes_;
  Scope* minibatch_scope_;
  std::vector<int> micro_ids_{};
  std::unique_ptr<OperatorBase> listen_op_{nullptr};
  std::vector<std::unique_ptr<OperatorBase>> forward_ops_;
  std::vector<std::unique_ptr<OperatorBase>> backward_ops_;
  std::shared_ptr<framework::ProgramDesc> program_;
  std::shared_ptr<
      ::paddle::framework::BlockingQueue<std::pair<std::string, int>>>
      thread_queue_;
  static uint64_t batch_id_;
  uint64_t total_ins_num_ = 0;
  platform::DeviceContext* dev_ctx_ = nullptr;
  bool debug_ = false;
  std::vector<double> op_total_time_;
  std::vector<std::string> op_name_;
  platform::Timer timeline_;
  double total_time_ = 0.0;
  double read_time_ = 0.0;
};
#endif

842 843
}  // namespace framework
}  // namespace paddle