fleet_wrapper.cc 12.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (c) 2019 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.

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/* 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. */

#include "paddle/fluid/framework/fleet/fleet_wrapper.h"
X
xujiaqi01 已提交
30
#include <utility>
31
#include "paddle/fluid/framework/data_feed.h"
32 33 34 35 36 37

namespace paddle {
namespace framework {

const uint32_t MAX_FEASIGN_NUM = 1024 * 100 * 100;
std::shared_ptr<FleetWrapper> FleetWrapper::s_instance_ = NULL;
38 39
bool FleetWrapper::is_initialized_ = false;

40
#ifdef PADDLE_WITH_PSLIB
D
dongdaxiang 已提交
41 42 43
template <class AR>
paddle::ps::Archive<AR>& operator<<(paddle::ps::Archive<AR>& ar,
                                    const MultiSlotType& ins) {
44 45 46 47
  ar << ins.GetType();
  ar << ins.GetOffset();
  ar << ins.GetFloatData();
  ar << ins.GetUint64Data();
X
xujiaqi01 已提交
48
  return ar;
49 50
}

D
dongdaxiang 已提交
51 52 53
template <class AR>
paddle::ps::Archive<AR>& operator>>(paddle::ps::Archive<AR>& ar,
                                    MultiSlotType& ins) {
54 55 56 57
  ar >> ins.MutableType();
  ar >> ins.MutableOffset();
  ar >> ins.MutableFloatData();
  ar >> ins.MutableUint64Data();
X
xujiaqi01 已提交
58
  return ar;
59 60 61
}
#endif

62 63 64
#ifdef PADDLE_WITH_PSLIB
std::shared_ptr<paddle::distributed::PSlib> FleetWrapper::pslib_ptr_ = NULL;
#endif
65 66 67 68

void FleetWrapper::InitServer(const std::string& dist_desc, int index) {
#ifdef PADDLE_WITH_PSLIB
  if (!is_initialized_) {
D
dongdaxiang 已提交
69
    VLOG(3) << "Going to init server";
70 71 72 73 74
    pslib_ptr_ = std::shared_ptr<paddle::distributed::PSlib>(
        new paddle::distributed::PSlib());
    pslib_ptr_->init_server(dist_desc, index);
    is_initialized_ = true;
  } else {
D
dongdaxiang 已提交
75
    VLOG(3) << "Server can be initialized only once";
76 77 78 79 80 81 82 83 84
  }
#endif
}

void FleetWrapper::InitWorker(const std::string& dist_desc,
                              const std::vector<uint64_t>& host_sign_list,
                              int node_num, int index) {
#ifdef PADDLE_WITH_PSLIB
  if (!is_initialized_) {
D
dongdaxiang 已提交
85
    VLOG(3) << "Going to init worker";
86 87 88 89 90 91 92
    pslib_ptr_ = std::shared_ptr<paddle::distributed::PSlib>(
        new paddle::distributed::PSlib());
    pslib_ptr_->init_worker(dist_desc,
                            const_cast<uint64_t*>(host_sign_list.data()),
                            node_num, index);
    is_initialized_ = true;
  } else {
D
dongdaxiang 已提交
93
    VLOG(3) << "Worker can be initialized only once";
94 95 96 97 98 99
  }
#endif
}

void FleetWrapper::StopServer() {
#ifdef PADDLE_WITH_PSLIB
D
dongdaxiang 已提交
100
  VLOG(3) << "Going to stop server";
101 102 103 104 105 106
  pslib_ptr_->stop_server();
#endif
}

uint64_t FleetWrapper::RunServer() {
#ifdef PADDLE_WITH_PSLIB
D
dongdaxiang 已提交
107
  VLOG(3) << "Going to run server";
108 109 110 111 112 113 114 115 116
  return pslib_ptr_->run_server();
#else
  return 0;
#endif
}

void FleetWrapper::GatherServers(const std::vector<uint64_t>& host_sign_list,
                                 int node_num) {
#ifdef PADDLE_WITH_PSLIB
D
dongdaxiang 已提交
117
  VLOG(3) << "Going to gather server ips";
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
  pslib_ptr_->gather_servers(const_cast<uint64_t*>(host_sign_list.data()),
                             node_num);
#endif
}

void FleetWrapper::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, int fea_value_dim) {
#ifdef PADDLE_WITH_PSLIB
  std::vector<::std::future<int32_t>> pull_sparse_status;
  pull_sparse_status.resize(0);
  fea_keys->clear();
  fea_keys->resize(0);
  fea_keys->reserve(MAX_FEASIGN_NUM);
  for (auto name : var_names) {
    Variable* var = scope.FindVar(name);
    LoDTensor* tensor = var->GetMutable<LoDTensor>();
    int64_t* ids = tensor->data<int64_t>();
    int len = tensor->numel();
    for (auto i = 0u; i < len; ++i) {
      if (ids[i] == 0u) {
        continue;
      }
      fea_keys->push_back(static_cast<uint64_t>(ids[i]));
    }
    fea_values->resize(fea_keys->size() + 1);
    for (auto& t : *fea_values) {
      t.resize(fea_value_dim);
    }
    std::vector<float*> pull_result_ptr;
    for (auto& t : *fea_values) {
      pull_result_ptr.push_back(t.data());
    }
    auto status = pslib_ptr_->_worker_ptr->pull_sparse(
        pull_result_ptr.data(), table_id, fea_keys->data(), fea_keys->size());
    pull_sparse_status.push_back(std::move(status));
  }
  for (auto& t : pull_sparse_status) {
    t.wait();
    auto status = t.get();
    if (status != 0) {
      LOG(ERROR) << "fleet pull sparse failed, status[" << status << "]";
      exit(-1);
    }
  }
#endif
}

void FleetWrapper::PullDenseVarsAsync(
    const Scope& scope, const uint64_t tid,
    const std::vector<std::string>& var_names,
    std::vector<::std::future<int32_t>>* pull_dense_status) {
#ifdef PADDLE_WITH_PSLIB
  std::vector<paddle::ps::Region> regions;
173 174 175
  regions.resize(var_names.size());
  for (auto i = 0u; i < var_names.size(); ++i) {
    Variable* var = scope.FindVar(var_names[i]);
176 177 178
    LoDTensor* tensor = var->GetMutable<LoDTensor>();
    float* w = tensor->data<float>();
    paddle::ps::Region reg(w, tensor->numel());
179
    regions[i] = std::move(reg);
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
  }
  auto status =
      pslib_ptr_->_worker_ptr->pull_dense(regions.data(), regions.size(), tid);
  pull_dense_status->push_back(std::move(status));
#endif
}

void FleetWrapper::PullDenseVarsSync(
    const Scope& scope, const uint64_t tid,
    const std::vector<std::string>& var_names) {
#ifdef PADDLE_WITH_PSLIB
  std::vector<paddle::ps::Region> regions;
  regions.reserve(var_names.size());
  for (auto& t : var_names) {
    Variable* var = scope.FindVar(t);
    LoDTensor* tensor = var->GetMutable<LoDTensor>();
    float* w = tensor->data<float>();
    paddle::ps::Region reg(w, tensor->numel());
    regions.emplace_back(std::move(reg));
  }
  auto status =
      pslib_ptr_->_worker_ptr->pull_dense(regions.data(), regions.size(), tid);
  status.wait();
#endif
}

D
dongdaxiang 已提交
206 207 208 209
void FleetWrapper::PushDenseVarsSync(
    Scope* scope, const uint64_t table_id,
    const std::vector<std::string>& var_names) {}

210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
void FleetWrapper::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) {
#ifdef PADDLE_WITH_PSLIB
  std::vector<paddle::ps::Region> regions;
  for (auto& t : var_names) {
    Variable* var = scope.FindVar(t);
    LoDTensor* tensor = var->GetMutable<LoDTensor>();
    int count = tensor->numel();
    float* g = tensor->data<float>();
    paddle::ps::Region reg(g, count);
    regions.emplace_back(std::move(reg));
  }
  auto status = pslib_ptr_->_worker_ptr->push_dense(regions.data(),
                                                    regions.size(), table_id);
  push_sparse_status->push_back(std::move(status));
#endif
}

