device_worker.h 11.5 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 38
#include <vector>

#include "paddle/fluid/framework/data_feed.h"
#include "paddle/fluid/framework/fleet/fleet_wrapper.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 已提交
39
#include "paddle/fluid/platform/port.h"
40 41
#include "paddle/fluid/platform/timer.h"

H
hutuxian 已提交
42 43 44 45
#if defined(PADDLE_WITH_CUDA) && !defined(_WIN32)
#include "paddle/fluid/platform/nccl_helper.h"
#endif

46 47 48
namespace paddle {
namespace framework {

H
hutuxian 已提交
49 50 51 52
#define SEC_LOG                                                              \
  VLOG(3) << "[s" << section_id_ << "p" << pipeline_id_ << "t" << thread_id_ \
          << "]: "

53 54 55 56 57 58
class PullDenseWorker {
 public:
  virtual ~PullDenseWorker() {}
  virtual void Initialize(const TrainerDesc& param);
  int Start();
  void Stop();
59
  void SetRootScope(Scope* scope) { root_scope_ = scope; }
60 61 62
  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);
63
  void PullDense(bool force_update = false);
64 65 66 67 68 69 70 71
  static std::shared_ptr<PullDenseWorker> GetInstance() {
    if (NULL == s_instance_) {
      s_instance_.reset(new paddle::framework::PullDenseWorker());
    }
    return s_instance_;
  }

 private:
72
  PullDenseWorker() : root_scope_(NULL) {}
73 74 75 76
  void Run();
  bool CheckUpdateParam(uint64_t table_id);

 private:
77
  static std::shared_ptr<PullDenseWorker> s_instance_;
78 79
  std::shared_ptr<paddle::framework::FleetWrapper> fleet_ptr_;
  PullDenseWorkerParameter param_;
H
heqiaozhi 已提交
80
  DownpourWorkerParameter dwp_param_;
81 82 83
  Scope* root_scope_;
  bool running_;

D
dongdaxiang 已提交
84 85 86 87 88
  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_;
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107

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

// should incorporate different type of device
class DeviceWorker {
 public:
108 109 110 111
  DeviceWorker() {
    no_cvm_ = true;
    use_cvm_ = false;
  }
112 113 114 115
  virtual ~DeviceWorker() {}
  virtual void Initialize(const TrainerDesc& desc) = 0;
  virtual void SetDeviceIndex(int tid) = 0;
  virtual void TrainFiles() = 0;
D
dongdaxiang 已提交
116
  virtual void PrintFetchVars() = 0;
117 118 119 120 121
  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 已提交
122
  virtual void SetDataFeed(DataFeed* data_feed);
123 124
  virtual void SetNeedDump(bool need_dump_field) {}
  virtual void SetChannelWriter(ChannelObject<std::string>* queue) {}
125 126 127
  virtual void SetPlace(const paddle::platform::Place& place) {
    place_ = place;
  }
128 129 130
  virtual void SetReaderPlace(const paddle::platform::Place& place) {
    device_reader_->SetPlace(place);
  }
131
  virtual Scope* GetThreadScope() { return thread_scope_; }
132 133

 protected:
J
jiaqi 已提交
134
  Scope* root_scope_ = nullptr;
135
  Scope* thread_scope_;
136
  paddle::platform::Place place_;
J
jiaqi 已提交
137
  DataFeed* device_reader_ = nullptr;
D
dongdaxiang 已提交
138 139
  int64_t batch_num_;
  FetchConfig fetch_config_;
140
  bool use_cvm_;
141
  bool no_cvm_;
142 143 144 145 146 147 148 149 150
};

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 已提交
151
  virtual void PrintFetchVars() {}
152 153 154 155 156 157 158 159 160
  virtual void CreateDeviceResource(const ProgramDesc& main_prog) {}

 protected:
  int thread_id_;
};

class HogwildWorker : public CPUWorkerBase {
 public:
  HogwildWorker() {}
161 162 163 164 165 166
  virtual ~HogwildWorker() {
    for (OperatorBase* op : ops_) {
      delete op;
    }
    std::vector<OperatorBase*>().swap(ops_);
  }
D
dongdaxiang 已提交
167
  virtual void Initialize(const TrainerDesc& desc);
168 169
  virtual void TrainFiles();
  virtual void TrainFilesWithProfiler();
D
dongdaxiang 已提交
170
  virtual void PrintFetchVars();
171 172
  virtual void CreateDeviceResource(const ProgramDesc& main_prog);
  virtual void BindingDataFeedMemory();
173 174
  template <typename T>
  void SetZero(LoDTensor* tensor, LoDTensor* root_tensor, int tensor_dim);
175 176 177 178 179 180

 protected:
  void CreateThreadOperators(const ProgramDesc& program);
  void CreateThreadScope(const ProgramDesc& program);
  std::vector<std::string> op_names_;
  std::vector<OperatorBase*> ops_;
181
  // Scope* thread_scope_;
182 183
  HogwildWorkerParameter param_;
  std::vector<std::string> skip_ops_;
184
  std::map<std::string, int> stat_var_name_map_;
185 186 187 188 189 190
};

class DownpourWorker : public HogwildWorker {
 public:
  DownpourWorker() {}
  virtual ~DownpourWorker() {}
191
  virtual void Initialize(const TrainerDesc& desc);
192
  virtual void TrainFiles();
193
  virtual void TrainFilesWithProfiler();
194 195
  virtual void SetNeedDump(bool need_dump_field);
  virtual void SetChannelWriter(ChannelObject<std::string>* queue);
196 197 198 199 200 201 202

 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);
203
  void AdjustInsWeight();
204
  void DumpParam();
X
xujiaqi01 已提交
205 206 207
  void CopySparseTable();
  void CopyDenseTable();
  void CopyDenseVars();
208 209

