fleet_wrapper.h 11.2 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
#include <atomic>
X
xujiaqi01 已提交
24
#include <ctime>
D
dongdaxiang 已提交
25
#include <map>
D
dongdaxiang 已提交
26
#include <random>
27
#include <string>
28
#include <unordered_map>
29
#include <vector>
30

D
dongdaxiang 已提交
31
#include "paddle/fluid/framework/program_desc.h"
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#include "paddle/fluid/framework/scope.h"
#include "paddle/fluid/framework/variable_helper.h"
#include "paddle/fluid/platform/macros.h"  // for DISABLE_COPY_AND_ASSIGN

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
52 53
//   Async: PushSparseVarsAsync(not implemented currently)
//   Async: PushSparseVarsWithLabelAsync(with special usage)
54 55 56 57 58 59 60
// 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() {}
61 62 63 64
  FleetWrapper() {
    scale_sparse_gradient_with_batch_size_ = true;
    // trainer sleep some time for pslib core dump
    sleep_seconds_before_fail_exit_ = 300;
65 66 67 68 69 70
    // 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;
71
    pull_local_thread_num_ = 25;
72
  }
73

X
xujiaqi01 已提交
74
  // set client to client communication config
75 76 77
  void SetClient2ClientConfig(int request_timeout_ms, int connect_timeout_ms,
                              int max_retry);

78 79 80
  void SetPullLocalThreadNum(int thread_num) {
    pull_local_thread_num_ = thread_num;
  }
X
xujiaqi01 已提交
81 82
  // Pull sparse variables from server in sync mode
  // Param<in>: scope, table_id, var_names, fea_keys, fea_dim
83 84 85 86 87
  // 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,
88 89
                          int fea_dim,
                          const std::vector<std::string>& var_emb_names);
90 91 92 93 94
  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);
X
xujiaqi01 已提交
95
  // pull dense variables from server in sync mod
96 97 98
  void PullDenseVarsSync(const Scope& scope, const uint64_t table_id,
                         const std::vector<std::string>& var_names);

X
xujiaqi01 已提交
99 100 101
  // pull dense variables from server in async mod
  // Param<in>: scope, table_id, var_names
  // Param<out>: pull_dense_status
102 103 104 105 106
  void PullDenseVarsAsync(
      const Scope& scope, const uint64_t table_id,
      const std::vector<std::string>& var_names,
      std::vector<::std::future<int32_t>>* pull_dense_status);

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

111
  // Push dense variables to server in async mode
X
xujiaqi01 已提交
112
  // Param<in>: scope, table_id, var_names, scale_datanorm, batch_size
113 114 115 116
  // Param<out>: push_sparse_status
  void PushDenseVarsAsync(
      const Scope& scope, const uint64_t table_id,
      const std::vector<std::string>& var_names,
117 118
      std::vector<::std::future<int32_t>>* push_sparse_status,
      float scale_datanorm, int batch_size);
119

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

X
xujiaqi01 已提交
124
  // Push sparse variables with labels to server in async mode
125 126 127 128 129 130 131 132 133 134 135 136
  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_;
  }
137
  // This is specially designed for click/show stats in server
X
xujiaqi01 已提交
138 139
  // Param<in>: scope, table_id, fea_keys, fea_labels, sparse_key_names,
  //            sparse_grad_names, batch_size, use_cvm, dump_slot
140 141 142 143 144 145 146 147
  // 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,
148
      std::vector<::std::future<int32_t>>* push_sparse_status,
149
      const int batch_size, const bool use_cvm, const bool dump_slot,
150
      std::vector<uint64_t>* sparse_push_keys, const bool no_cvm);
151 152 153 154 155 156 157 158 159 160 161 162 163 164

  // 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 已提交
165
  // init server
166
  void InitServer(const std::string& dist_desc, int index);
X
xujiaqi01 已提交
167
  // init trainer
168 169 170
  void InitWorker(const std::string& dist_desc,
                  const std::vector<uint64_t>& host_sign_list, int node_num,
                  int index);
X
xujiaqi01 已提交
171
  // stop server
172
  void StopServer();
173 174
  // finalize worker to make worker can be stop
  void FinalizeWorker();
X
xujiaqi01 已提交
175
  // run server
176
  uint64_t RunServer();
177 178
  // run server with ip port
  uint64_t RunServer(const std::string& ip, uint32_t port);