void FleetWrapper::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,
    std::vector<::std::future<int32_t>>* push_sparse_status) {
#ifdef PADDLE_WITH_PSLIB
  int offset = 2;
  uint64_t fea_idx = 0u;
  for (size_t i = 0; i < sparse_key_names.size(); ++i) {
241 242 243 244
    LOG(WARNING) << "sparse key names[" << i << "]: " << sparse_key_names[i];
    LOG(WARNING) << "sparse grad names[" << i << "]: " << sparse_grad_names[i];
    Variable* g_var = scope.FindVar(sparse_grad_names[i]);
    CHECK(g_var != nullptr) << "var[" << sparse_grad_names[i] << "] not found";
245 246 247 248 249 250 251 252 253 254 255 256 257 258
    LoDTensor* g_tensor = g_var->GetMutable<LoDTensor>();
    if (g_tensor == NULL) {
      LOG(ERROR) << "var[" << sparse_key_names[i] << "] not found";
      exit(-1);
    }
    float* g = g_tensor->data<float>();
    Variable* var = scope.FindVar(sparse_key_names[i]);
    CHECK(var != nullptr) << "var[" << sparse_key_names[i] << "] not found";
    LoDTensor* tensor = var->GetMutable<LoDTensor>();
    if (tensor == NULL) {
      LOG(ERROR) << "var[" << sparse_key_names[i] << "] not found";
      exit(-1);
    }
    int len = tensor->numel();
259
    LOG(WARNING) << " tensor len: " << len;
260
    int64_t* ids = tensor->data<int64_t>();
261 262 263 264 265
    push_values->resize(fea_keys.size() + 1);
    for (auto& t : *push_values) {
      t.resize(emb_dim + offset);
    }

266 267 268 269 270
    for (auto id_idx = 0u; id_idx < len; ++id_idx) {
      if (ids[id_idx] == 0) {
        g += emb_dim;
        continue;
      }
271
      LOG(WARNING) << "going to memcpy";
272 273
      memcpy((*push_values)[fea_idx].data() + offset, g,
             sizeof(float) * emb_dim);
274
      LOG(WARNING) << "show";
275
      (*push_values)[fea_idx][0] = 1.0f;
276
      LOG(WARNING) << "click";
277
      (*push_values)[fea_idx][1] = static_cast<float>(fea_labels[fea_idx]);
278
      LOG(WARNING) << "offset";
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
      g += emb_dim;
      fea_idx++;
    }
  }
  CHECK(fea_idx == fea_keys.size()) << "fea_idx: " << fea_idx
                                    << "features size: " << fea_keys.size();
  std::vector<float*> push_g_vec;
  for (auto i = 0u; i < fea_keys.size(); ++i) {
    push_g_vec.push_back((*push_values)[i].data());
  }
  auto status = pslib_ptr_->_worker_ptr->push_sparse(
      table_id, fea_keys.data(), (const float**)push_g_vec.data(),
      fea_keys.size());
  push_sparse_status->push_back(std::move(status));

#endif
}

