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

#include <memory>
#ifdef PADDLE_WITH_PSLIB
19
#include <archive.h>
D
dongdaxiang 已提交
20
#include <pslib.h>
21
#endif
22
#include <ThreadPool.h>
23

24
#include <atomic>
X
xujiaqi01 已提交
25
#include <ctime>
D
dongdaxiang 已提交
26
#include <map>
D
dongdaxiang 已提交
27
#include <random>
28
#include <string>
29
#include <unordered_map>
30
#include <vector>
31

T
Thunderbrook 已提交
32
#include "paddle/fluid/framework/heter_util.h"
D
dongdaxiang 已提交
33
#include "paddle/fluid/framework/program_desc.h"
34
#include "paddle/fluid/framework/scope.h"
35
#include "paddle/fluid/framework/tensor.h"
36 37
#include "paddle/fluid/framework/variable_helper.h"
#include "paddle/fluid/platform/macros.h"  // for DISABLE_COPY_AND_ASSIGN
T
Thunderbrook 已提交
38
#ifdef PADDLE_WITH_HETERPS
39
#include "paddle/fluid/platform/device/gpu/gpu_types.h"
T
Thunderbrook 已提交
40
#endif
41

W
wanghuancoder 已提交
42 43 44 45 46 47
namespace paddle {
namespace framework {
class Scope;
}  // namespace framework
}  // namespace paddle

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
namespace paddle {
namespace framework {

// A wrapper class for pslib.h, this class follows Singleton pattern
// i.e. only initialized once in the current process
// Example:
//    std::shared_ptr<FleetWrapper> fleet_ptr =
//         FleetWrapper::GetInstance();
//    string dist_desc;
//    fleet_ptr->InitServer(dist_desc, 0);
// interface design principles:
// Pull
//   Sync: PullSparseVarsSync
//   Async: PullSparseVarsAsync(not implemented currently)
// Push
//   Sync: PushSparseVarsSync
64 65
//   Async: PushSparseVarsAsync(not implemented currently)
//   Async: PushSparseVarsWithLabelAsync(with special usage)
66 67 68 69 70 71 72
// Push dense variables to server in Async mode
// Param<in>: scope, table_id, var_names
// Param<out>: push_sparse_status

class FleetWrapper {
 public:
  virtual ~FleetWrapper() {}
73 74 75 76
  FleetWrapper() {
    scale_sparse_gradient_with_batch_size_ = true;
    // trainer sleep some time for pslib core dump
    sleep_seconds_before_fail_exit_ = 300;
77 78 79 80 81 82
    // pslib request server timeout ms
    client2client_request_timeout_ms_ = 500000;
    // pslib connect server timeout_ms
    client2client_connect_timeout_ms_ = 10000;
    // pslib request max retry
    client2client_max_retry_ = 3;
83
    pull_local_thread_num_ = 25;
84
  }
85

X
xujiaqi01 已提交
86
  // set client to client communication config
87 88 89
  void SetClient2ClientConfig(int request_timeout_ms, int connect_timeout_ms,
                              int max_retry);

90 91 92
  void SetPullLocalThreadNum(int thread_num) {
    pull_local_thread_num_ = thread_num;
  }
93

T
Thunderbrook 已提交
94 95 96 97 98 99 100 101
#ifdef PADDLE_WITH_PSLIB
  void HeterPullSparseVars(int workerid, std::shared_ptr<HeterTask> task,
                           const uint64_t table_id,
                           const std::vector<std::string>& var_names,
                           int fea_dim,
                           const std::vector<std::string>& var_emb_names);

  void HeterPushSparseVars(
T
Thunderbrook 已提交
102 103
      std::shared_ptr<HeterTask> task, const Scope& scope,
      const uint64_t table_id, const std::vector<std::string>& sparse_key_names,
T
Thunderbrook 已提交
104 105 106 107 108 109 110 111
      const std::vector<std::string>& sparse_grad_names, const int emb_dim,
      std::vector<::std::future<int32_t>>* push_sparse_status,
      const bool use_cvm, const bool dump_slot, const bool no_cvm);
#endif

  typedef std::function<void(int, int)> HeterCallBackFunc;
  int RegisterHeterCallback(HeterCallBackFunc handler);

X
xujiaqi01 已提交
112
  // Pull sparse variables from server in sync mode
113
  // Param<in>: scope, table_id, var_names, fea_keys, fea_dim, var_emb_names
114 115 116 117 118
  // Param<out>: fea_values
  void PullSparseVarsSync(const Scope& scope, const uint64_t table_id,
                          const std::vector<std::string>& var_names,
                          std::vector<uint64_t>* fea_keys,
                          std::vector<std::vector<float>>* fea_values,
119 120
                          int fea_dim,
                          const std::vector<std::string>& var_emb_names);
121 122 123 124