X
xujiaqi01 已提交
179
  // gather server ip
180
  void GatherServers(const std::vector<uint64_t>& host_sign_list, int node_num);
X
xjqbest 已提交
181
  // gather client ip
X
xjqbest 已提交
182
  void GatherClients(const std::vector<uint64_t>& host_sign_list);
X
xjqbest 已提交
183
  // get client info
X
xjqbest 已提交
184
  std::vector<uint64_t> GetClientsInfo();
X
xjqbest 已提交
185
  // create client to client connection
X
xjqbest 已提交
186
  void CreateClient2ClientConnection();
187 188
  // flush all push requests
  void ClientFlush();
189 190 191 192
  // 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,
193
                           std::vector<std::string> table_var_list,
194
                           bool load_combine);
195 196

  void PrintTableStat(const uint64_t table_id);
197
  // mode = 0, load all feature
198
  // mode = 1, load delta feature, which means load diff
199
  void LoadModel(const std::string& path, const int mode);
200
  // mode = 0, load all feature
201
  // mode = 1, load delta feature, which means load diff
202 203
  void LoadModelOneTable(const uint64_t table_id, const std::string& path,
                         const int mode);
204 205 206
  // mode = 0, save all feature
  // mode = 1, save delta feature, which means save diff
  void SaveModel(const std::string& path, const int mode);
207 208 209 210 211 212 213
  // 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 已提交
214
  // get save cache threshold
215
  double GetCacheThreshold(int table_id);
X
xujiaqi01 已提交
216
  // shuffle cache model between servers
217 218
  void CacheShuffle(int table_id, const std::string& path, const int mode,
                    const double cache_threshold);
X
xujiaqi01 已提交
219 220
  // save cache model
  // cache model can speed up online predict
221
  int32_t SaveCache(int table_id, const std::string& path, const int mode);
X
xujiaqi01 已提交
222 223 224 225 226 227 228
  // 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
229
  void ClearModel();
230 231
  // clear one table
  void ClearOneTable(const uint64_t table_id);
X
xujiaqi01 已提交
232
  // shrink sparse table
233
  void ShrinkSparseTable(int table_id);
X
xujiaqi01 已提交
234
  // shrink dense table
235
  void ShrinkDenseTable(int table_id, Scope* scope,
236 237
                        std::vector<std::string> var_list, float decay,
                        int emb_dim);
238

D
dongdaxiang 已提交
239
  typedef std::function<int32_t(int, int, const std::string&)> MsgHandlerFunc;
X
xujiaqi01 已提交
240
  // register client to client communication
241
  int RegisterClientToClientMsgHandler(int msg_type, MsgHandlerFunc handler);
X
xjqbest 已提交
242
  // send client to client message
D
dongdaxiang 已提交
243 244
  std::future<int32_t> SendClientToClientMsg(int msg_type, int to_client_id,
                                             const std::string& msg);
X
xujiaqi01 已提交
245
  // FleetWrapper singleton
246 247 248 249 250 251
  static std::shared_ptr<FleetWrapper> GetInstance() {
    if (NULL == s_instance_) {
      s_instance_.reset(new paddle::framework::FleetWrapper());
    }
    return s_instance_;
  }
252 253 254
  // this performs better than rand_r, especially large data
  std::default_random_engine& LocalRandomEngine();

255 256 257 258
#ifdef PADDLE_WITH_PSLIB
  static std::shared_ptr<paddle::distributed::PSlib> pslib_ptr_;
#endif

259 260
 private:
  static std::shared_ptr<FleetWrapper> s_instance_;
X
xjqbest 已提交
261
#ifdef PADDLE_WITH_PSLIB
X
xujiaqi01 已提交
262
  std::map<uint64_t, std::vector<paddle::ps::Region>> _regions;
X
xjqbest 已提交
263
#endif
264

265
 protected:
266
  static bool is_initialized_;
267
  bool scale_sparse_gradient_with_batch_size_;
268
  int32_t sleep_seconds_before_fail_exit_;
269 270 271
  int client2client_request_timeout_ms_;
  int client2client_connect_timeout_ms_;
  int client2client_max_retry_;
272 273 274 275
  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_;
276 277 278 279 280
  DISABLE_COPY_AND_ASSIGN(FleetWrapper);
};

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