297
int FleetWrapper::RegisterClientToClientMsgHandler(
X
xujiaqi01 已提交
298
    int msg_type, MsgHandlerFunc handler) {
299
#ifdef PADDLE_WITH_PSLIB
X
xujiaqi01 已提交
300 301 302
  VLOG(3) << "calling FleetWrapper::RegisterClientToClientMsgHandler";
  VLOG(3) << "pslib_ptr_=" << pslib_ptr_;
  VLOG(3) << "_worker_ptr=" << pslib_ptr_->_worker_ptr;
X
xujiaqi01 已提交
303 304
  pslib_ptr_->_worker_ptr->registe_client2client_msg_handler(
      msg_type, handler);
305 306 307 308
#else
  VLOG(0) << "FleetWrapper::RegisterClientToClientMsgHandler"
          << " does nothing when no pslib";
#endif
X
xujiaqi01 已提交
309
  return 0;
310 311
}

312
int FleetWrapper::SendClientToClientMsg(
X
xujiaqi01 已提交
313
    int msg_type, int to_client_id, const std::string& msg) {
314
#ifdef PADDLE_WITH_PSLIB
X
xujiaqi01 已提交
315 316
  pslib_ptr_->_worker_ptr->send_client2client_msg(
      msg_type, to_client_id, msg);
317 318 319 320
#else
  VLOG(0) << "FleetWrapper::SendClientToClientMsg"
          << " does nothing when no pslib";
#endif
X
xujiaqi01 已提交
321 322 323
  return 0;
}

324
std::default_random_engine& FleetWrapper::LocalRandomEngine() {
X
xujiaqi01 已提交
325 326 327 328 329 330 331
  struct engine_wrapper_t {
    std::default_random_engine engine;
    engine_wrapper_t() {
      struct timespec tp;
      clock_gettime(CLOCK_REALTIME, &tp);
      double cur_time = tp.tv_sec + tp.tv_nsec * 1e-9;
      static std::atomic<uint64_t> x(0);
D
dongdaxiang 已提交
332
      std::seed_seq sseq = {x++, x++, x++, (uint64_t)(cur_time * 1000)};
X
xujiaqi01 已提交
333 334 335 336 337
      engine.seed(sseq);
    }
  };
  thread_local engine_wrapper_t r;
  return r.engine;
338 339
}

D
dongdaxiang 已提交
340
template <typename T>
X
xujiaqi01 已提交
341
void FleetWrapper::Serialize(const T& t, std::string* str) {
342 343 344
#ifdef PADDLE_WITH_PSLIB
  paddle::ps::BinaryArchive ar;
  ar << t;
X
xujiaqi01 已提交
345
  *str = std::string(ar.buffer(), ar.length());
346
#else
347
  VLOG(0) << "FleetWrapper::Serialize does nothing when no pslib";
348 349 350
#endif
}

D
dongdaxiang 已提交
351
template <typename T>
X
xujiaqi01 已提交
352
void FleetWrapper::Deserialize(T* t, const std::string& str) {
353 354 355
#ifdef PADDLE_WITH_PSLIB
  paddle::ps::BinaryArchive ar;
  ar.set_read_buffer(const_cast<char*>(str.c_str()), str.length(), nullptr);
X
xujiaqi01 已提交
356
  *t = ar.get<T>();
357
#else
358
  VLOG(0) << "FleetWrapper::Deserialize does nothing when no pslib";
359 360 361 362
#endif
}

template void FleetWrapper::Serialize<std::vector<MultiSlotType>>(
X
xujiaqi01 已提交
363
    const std::vector<MultiSlotType>&, std::string*);
D
dongdaxiang 已提交
364 365
template void FleetWrapper::Deserialize(std::vector<MultiSlotType>*,
                                        const std::string&);
366

367 368
}  // end namespace framework
}  // end namespace paddle