  // Pull sparse variables from server in async mode
  // Param<in>: scope, table_id, var_names, fea_keys, fea_dim
  // Param<out>: fea_values std::future
125 126 127 128 129
  std::future<int32_t> PullSparseVarsAsync(
      const Scope& scope, const uint64_t table_id,
      const std::vector<std::string>& var_names,
      std::vector<uint64_t>* fea_keys,
      std::vector<std::vector<float>>* fea_values, int fea_dim);
130 131 132 133 134 135 136 137

  // Pull sparse variables from server in sync mode
  // pull immediately to tensors
  void PullSparseToTensorSync(const uint64_t table_id, int fea_dim,
                              uint64_t padding_id, platform::Place place,
                              std::vector<const LoDTensor*>* inputs,  // NOLINT
                              std::vector<LoDTensor*>* outputs);      // NOLINT

X
xujiaqi01 已提交
138
  // pull dense variables from server in sync mod
139 140
  // Param<in>: scope, table_id, var_names
  // Param<out>: void
141 142 143
  void PullDenseVarsSync(const Scope& scope, const uint64_t table_id,
                         const std::vector<std::string>& var_names);

X
xujiaqi01 已提交
144 145 146
  // pull dense variables from server in async mod
  // Param<in>: scope, table_id, var_names
  // Param<out>: pull_dense_status
147 148 149
  void PullDenseVarsAsync(
      const Scope& scope, const uint64_t table_id,
      const std::vector<std::string>& var_names,
T
Thunderbrook 已提交
150
      std::vector<::std::future<int32_t>>* pull_dense_status, bool in_cpu);
151

X
xujiaqi01 已提交
152
  // push dense parameters(not gradients) to server in sync mode
D
dongdaxiang 已提交
153
  void PushDenseParamSync(const Scope& scope, const uint64_t table_id,
D
dongdaxiang 已提交
154
                          const std::vector<std::string>& var_names);
155

T
Thunderbrook 已提交
156 157 158
// Push dense variables to server in async mode
// Param<in>: scope, table_id, var_names, scale_datanorm, batch_size
// Param<out>: push_sparse_status
159
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
T
Thunderbrook 已提交
160 161 162 163 164
  void PushDenseVarsAsync(
      const Scope& scope, const uint64_t table_id,
      const std::vector<std::string>& var_names,
      std::vector<::std::future<int32_t>>* push_sparse_status,
      float scale_datanorm, int batch_size,
165 166
      const paddle::platform::Place& place, gpuStream_t stream,
      gpuEvent_t event);
T
Thunderbrook 已提交
167 168 169 170 171 172 173 174
#endif
#ifdef PADDLE_WITH_XPU
  void PushDenseVarsAsync(
      const Scope& scope, const uint64_t table_id,
      const std::vector<std::string>& var_names,
      std::vector<::std::future<int32_t>>* push_sparse_status,
      float scale_datanorm, int batch_size,
      const paddle::platform::Place& place);
T
Thunderbrook 已提交
175
#endif
176 177 178
  void PushDenseVarsAsync(
      const Scope& scope, const uint64_t table_id,
      const std::vector<std::string>& var_names,
179 180
      std::vector<::std::future<int32_t>>* push_sparse_status,
      float scale_datanorm, int batch_size);
181

X
xujiaqi01 已提交
182
  // push dense variables to server in sync mode
D
dongdaxiang 已提交
183 184 185
  void PushDenseVarsSync(Scope* scope, const uint64_t table_id,
                         const std::vector<std::string>& var_names);

X
xujiaqi01 已提交
186
  // Push sparse variables with labels to server in async mode
187 188 189 190 191 192 193 194 195 196 197 198
  std::vector<std::unordered_map<uint64_t, std::vector<float>>> local_tables_;
  void PullSparseToLocal(const uint64_t table_id, int fea_value_dim);
  void PullSparseVarsFromLocal(const Scope& scope, const uint64_t table_id,
                               const std::vector<std::string>& var_names,
                               std::vector<uint64_t>* fea_keys,
                               std::vector<std::vector<float>>* fea_values,
                               int fea_value_dim);
  void ClearLocalTable();
  std::vector<std::unordered_map<uint64_t, std::vector<float>>>&
  GetLocalTable() {
    return local_tables_;
  }
199

200
  // This is specially designed for click/show stats in server
X
xujiaqi01 已提交
201 202
  // Param<in>: scope, table_id, fea_keys, fea_labels, sparse_key_names,
  //            sparse_grad_names, batch_size, use_cvm, dump_slot
203 204 205 206 207 208 209 210
  // Param<out>: push_values, push_sparse_status
  void PushSparseVarsWithLabelAsync(
      const Scope& scope, const uint64_t table_id,
      const std::vector<uint64_t>& fea_keys,
      const std::vector<float>& fea_labels,
      const std::vector<std::string>& sparse_key_names,
      const std::vector<std::string>& sparse_grad_names, const int emb_dim,
      std::vector<std::vector<float>>* push_values,
211
      std::vector<::std::future<int32_t>>* push_sparse_status,
212
      const int batch_size, const bool use_cvm, const bool dump_slot,
213 214
      std::vector<uint64_t>* sparse_push_keys, const bool no_cvm,
      const bool scale_sparse_gradient_with_batch_size);
215

216 217 218 219 220 221 222 223 224
  // Push sparse variables to server in async mode
  void PushSparseFromTensorWithLabelAsync(
      const Scope& scope, const uint64_t table_id, int fea_dim,
      uint64_t padding_id, bool scale_sparse, const std::string& accesor,
      const std::string& click_name, platform::Place place,
      const std::vector<std::string>& input_names,
      std::vector<const LoDTensor*>* inputs,    // NOLINT
      std::vector<const LoDTensor*>* outputs);  // NOLINT

225 226 227 228 229 230 231 232 233 234 235 236 237
  // Push sparse variables to server in Async mode
  // Param<In>: scope, table_id, fea_keys, sparse_grad_names
  // Param<Out>: push_values, push_sparse_status
  /*
  void PushSparseVarsAsync(
          const Scope& scope,
          const uint64_t table_id,
          const std::vector<uint64_t>& fea_keys,
          const std::vector<std::string>& sparse_grad_names,
          std::vector<std::vector<float>>* push_values,
          std::vector<::std::future<int32_t>>* push_sparse_status);
  */

X
xujiaqi01 已提交
238
  // init server
239
  void InitServer(const std::string& dist_desc, int index);
X
xujiaqi01 已提交
240
  // init trainer
241 242 243
  void InitWorker(const std::string& dist_desc,
                  const std::vector<uint64_t>& host_sign_list, int node_num,
                  int index);
X
xujiaqi01 已提交
244
  // stop server
245
  void StopServer();
246 247
  // finalize worker to make worker can be stop
  void FinalizeWorker();
X
xujiaqi01 已提交
248
  // run server
249
  uint64_t RunServer();
250 251
  // run server with ip port
  uint64_t RunServer(const std::string& ip, uint32_t port);
X
xujiaqi01 已提交
252
  // gather server ip
253
  void GatherServers(const std::vector<uint64_t>& host_sign_list, int node_num);
X
xjqbest 已提交
254
  // gather client ip
X
xjqbest 已提交
255
  void GatherClients(const std::vector<uint64_t>& host_sign_list);
X
xjqbest 已提交
256
  // get client info
X
xjqbest 已提交
257
  std::vector<uint64_t> GetClientsInfo();
X
xjqbest 已提交
258
  // create client to client connection
X
xjqbest 已提交
259
  void CreateClient2ClientConnection();
260 261
  // flush all push requests
  void ClientFlush();
262 263 264 265
  // load from paddle model
  void LoadFromPaddleModel(Scope& scope, const uint64_t table_id,  // NOLINT
                           std::vector<std::string> var_list,
                           std::string model_path, std::string model_proto_file,
266
                           std::vector<std::string> table_var_list,
267
                           bool load_combine);
268 269