 private:
210 211
  bool need_dump_param_;
  std::vector<std::string> dump_param_;
212
  bool need_to_push_dense_;
213
  bool need_dump_field_;
T
Thunderbrook 已提交
214
  bool dump_slot_;
215
  bool need_to_push_sparse_;
216 217
  std::vector<std::string> dump_fields_;
  ChannelWriter<std::string> writer_;
218
  DownpourWorkerParameter param_;
219
  float scale_datanorm_;
220
  // just save the value in param_ for easy access
221
  std::map<uint64_t, std::string> label_var_name_;
222 223 224 225 226
  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_;
227 228
  // actually pushed feasign of each table
  std::map<uint64_t, std::vector<uint64_t>> sparse_push_keys_;
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243

  // feasign
  std::map<uint64_t, std::vector<uint64_t>> features_;
  // feasign stats
  std::map<uint64_t, std::vector<float>> feature_labels_;
  // feasign embedding
  std::map<uint64_t, std::vector<std::vector<float>>> feature_values_;
  // feasign embedding gradient
  std::map<uint64_t, std::vector<std::vector<float>>> feature_grads_;
  // skipped ops
  std::vector<std::string> skip_ops_;

  std::shared_ptr<PullDenseWorker> _pull_dense_worker;
  std::vector<::std::future<int32_t>> push_sparse_status_;
  std::vector<::std::future<int32_t>> push_dense_status_;
244 245 246 247

  // adjust ins weight
  AdjustInsWeightConfig adjust_ins_weight_config_;
  std::vector<float> nid_show_;
248 249
  // check nan and inf during training
  std::vector<std::string> check_nan_var_names_;
X
xujiaqi01 已提交
250 251 252 253 254 255
  // 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_;
256 257
};

H
hutuxian 已提交
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 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 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
#if defined(PADDLE_WITH_CUDA) && !defined(_WIN32)
using ScopeQueue = operators::reader::BlockingQueue<Scope*>;

class SyncFunctor {
 public:
  SyncFunctor(int rank_id, int rank_num, int sync_steps);
  virtual ~SyncFunctor() {}

  void SetSyncParam(const std::vector<std::string>& sync_param) {
    sync_param_ = &sync_param;
  }
  void SetNcclCtxMap(platform::NCCLContextMap* nccl_ctx_map) {
    nccl_ctx_map_ = nccl_ctx_map;
  }

  int operator()(Scope* scope);
  static std::vector<Scope*> pipeline_scopes_;
  static uint64_t sync_flag_;

 protected:
  const int rank_id_;
  const int rank_num_;
  const std::vector<std::string>* sync_param_ = nullptr;
  platform::NCCLContextMap* nccl_ctx_map_ = nullptr;

  uint64_t sync_signal_;
  const int sync_steps_;
  int counter_;

  void Synchronize();
};

class SectionWorker : public DeviceWorker {
 public:
  SectionWorker() {}
  ~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; }
  void SetDeviceIndex(int tid) override { pipeline_id_ = tid; }
  void SetThreadIndex(int thread_id) { thread_id_ = thread_id; }
  void SetVarNames(const std::vector<std::string>& in_var_names,
                   const std::vector<std::string>& out_var_names) {
    in_var_names_ = &in_var_names;
    out_var_names_ = &out_var_names;
  }
  void SetScopeQueue(ScopeQueue* in_scope_queue, ScopeQueue* out_scope_queue) {
    in_scope_queue_ = in_scope_queue;
    out_scope_queue_ = out_scope_queue;
  }
  void SetCountMutex(std::mutex* mutex) { worker_count_mutex_ = mutex; }
  void SetWorkerCount(int* worker_count) { worker_count_ = worker_count; }
  void SetSectionNum(int section_num) { section_num_ = section_num; }
  void SetPipelineNum(int pipeline_num) { pipeline_num_ = pipeline_num; }
  void SetNextSectionPlace(const paddle::platform::Place& place) {
    next_section_place_ = place;
  }
  SyncFunctor* sync_func_ = nullptr;
  void SetSyncFunctor(SyncFunctor* sync_func) { sync_func_ = sync_func; }

  static std::atomic<int> cpu_id_;

 protected:
  void AutoSetCPUAffinity(bool reuse);
  int section_id_;
  int pipeline_id_;
  int section_num_;
  int pipeline_num_;
  int thread_id_;
  // This worker will consume scope from in_scope_queue_
  // and produce scope to out_scope_queue_
  ScopeQueue* in_scope_queue_ = nullptr;
  ScopeQueue* out_scope_queue_ = nullptr;
  const std::vector<std::string>* in_var_names_ = nullptr;
  const std::vector<std::string>* out_var_names_ = nullptr;
  std::mutex* worker_count_mutex_ = nullptr;
  int* worker_count_ = nullptr;
  paddle::platform::Place next_section_place_;

  std::vector<std::unique_ptr<OperatorBase>> ops_;

  platform::DeviceContext* dev_ctx_ = nullptr;
};
#endif
353 354
}  // namespace framework
}  // namespace paddle