  void PrintTableStat(const uint64_t table_id);
270
  void SetFileNumOneShard(const uint64_t table_id, int file_num);
271
  // mode = 0, load all feature
X
xujiaqi01 已提交
272
  // mode = 1, load delta feature, which means load diff
273
  void LoadModel(const std::string& path, const int mode);
274
  // mode = 0, load all feature
X
xujiaqi01 已提交
275
  // mode = 1, load delta feature, which means load diff
276 277
  void LoadModelOneTable(const uint64_t table_id, const std::string& path,
                         const int mode);
278 279 280
  // mode = 0, save all feature
  // mode = 1, save delta feature, which means save diff
  void SaveModel(const std::string& path, const int mode);
281 282
  void SaveMultiTableOnePath(const std::vector<int>& table_ids,
                             const std::string& path, const int mode);
X
xujiaqi01 已提交
283 284 285 286 287 288 289
  // mode = 0, save all feature
  // mode = 1, save delta feature, which means save diff
  void SaveModelOneTable(const uint64_t table_id, const std::string& path,
                         const int mode);
  // save model with prefix
  void SaveModelOneTablePrefix(const uint64_t table_id, const std::string& path,
                               const int mode, const std::string& prefix);
X
xujiaqi01 已提交
290
  // get save cache threshold
291
  double GetCacheThreshold(int table_id);
X
xujiaqi01 已提交
292
  // shuffle cache model between servers
293 294
  void CacheShuffle(int table_id, const std::string& path, const int mode,
                    const double cache_threshold);
X
xujiaqi01 已提交
295 296
  // save cache model
  // cache model can speed up online predict
297
  int32_t SaveCache(int table_id, const std::string& path, const int mode);
298 299 300 301 302
  // save sparse table filtered by user-defined whitelist
  int32_t SaveWithWhitelist(int table_id, const std::string& path,
                            const int mode, const std::string& whitelist_path);
  void LoadWithWhitelist(const uint64_t table_id, const std::string& path,
                         const int mode);
X
xujiaqi01 已提交
303 304 305 306 307 308 309
  // copy feasign key/value from src_table_id to dest_table_id
  int32_t CopyTable(const uint64_t src_table_id, const uint64_t dest_table_id);
  // copy feasign key/value from src_table_id to dest_table_id
  int32_t CopyTableByFeasign(const uint64_t src_table_id,
                             const uint64_t dest_table_id,
                             const std::vector<uint64_t>& feasign_list);
  // clear all models, release their memory
310
  void ClearModel();
X
xujiaqi01 已提交
311 312
  // clear one table
  void ClearOneTable(const uint64_t table_id);
X
xujiaqi01 已提交
313
  // shrink sparse table
314
  void ShrinkSparseTable(int table_id);
X
xujiaqi01 已提交
315
  // shrink dense table
316
  void ShrinkDenseTable(int table_id, Scope* scope,
317 318
                        std::vector<std::string> var_list, float decay,
                        int emb_dim);
319

D
dongdaxiang 已提交
320
  typedef std::function<int32_t(int, int, const std::string&)> MsgHandlerFunc;
X
xujiaqi01 已提交
321
  // register client to client communication
322
  int RegisterClientToClientMsgHandler(int msg_type, MsgHandlerFunc handler);
X
xjqbest 已提交
323
  // send client to client message
D
dongdaxiang 已提交
324 325
  std::future<int32_t> SendClientToClientMsg(int msg_type, int to_client_id,
                                             const std::string& msg);
326 327 328 329
  // confirm all the updated params in the current pass
  void Confirm();
  // revert all the updated params in the current pass
  void Revert();
X
xujiaqi01 已提交
330
  // FleetWrapper singleton
331 332 333 334 335 336
  static std::shared_ptr<FleetWrapper> GetInstance() {
    if (NULL == s_instance_) {
      s_instance_.reset(new paddle::framework::FleetWrapper());
    }
    return s_instance_;
  }
337 338 339
  // this performs better than rand_r, especially large data
  std::default_random_engine& LocalRandomEngine();

340 341
  void SetDate(const uint64_t table_id, const std::string& date);

342 343 344 345
#ifdef PADDLE_WITH_PSLIB
  static std::shared_ptr<paddle::distributed::PSlib> pslib_ptr_;
#endif

346 347
 private:
  static std::shared_ptr<FleetWrapper> s_instance_;
X
xjqbest 已提交
348
#ifdef PADDLE_WITH_PSLIB
X
xujiaqi01 已提交
349
  std::map<uint64_t, std::vector<paddle::ps::Region>> _regions;
X
xjqbest 已提交
350
#endif
351

352 353 354
  size_t GetAbsoluteSum(size_t start, size_t end, size_t level,
                        const framework::LoD& lod);

355
 protected:
356
  static bool is_initialized_;
357
  bool scale_sparse_gradient_with_batch_size_;
358
  int32_t sleep_seconds_before_fail_exit_;
359 360 361
  int client2client_request_timeout_ms_;
  int client2client_connect_timeout_ms_;
  int client2client_max_retry_;
362 363 364 365
  std::unique_ptr<::ThreadPool> local_pull_pool_{nullptr};
  int pull_local_thread_num_;
  std::unique_ptr<::ThreadPool> pull_to_local_pool_{nullptr};
  int local_table_shard_num_;
366 367 368 369 370
  DISABLE_COPY_AND_ASSIGN(FleetWrapper);
};

}  // end namespace framework
}  // end namespace paddle