communicator.cc 55.5 KB
Newer Older
T
tangwei12 已提交
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
#include "paddle/fluid/distributed/ps/service/communicator/communicator.h"
16

17
#include <google/protobuf/text_format.h>
18

19
#include "gflags/gflags.h"
20
#include "paddle/fluid/distributed/ps/service/brpc_ps_client.h"
21
#include "paddle/fluid/distributed/ps/wrapper/fleet.h"
T
tangwei12 已提交
22
#include "paddle/fluid/platform/profiler.h"
23
#include "paddle/fluid/string/string_helper.h"
T
tangwei12 已提交
24

25 26 27
#define LEARNING_RATE_DECAY_COUNTER "@LR_DECAY_COUNTER@"
#define STEP_COUNTER "@PS_STEP_COUNTER@"

T
tangwei12 已提交
28 29 30 31
namespace paddle {
namespace distributed {

using framework::LoDTensor;
32
using phi::SelectedRows;
T
tangwei12 已提交
33

Y
yaoxuefeng 已提交
34 35
const uint32_t MAX_FEASIGN_NUM = 1024 * 100 * 100;

T
tangwei12 已提交
36 37 38 39 40 41 42 43
inline double GetCurrentUS() {
  struct timeval time;
  gettimeofday(&time, NULL);
  return 1e+6 * time.tv_sec + time.tv_usec;
}

Communicator::Communicator() {}

Z
zhaocaibei123 已提交
44
void Communicator::InitGFlag(const std::string &gflags) {
45
  VLOG(3) << "Init With Gflags:" << gflags;
T
tangwei12 已提交
46 47 48 49 50 51 52 53 54 55 56
  std::vector<std::string> flags = paddle::string::split_string(gflags);
  if (flags.size() < 1) {
    flags.push_back("-max_body_size=314217728");
    flags.push_back("-bthread_concurrency=40");
    flags.push_back("-socket_max_unwritten_bytes=2048000000");
    flags.push_back("-max_connection_pool_size=1950");
  }
  auto it = flags.begin();
  flags.insert(it, "exe default");
  char *flags_ptr[flags.size()];
  for (size_t i = 0; i < flags.size(); ++i) {
57
    flags_ptr[i] = (char *)(flags[i].c_str());  // NOLINT
T
tangwei12 已提交
58 59 60
  }
  int params_cnt = flags.size();
  char **params_ptr = &(flags_ptr[0]);
61
  ::GFLAGS_NAMESPACE::ParseCommandLineFlags(&params_cnt, &params_ptr, true);
T
tangwei12 已提交
62 63 64 65 66 67 68 69
}

std::once_flag Communicator::init_flag_;
std::shared_ptr<Communicator> Communicator::communicator_(nullptr);

void Communicator::InitBrpcClient(
    const std::string &dist_desc,
    const std::vector<std::string> &host_sign_list) {
70
  auto fleet = paddle::distributed::FleetWrapper::GetInstance();
T
tangwei12 已提交
71
  if (_worker_ptr.get() == nullptr) {
72
    _worker_ptr = fleet->worker_ptr_;
T
tangwei12 已提交
73 74 75 76
  }
  return;
}

Z
zhaocaibei123 已提交
77
std::vector<uint64_t> Communicator::GetClientInfo() {
Z
zhaocaibei123 已提交
78
  std::vector<uint64_t> res = _ps_env.GetClientInfo();
Z
zhaocaibei123 已提交
79 80 81 82 83 84 85 86
  for (auto rr : res) {
    VLOG(2) << "Communicator::GetClientInfo " << rr;
  }
  return res;
}

int Communicator::SetClients(std::vector<uint64_t> &host_sign_list) {
  int node = host_sign_list.size();
Z
zhaocaibei123 已提交
87
  return _ps_env.SetPsClients(host_sign_list.data(), node);
Z
zhaocaibei123 已提交
88 89
}

T
tangwei12 已提交
90
void Communicator::RpcRecvDense(const std::vector<std::string> &varnames,
91
                                int table_id,
92
                                Scope *scope) {  // pserver_scope_
93 94 95
  platform::RecordEvent record_event("Communicator->RpcRecvDense",
                                     platform::TracerEventType::Communication,
                                     1);
T
tangwei12 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108
  std::vector<paddle::distributed::Region> regions;
  regions.reserve(varnames.size());
  for (auto &t : varnames) {
    Variable *var = scope->Var(t);
    LoDTensor *tensor = var->GetMutable<LoDTensor>();
    if (platform::is_gpu_place(tensor->place())) {
#ifdef PADDLE_WITH_CUDA
      Variable *temp_var = xpu_temp_scope_->Var(t);
      LoDTensor *temp_tensor = temp_var->GetMutable<LoDTensor>();
      temp_tensor->Resize(tensor->dims());
      float *temp_data = temp_tensor->mutable_data<float>(platform::CPUPlace());
      paddle::distributed::Region reg(temp_data, tensor->numel());
      regions.emplace_back(std::move(reg));
109
      VLOG(1) << "Communicator::RpcRecvDense Var " << t << " table_id "
T
tangwei12 已提交
110 111 112 113 114 115 116 117 118 119
              << table_id << " Temp_data[0] " << temp_data[0]
              << " Temp_data[-1] " << temp_data[tensor->numel() - 1];
#endif
    } else {
      float *w = tensor->mutable_data<float>(tensor->place());
      paddle::distributed::Region reg(w, tensor->numel());
      regions.emplace_back(std::move(reg));
    }
  }
  auto status =
Z
zhaocaibei123 已提交
120
      _worker_ptr->PullDense(regions.data(), regions.size(), table_id);
T
tangwei12 已提交
121 122 123 124 125
  status.wait();

  for (auto &t : varnames) {
    Variable *var = scope->FindVar(t);
    LoDTensor *tensor = var->GetMutable<LoDTensor>();
126
    VLOG(3) << "Communicator::RecvNoBarrier Var " << t << " On gpu? "
T
tangwei12 已提交
127
            << platform::is_gpu_place(tensor->place());
Z
zhaocaibei123 已提交
128 129

    float *temp_recv_data = tensor->mutable_data<float>(platform::CPUPlace());
130
    VLOG(3) << "Communicator::RpcRecvDense Var " << t << " table_id "
Z
zhaocaibei123 已提交
131 132
            << table_id << " Temp_data[0] " << temp_recv_data[0]
            << " Temp_data[-1] " << temp_recv_data[tensor->numel() - 1];
T
tangwei12 已提交
133 134 135 136 137 138
    if (platform::is_gpu_place(tensor->place())) {
#ifdef PADDLE_WITH_CUDA
      LoDTensor *temp_tensor =
          xpu_temp_scope_->FindVar(t)->GetMutable<LoDTensor>();
      framework::TensorCopy(*temp_tensor, tensor->place(), tensor);
      float *temp_data = temp_tensor->mutable_data<float>(platform::CPUPlace());
139
      VLOG(1) << "Communicator::RpcRecvDense Var " << t << " table_id "
T
tangwei12 已提交
140 141 142 143 144 145 146 147 148 149
              << table_id << " Temp_data[0] " << temp_data[0]
              << " Temp_data[-1] " << temp_data[tensor->numel() - 1];
#endif
    }
  }

  return;
}

void Communicator::RpcSendDenseParam(const std::vector<std::string> &varnames,
150 151
                                     int table_id,
                                     const Scope &scope) {
152 153 154
  platform::RecordEvent record_event("Communicator->RpcSendDenseParam",
                                     platform::TracerEventType::Communication,
                                     1);
T
tangwei12 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
  auto place = platform::CPUPlace();
  std::vector<paddle::distributed::Region> regions;
  for (auto &t : varnames) {
    Variable *var = scope.FindVar(t);
    CHECK(var != nullptr) << "var[" << t << "] not found";
    LoDTensor *tensor = var->GetMutable<LoDTensor>();
    if (platform::is_gpu_place(tensor->place())) {
#ifdef PADDLE_WITH_CUDA
      Variable *temp_var = xpu_temp_scope_->Var(t);
      LoDTensor *temp_tensor = temp_var->GetMutable<LoDTensor>();
      temp_tensor->Resize(tensor->dims());
      float *temp_data = temp_tensor->mutable_data<float>(platform::CPUPlace());
      framework::TensorCopy(*tensor, platform::CPUPlace(), temp_tensor);
      paddle::distributed::Region reg(temp_data, tensor->numel());
      regions.emplace_back(std::move(reg));
170 171 172
      VLOG(1) << "rpc_send_dense_param Var " << t << " table_id " << table_id
              << " Temp_data[0] " << temp_data[0] << " Temp_data[-1] "
              << temp_data[tensor->numel() - 1];
T
tangwei12 已提交
173 174 175 176
#endif
    } else {
      float *w = tensor->mutable_data<float>(place);
      paddle::distributed::Region reg(w, tensor->numel());
177 178 179 180
      regions.emplace_back(reg);
      VLOG(1) << "rpc_send_dense_param Var " << t << " talbe_id " << table_id
              << " Temp_data[0] " << w[0] << " Temp_data[-1] "
              << w[tensor->numel() - 1];
T
tangwei12 已提交
181 182 183
    }
  }
  auto status =
Z
zhaocaibei123 已提交
184
      _worker_ptr->PushDenseParam(regions.data(), regions.size(), table_id);
T
tangwei12 已提交
185 186 187 188 189
  status.wait();
  VLOG(4) << "RPC Send Dense Param " << table_id << " done!";
  return;
}

190 191
void Communicator::RpcSendDense(const CommContext &ctx,
                                const Scope &scope) {  // delta_scope_
192 193 194
  platform::RecordEvent record_event("Communicator->RpcSendDense",
                                     platform::TracerEventType::Communication,
                                     1);
T
tangwei12 已提交
195 196 197
  auto &var_names = ctx.origin_varnames;
  auto &table_id = ctx.table_id;
  auto dense_data = std::make_shared<std::vector<float>>();
Z
zhaocaibei123 已提交
198
  size_t request_call_num = _worker_ptr->GetServerNums();
T
tangwei12 已提交
199
  uint32_t num_per_shard =
Z
zhaocaibei123 已提交
200
      DenseDimPerShard(ctx.height_sections[0], request_call_num);
T
tangwei12 已提交
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
  dense_data->resize(num_per_shard *
                     request_call_num);  // accessor->update_dim() = 1
  float *data = dense_data->data();
  uint32_t pos = 0;
  for (size_t i = 0; i < var_names.size(); ++i) {
    const LoDTensor tensor = scope.FindVar(var_names[i])->Get<LoDTensor>();
    size_t count = static_cast<size_t>(tensor.numel());
    const float *g = tensor.data<float>();
    CHECK(pos + count <= dense_data->size())
        << "invalid dense size, cur pos[" << pos << "]"
        << " data_num[" << count << "] size[" << dense_data->size() << "]";
    memcpy(data + pos, g, count * sizeof(float));
    pos += count;
  }

  ++_async_call_num;
  DownpourBrpcClosure *closure = new DownpourBrpcClosure(
      request_call_num, [this, request_call_num](void *done) {
        int ret = 0;
220
        auto *closure = (DownpourBrpcClosure *)done;  // NOLINT
T
tangwei12 已提交
221 222 223 224 225 226 227 228 229
        for (size_t i = 0; i < request_call_num; ++i) {
          if (closure->check_response(i, PS_PUSH_DENSE_TABLE) != 0) {
            ret = -1;
            break;
          }
        }
        closure->set_promise_value(ret);
        --_async_call_num;
      });
230 231
  auto status = _worker_ptr->PushDenseRawGradient(
      table_id, data, dense_data->size(), closure);
T
tangwei12 已提交
232 233 234 235
  status.wait();
  return;
}

236 237
void Communicator::RpcSendSparseParam(const std::string &varname,
                                      int table_id,
T
tangwei12 已提交
238
                                      const Scope &scope) {
239 240 241
  platform::RecordEvent record_event("Communicator->RpcSendSparseParam",
                                     platform::TracerEventType::Communication,
                                     1);
Z
zhaocaibei123 已提交
242
  size_t request_call_num = _worker_ptr->GetServerNums();
T
tangwei12 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
  std::vector<float *> push_g_vec;

  auto *send_var = scope.FindVar(varname);
  auto *tensor = send_var->GetMutable<framework::LoDTensor>();
  auto dim = tensor->dims()[1];
  uint64_t sparse_num = static_cast<uint64_t>(tensor->dims()[0]);
  std::vector<uint64_t> sparse_push_keys(sparse_num);
  std::iota(sparse_push_keys.begin(), sparse_push_keys.end(), 0);
  push_g_vec.reserve(sparse_num);

  for (auto i = 0; i < static_cast<int>(sparse_push_keys.size()); ++i) {
    push_g_vec.push_back(tensor->data<float>() + i * dim);
  }

  DownpourBrpcClosure *closure = new DownpourBrpcClosure(
      request_call_num, [this, request_call_num](void *done) {
        int ret = 0;
260
        auto *closure = (DownpourBrpcClosure *)done;  // NOLINT
T
tangwei12 已提交
261 262 263 264 265 266 267 268
        for (size_t i = 0; i < request_call_num; ++i) {
          if (closure->check_response(i, PS_PUSH_SPARSE_PARAM) != 0) {
            ret = -1;
            break;
          }
        }
        closure->set_promise_value(ret);
      });
269 270
  auto status = _worker_ptr->PushSparseParam(table_id,
                                             sparse_push_keys.data(),
Z
zhaocaibei123 已提交
271
                                             (const float **)push_g_vec.data(),
272 273
                                             sparse_push_keys.size(),
                                             closure);
T
tangwei12 已提交
274 275 276 277
  status.wait();
  return;
}

278 279
void Communicator::RpcSendSparse(const std::string &var_name,
                                 int table_id,
T
tangwei12 已提交
280
                                 const Scope &scope) {
281 282 283
  platform::RecordEvent record_event("Communicator->RpcSendSparse",
                                     platform::TracerEventType::Communication,
                                     1);
Z
zhaocaibei123 已提交
284
  size_t request_call_num = _worker_ptr->GetServerNums();
T
tangwei12 已提交
285 286 287 288
  std::vector<uint64_t> sparse_push_keys;
  std::vector<float *> push_g_vec;

  auto *send_var = scope.FindVar(var_name);
289
  auto *tensor = send_var->GetMutable<phi::SelectedRows>();
T
tangwei12 已提交
290
  auto dim = tensor->value().dims()[1];
291 292
  std::transform(tensor->rows().begin(),
                 tensor->rows().end(),
T
tangwei12 已提交
293
                 std::back_inserter(sparse_push_keys),
C
Chengmo 已提交
294
                 [&](int64_t id) { return static_cast<uint64_t>(id); });
T
tangwei12 已提交
295 296 297 298 299

  for (auto i = 0; i < static_cast<int>(sparse_push_keys.size()); ++i) {
    push_g_vec.push_back(tensor->mutable_value()->data<float>() + i * dim);
  }

300 301 302 303 304 305 306 307 308 309 310 311
  // TODO(wangguanqun): padding_idx is not ignored, this is a bug.
  // if padding_idx == padding in datareader, the server will core.
  /*
  for (size_t i = 0; i < tensor->rows().size(); ++i) {
    uint64_t real_id = static_cast<uint64_t>(tensor->rows()[i]);
    if (real_id != 0) {
      sparse_push_keys.push_back(real_id);
      push_g_vec.push_back(tensor->mutable_value()->data<float>() + i * dim);
    }
  }
  */

T
tangwei12 已提交
312 313 314 315
  ++_async_call_num;
  DownpourBrpcClosure *closure = new DownpourBrpcClosure(
      request_call_num, [this, request_call_num](void *done) {
        int ret = 0;
316
        auto *closure = (DownpourBrpcClosure *)done;  // NOLINT
T
tangwei12 已提交
317 318 319 320 321 322 323 324 325
        for (size_t i = 0; i < request_call_num; ++i) {
          if (closure->check_response(i, PS_PUSH_SPARSE_TABLE) != 0) {
            ret = -1;
            break;
          }
        }
        closure->set_promise_value(ret);
        --_async_call_num;
      });
326 327 328 329 330 331
  auto status =
      _worker_ptr->PushSparseRawGradient(table_id,
                                         sparse_push_keys.data(),
                                         (const float **)push_g_vec.data(),
                                         sparse_push_keys.size(),
                                         closure);
T
tangwei12 已提交
332 333 334 335
  status.wait();
  return;
}

336 337
void Communicator::RpcRecvSparse(const std::string &varname,
                                 int table_id,
T
tangwei12 已提交
338
                                 Scope *scope) {
339 340 341
  platform::RecordEvent record_event("Communicator->RpcRecvSparse",
                                     platform::TracerEventType::Communication,
                                     1);
T
tangwei12 已提交
342 343 344 345 346
  auto *send_var = scope->Var(varname);
  auto *tensor = send_var->GetMutable<framework::LoDTensor>();
  auto dim = tensor->dims()[1];
  uint64_t sparse_num = static_cast<uint64_t>(tensor->dims()[0]);

347 348
  std::vector<uint64_t> sparse_pull_keys(sparse_num);
  std::iota(sparse_pull_keys.begin(), sparse_pull_keys.end(), 0);
T
tangwei12 已提交
349

350 351 352
  std::vector<float *> pull_g_vec;
  for (auto i = 0; i < static_cast<int>(sparse_pull_keys.size()); ++i) {
    pull_g_vec.push_back(tensor->data<float>() + i * dim);
T
tangwei12 已提交
353 354
  }

355 356
  bool training = true;

L
Leo Chen 已提交
357
  auto status =
358
      _worker_ptr->PullSparseParam(static_cast<float **>(pull_g_vec.data()),
L
Leo Chen 已提交
359
                                   table_id,
360 361
                                   sparse_pull_keys.data(),
                                   sparse_pull_keys.size(),
L
Leo Chen 已提交
362
                                   training);
T
tangwei12 已提交
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
  status.wait();
  return;
}

void Communicator::InitParams(const RecvCtxMap &recv_varname_to_ctx) {
  if (trainer_id_ == 0) {
    for (auto &iter : recv_varname_to_ctx) {
      auto &table_id = iter.first;
      auto &varnames = iter.second;
      RpcSendDenseParam(varnames, table_id, *recv_scope_);
      VLOG(1) << "push dense param to table " << table_id
              << " from 0' trainer done";
    }
  }
  return;
}

380 381 382 383 384 385 386 387 388 389 390
void Communicator::PullDense(const RecvCtxMap &recv_varname_to_ctx) {
  for (auto &iter : recv_varname_to_ctx) {
    auto &table_id = iter.first;
    auto &varnames = iter.second;
    RpcRecvDense(varnames, table_id, recv_scope_);
    VLOG(1) << "pull dense param to table " << table_id
            << " from 0' trainer done";
  }
  return;
}

T
tangwei12 已提交
391 392 393 394 395
void Communicator::RpcProfilerControl() {
  if (trainer_id_ == 0) {
    if (!do_server_profiler_ && platform::IsProfileEnabled()) {
      // send profiler start flag
      do_server_profiler_ = true;
Z
zhaocaibei123 已提交
396
      auto start_status = _worker_ptr->StartProfiler();
T
tangwei12 已提交
397 398 399
      start_status.wait();
    } else if (do_server_profiler_ && !platform::IsProfileEnabled()) {
      // send profiler end flag
Z
zhaocaibei123 已提交
400
      auto stop_status = _worker_ptr->StopProfiler();
T
tangwei12 已提交
401 402 403 404 405 406
      stop_status.wait();
      do_server_profiler_ = false;
    }
  }
}

407 408
void Communicator::SendGlobalStep(const CommContext &ctx,
                                  int batches,
409 410 411 412
                                  Scope *send_scope) {
  if (batches == 0) {
    return;
  }
413 414 415
  platform::RecordEvent record_event("Communicator->SendGlobalStep",
                                     platform::TracerEventType::Communication,
                                     1);
416
  auto &table_id = ctx.table_id;
Z
zhaocaibei123 已提交
417
  size_t request_call_num = _worker_ptr->GetServerNums();
418 419 420 421 422 423 424 425 426 427

  auto &var_name = STEP_COUNTER;
  auto *out_var = send_scope->Var(var_name);
  auto *out_t = out_var->GetMutable<framework::LoDTensor>();
  auto *data = out_t->mutable_data<int64_t>({1}, platform::CPUPlace());
  data[0] = static_cast<int64_t>(batches);
  VLOG(3) << "Communicator::SendGlobalStep send: " << batches;
  DownpourBrpcClosure *closure = new DownpourBrpcClosure(
      request_call_num, [this, request_call_num](void *done) {
        int ret = 0;
428
        auto *closure = (DownpourBrpcClosure *)done;  // NOLINT
429 430 431 432 433 434 435 436
        for (size_t i = 0; i < request_call_num; ++i) {
          if (closure->check_response(i, PS_PUSH_GLOBAL_STEP) != 0) {
            ret = -1;
            break;
          }
        }
        closure->set_promise_value(ret);
      });
Z
zhaocaibei123 已提交
437
  auto status = _worker_ptr->PushGlobalStep(table_id, data, closure);
438 439 440 441
  status.wait();
  return;
}

T
tangwei12 已提交
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
void AsyncCommunicator::RecvThread() {
  if (!independent_recv_) return;
  VLOG(3) << "Independent RecvThread Start and Wait";

  while (running_) {
    int grad_num = grad_num_.load();
    if (grad_num > min_send_grad_num_before_recv_) {
      RecvByCommunicator();
      grad_num_.store(0);
    } else {
      std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
  }
  VLOG(1) << "communicator stopped, independent recv thread exit";
}

void AsyncCommunicator::RecvByCommunicator() {
  if (!running_) return;
  RecvNoBarrier();
  VLOG(3) << "run recv graph end";
}

void AsyncCommunicator::RecvNoBarrier() {
  for (auto &iter : recv_varname_to_ctx_) {
    auto &table_id = iter.first;
    auto &varnames = iter.second;
    RpcRecvDense(varnames, table_id, recv_scope_);
  }

  for (auto &iter : recv_varname_to_ctx_) {
    auto var_names = iter.second;
    for (auto &t : var_names) {
      Variable *var = recv_scope_->FindVar(t);
      LoDTensor *tensor = var->GetMutable<LoDTensor>();
476
      VLOG(3) << "AsyncCommunicator::RecvNoBarrier Var " << t << " On gpu? "
T
tangwei12 已提交
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
              << platform::is_gpu_place(tensor->place());
      if (platform::is_gpu_place(tensor->place())) {
#ifdef PADDLE_WITH_CUDA
        LoDTensor *temp_tensor =
            xpu_temp_scope_->FindVar(t)->GetMutable<LoDTensor>();
        framework::TensorCopy(*temp_tensor, tensor->place(), tensor);
#endif
      }
    }
  }

  return;
}

void AsyncCommunicator::SendByCommunicator() {
  std::vector<std::future<void>> tasks;
  tasks.reserve(send_varname_to_ctx_.size());

  for (auto &iter : send_varname_to_ctx_) {
    auto &ctx = iter.second;

    auto send_recv_task = [this, &ctx] {
      auto &varnames = ctx.origin_varnames;
      auto &table_id = ctx.table_id;
      size_t var_nums = varnames.size();
      auto &check_queue = send_varname_to_queue_[varnames[0]];
      std::vector<std::vector<std::shared_ptr<Variable>>> vars;
      vars.resize(var_nums);
      int merged_var_num = 0;
      int wait_times = 0;
      while (merged_var_num < max_merge_var_num_) {
        if (check_queue->Size() == 0) {
          VLOG(4) << "wait_times -> " << wait_times;
          if (wait_times >= send_wait_times_) {
            break;
          }
          std::this_thread::sleep_for(std::chrono::milliseconds(10));
          wait_times++;
          continue;
        } else {
          wait_times = 0;
          for (size_t i = 0; i < var_nums; i++) {
            auto &var_name = varnames[i];
            auto &var_queue = send_varname_to_queue_[var_name];
            vars[i].push_back(var_queue->Pop());
          }
          merged_var_num++;
        }
      }
      if (merged_var_num == 0) return;

      for (size_t i = 0; i < var_nums; i++) {
        auto &var_name = varnames[i];
530 531 532 533 534
        if (var_name == STEP_COUNTER) {
          MergeVars<int64_t>(var_name, vars[i], send_scope_.get(), 1);
        } else {
          MergeVars<float>(var_name, vars[i], send_scope_.get(), 1);
        }
T
tangwei12 已提交
535
      }
Z
zhaocaibei123 已提交
536

537 538 539
      if (ctx.is_tensor_table) {
        SendGlobalStep(ctx, merged_var_num, send_scope_.get());
      } else if (ctx.is_sparse) {
T
tangwei12 已提交
540
        PADDLE_ENFORCE_EQ(
541 542
            varnames.size(),
            1,
T
tangwei12 已提交
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
            platform::errors::InvalidArgument(
                "sparse variables can only be merged by one variables"));
        RpcSendSparse(varnames[0], table_id, *send_scope_);
      } else {
        RpcSendDense(ctx, *send_scope_);
        if (!independent_recv_ &&
            recv_varname_to_ctx_.find(table_id) != recv_varname_to_ctx_.end()) {
          auto recv_varnames = recv_varname_to_ctx_.at(table_id);
          RpcRecvDense(recv_varnames, table_id, recv_scope_);
        }
      }
      if (independent_recv_) {
        grad_num_.fetch_add(1, std::memory_order_relaxed);
      }
    };
    tasks.emplace_back(send_threadpool_->enqueue(std::move(send_recv_task)));
  }
  for (auto &task : tasks) {
    task.wait();
  }
  return;
}

Z
zhaocaibei123 已提交
566 567 568 569 570 571 572
void AsyncCommunicator::PushDensePostProcessing() {
  if (independent_recv_) {
    grad_num_.fetch_add(1, std::memory_order_relaxed);
  }
  return;
}

T
tangwei12 已提交
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
void AsyncCommunicator::MainThread() {
  VLOG(3) << "AsyncCommunicator MainThread start and wait";

  while (waiting_ && running_) {
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    VLOG(3) << "wait for running";
  }

  while (running_) {
    SendByCommunicator();
    RpcProfilerControl();
  }
  VLOG(1) << "communicator stopped, send thread exit";
}

Y
yaoxuefeng 已提交
588
void AsyncCommunicator::PullSparseToTensorSync(
589 590 591 592 593 594 595
    const uint64_t table_id,
    int fea_dim,
    uint64_t padding_id,
    platform::Place place,
    bool is_training,
    std::vector<const LoDTensor *> *inputs,
    std::vector<LoDTensor *> *outputs) {
Y
yaoxuefeng 已提交
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
  std::vector<uint64_t> fea_keys;
  std::vector<float *> pull_result_ptr;
  fea_keys.reserve(MAX_FEASIGN_NUM / 100);
  pull_result_ptr.reserve(MAX_FEASIGN_NUM / 100);
  std::vector<float> init_value(fea_dim, 0);
  framework::LoDTensor *output = nullptr;
  float *output_data = nullptr;
  size_t output_index = -1;
  size_t output_len = 0;
  for (size_t index = 0; index < inputs->size(); ++index) {
    const framework::LoDTensor *tensor = inputs->at(index);
    const int64_t *ids = tensor->data<int64_t>();
    size_t len = tensor->numel();
    for (size_t i = 0; i < len; ++i, output_len += fea_dim) {
      if (!output || output_len == size_t(output->numel())) {
        ++output_index;
        CHECK(output_index < outputs->size());  // NOLINT
        output = outputs->at(output_index);
        output->set_lod(tensor->lod());
        output_data = output->mutable_data<float>(place);
        output_len = 0;
        CHECK(output->numel() % fea_dim == 0);  // NOLINT
        CHECK(output_data != nullptr);          // NOLINT
      }
      uint64_t real_id = static_cast<uint64_t>(ids[i]);
      if (real_id == padding_id) {
622 623
        memcpy(output_data + output_len,
               init_value.data(),
Y
yaoxuefeng 已提交
624 625 626 627 628 629 630
               sizeof(float) * fea_dim);
        continue;
      }
      fea_keys.push_back(real_id);
      pull_result_ptr.push_back(output_data + output_len);
    }
  }
631 632 633 634 635
  auto status = _worker_ptr->PullSparse(pull_result_ptr.data(),
                                        table_id,
                                        fea_keys.data(),
                                        fea_keys.size(),
                                        is_training);
Y
yaoxuefeng 已提交
636 637 638 639 640 641 642 643 644
  status.wait();
  auto ret = status.get();
  if (ret != 0) {
    LOG(ERROR) << "fleet pull sparse failed, status[" << ret << "]";
    sleep(sleep_seconds_before_fail_exit_);
  }
}

void AsyncCommunicator::PushSparseFromTensorAsync(
645 646 647 648 649 650 651
    const uint64_t table_id,
    int fea_dim,
    uint64_t padding_id,
    platform::Place place,
    std::vector<const framework::LoDTensor *> *inputs,
    const framework::LoDTensor *shows,
    const framework::LoDTensor *clks,
Y
yaoxuefeng 已提交
652 653 654 655 656 657 658 659
    std::vector<framework::LoDTensor *> *outputs) {
  int batch_size = -1;
  bool batch_size_consist = true;
  for (auto *input : *inputs) {
    int cur_batch_size =
        input->lod().size() ? input->lod()[0].size() - 1 : input->dims()[0];
    if (batch_size == -1) {
      batch_size = cur_batch_size;
660
    } else if (batch_size != cur_batch_size) {
Y
yaoxuefeng 已提交
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
      // CHECK(batch_size == cur_batch_size);  // NOLINT
      batch_size_consist = false;
      break;
    }
  }
  CHECK(batch_size > 0);  // NOLINT

  int show_size =
      shows->lod().size() ? shows->lod()[0].size() - 1 : shows->dims()[0];
  CHECK(show_size == batch_size || show_size == 1);
  int clk_size =
      clks->lod().size() ? clks->lod()[0].size() - 1 : clks->dims()[0];
  CHECK(clk_size == batch_size || clk_size == 1);

  CHECK(outputs->size() == inputs->size());
  std::vector<uint64_t> push_keys;
  push_keys.reserve(MAX_FEASIGN_NUM / 100);
  std::vector<std::vector<float>> push_values;
  push_values.reserve(MAX_FEASIGN_NUM / 100);
  size_t output_len = 0;
  size_t input_idx = 0;

683 684
  VLOG(2) << "fleet.cc::emb_dim: " << fea_dim << " batch_size: " << batch_size
          << " batch_size_consist: " << batch_size_consist;
Y
yaoxuefeng 已提交
685 686 687 688 689 690 691 692

  // TODO(zhaocaibei123): check type of show/clk is int? float? uint64?
  // const long int* show_tensor = shows->data<int64_t>();
  // const long int* clk_tensor = clks->data<int64_t>();

  for (size_t index = 0; index < inputs->size(); ++index) {
    framework::LoDTensor *g_tensor = outputs->at(index);
    float *g = g_tensor->data<float>();
693

Y
yaoxuefeng 已提交
694 695 696 697 698
    if (batch_size_consist) {  // TODO(zhaocaibei123): add config
                               // scale_sparse_gradient_with_batch_size_
      Eigen::Map<
          Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>
          g_mat(g, g_tensor->numel() / fea_dim, fea_dim);
699 700
      g_mat.rightCols(fea_dim - 2) *=
          batch_size;  // hard code here, because of cvm_grad op
Y
yaoxuefeng 已提交
701 702 703 704 705 706 707 708 709
    }

    const framework::LoDTensor *tensor = inputs->at(index);
    const int64_t *ids = tensor->data<int64_t>();
    size_t len = tensor->numel();
    output_len = 0;

    if (tensor->lod().size() > 0) {
      for (size_t i = 0; i < tensor->lod()[0].size() - 1; ++i) {
Z
zhangchunle 已提交
710
        for (size_t j = tensor->lod()[0][i]; j < tensor->lod()[0][i + 1];
Y
yaoxuefeng 已提交
711 712 713 714 715 716
             ++j, output_len += fea_dim) {
          uint64_t real_id = static_cast<uint64_t>(ids[j]);
          if (real_id == padding_id) {
            continue;
          }
          push_keys.emplace_back(real_id);
717
          push_values.emplace_back(fea_dim + 1);
Y
yaoxuefeng 已提交
718 719 720
          // slot show clk grad... consistent with CtrCommonPushValue defined in
          // ctr_accessor.h
          push_values.back()[0] = 2;  // TODO(zhaocaibei123): slot
721 722 723 724
          // push_values.back()[1] =
          //    (i >= show_size ? 1 : static_cast<float>(show_tensor[i]));
          // push_values.back()[2] =
          //    (i >= clk_size ? 0 : static_cast<float>(clk_tensor[i]));
Y
yaoxuefeng 已提交
725

726
          float *data = push_values.back().data() + 1;  // hard code here
Y
yaoxuefeng 已提交
727 728 729 730 731 732 733 734 735 736 737 738 739

          memcpy(data, g + output_len, sizeof(float) * fea_dim);

          ++input_idx;
        }
      }
    } else {
      for (size_t i = 0; i < len; ++i, output_len += fea_dim) {
        uint64_t real_id = static_cast<uint64_t>(ids[i]);
        if (real_id == padding_id) {
          continue;
        }
        push_keys.emplace_back(real_id);
740
        push_values.emplace_back(fea_dim + 1);
Y
yaoxuefeng 已提交
741 742 743
        // slot show clk grad... consistent with CtrCommonPushValue defined in
        // ctr_accessor.h
        push_values.back()[0] = 2;  // TODO(zhaocaibei123): slot
744 745 746 747
        // push_values.back()[1] =
        //    (i >= show_size ? 1 : static_cast<float>(show_tensor[i]));
        // push_values.back()[2] =
        //    (i >= clk_size ? 0 : static_cast<float>(clk_tensor[i]));
Y
yaoxuefeng 已提交
748

749
        float *data = push_values.back().data() + 1;
Y
yaoxuefeng 已提交
750 751 752 753 754 755

        memcpy(data, g + output_len, sizeof(float) * fea_dim);

        ++input_idx;
      }
    }
Z
zhangchunle 已提交
756
    CHECK(static_cast<int64_t>(output_len) == g_tensor->numel());
Y
yaoxuefeng 已提交
757 758 759 760 761 762 763 764 765
  }

  std::vector<float *> push_g_vec(input_idx, nullptr);

  for (auto i = 0u; i < push_keys.size(); ++i) {
    push_g_vec[i] = push_values.at(i).data();
  }

  PADDLE_ENFORCE_EQ(
766 767
      this->Check(table_id),
      true,
Y
yaoxuefeng 已提交
768 769
      platform::errors::InvalidArgument(
          "can not find table: %s, please check your config", table_id));
770 771
  auto status = _worker_ptr->PushSparse(table_id,
                                        push_keys.data(),
Z
zhaocaibei123 已提交
772 773
                                        (const float **)push_g_vec.data(),
                                        push_keys.size());
Y
yaoxuefeng 已提交
774 775
}

T
tangwei12 已提交
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 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
void HalfAsyncCommunicator::MainThread() {
  VLOG(3) << "HalfAsyncCommunicator MainThread start and wait";

  while (waiting_ && running_) {
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    VLOG(3) << "wait for running";
  }

  while (running_) {
    SendByCommunicator();
    BarrierSend();
    RecvByCommunicator();
    BarrierRecv();
    BarrierWeakUp();
  }
  VLOG(1) << "communicator stopped, send thread exit";
}

void AsyncCommunicator::InitImpl(const RpcCtxMap &send_varname_to_ctx,
                                 const RecvCtxMap &recv_varname_to_ctx,
                                 Scope *recv_scope) {
  send_varname_to_ctx_ = std::move(send_varname_to_ctx);
  recv_varname_to_ctx_ = std::move(recv_varname_to_ctx);
  recv_scope_ = std::move(recv_scope);
  send_scope_.reset(new Scope());
  xpu_temp_scope_.reset(new Scope());
  for (auto &iter : send_varname_to_ctx_) {
    auto &ctx = iter.second;
    auto &varnames = ctx.origin_varnames;
    for (auto &var_name : varnames) {
      send_varname_to_queue_[var_name] =
          std::make_shared<BlockingQueue<std::shared_ptr<Variable>>>(
              send_queue_size_);
    }
  }
  send_threadpool_.reset(new ::ThreadPool(thread_pool_size_));
}

AsyncCommunicator::~AsyncCommunicator() {
  running_ = false;
  if (main_thread_) main_thread_->join();
  if (recv_thread_) recv_thread_->join();
}

void AsyncCommunicator::Start() {
  VLOG(1) << "Communicator start";
  if (!communicator_) {
    VLOG(0) << "Communicator is not inited, do nothing";
  } else {
    VLOG(1) << "start send thread and recv thread";
    waiting_ = true;
    running_ = true;
    // flushing_ = false;
    BarrierTriggerReset(max_merge_var_num_);
    // start send and recv thread
    main_thread_.reset(
        new std::thread(std::bind(&AsyncCommunicator::MainThread, this)));
    if (independent_recv_) {
      recv_thread_.reset(
          new std::thread(std::bind(&AsyncCommunicator::RecvThread, this)));
    }
  }
}

void AsyncCommunicator::Stop() {
Z
zhaocaibei123 已提交
841
  VLOG(1) << "Communicator stop begin";
T
tangwei12 已提交
842 843 844 845
  running_ = false;
  if (!communicator_) {
    VLOG(0) << "Communicator is not inited, do nothing";
  } else {
Z
zhaocaibei123 已提交
846
    // _worker_ptr->FinalizeWorker();
Z
zhaocaibei123 已提交
847
    VLOG(1) << "client finalize_worker done";
T
tangwei12 已提交
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
    if (recv_thread_) {
      VLOG(1) << "stop recv thread";
      recv_thread_->join();
      recv_thread_.reset(nullptr);
    }
    if (main_thread_) {
      VLOG(1) << "stop main thread";
      main_thread_->join();
      main_thread_.reset(nullptr);
    }
  }
  VLOG(1) << "Communicator stop done";
}

bool AsyncCommunicator::Check(const std::vector<std::string> &var_tables) {
  PADDLE_ENFORCE_EQ(
864 865
      var_tables.size(),
      1,
T
tangwei12 已提交
866 867 868
      platform::errors::InvalidArgument("var_tables.size() == 1 is permitted"));

  auto table_name = var_tables[0];
869
  if (send_varname_to_ctx_.find(table_name) == send_varname_to_ctx_.end()) {
T
tangwei12 已提交
870
    return false;
871 872 873 874 875
  }
  if (table_name == STEP_COUNTER) {
    VLOG(3) << "send step_counter into queue";
    auto tmp_var = std::make_shared<Variable>();
    auto *tensor = tmp_var->GetMutable<framework::LoDTensor>();
876
    tensor->Resize(phi::make_ddim({1}));
877 878 879 880
    auto *out_d = tensor->mutable_data<int64_t>(platform::CPUPlace());
    out_d[0] = 1;
    send_varname_to_queue_[table_name]->Push(tmp_var);
  }
T
tangwei12 已提交
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
  return true;
}

bool AsyncCommunicator::Check(const int table_id) {
  for (auto &iter : send_varname_to_ctx_) {
    auto &ctx = iter.second;
    if (ctx.table_id == table_id) return true;
  }
  return false;
}

void AsyncCommunicator::Send(const std::vector<std::string> &var_names,
                             const framework::Scope &scope) {
  waiting_ = false;
  for (size_t i = 0; i < var_names.size(); i++) {
    auto *var = scope.FindVar(var_names[i]);
    auto tmp_grad_var = std::make_shared<Variable>();
    framework::CopyVariable(*var, tmp_grad_var.get());
    send_varname_to_queue_[var_names[i]]->Push(tmp_grad_var);
  }
}

void HalfAsyncCommunicator::Clean() {
  for (auto &iter : send_varname_to_queue_) {
    auto &var_name = iter.first;
    auto &var_queue = iter.second;

    while (var_queue->Size() > 0) {
      var_queue->Pop();
    }

    VLOG(3) << "clean var: " << var_name << " done";
  }
}

void HalfAsyncCommunicator::BarrierTriggerDecrement() {
  barrier_trigger_--;
  VLOG(3) << "BarrierTriggerDecrement decrement barrier trigger to "
          << barrier_trigger_.load();
}

void HalfAsyncCommunicator::BarrierTriggerReset(int initial_val) {
  barrier_trigger_.store(initial_val);

  VLOG(3) << "BarrierTriggerReset reset barrier trigger to "
          << barrier_trigger_.load();
}

void HalfAsyncCommunicator::Barrier() {
  barrier_counter_++;

  if (!running_) {
    VLOG(3) << "Communicator is not running, release barrier";
    return;
  }

  {
    std::unique_lock<std::mutex> lk(barrier_mutex_);
    barrier_cond_.wait(lk, [this] { return (barrier_counter_ == 0); });
  }
}

int HalfAsyncCommunicator::BatchesCounter() {
  while (running_) {
    if (barrier_counter_.load() >= barrier_trigger_.load() &&
        barrier_trigger_.load() != 0) {
      break;
    } else {
      std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
  }

  return barrier_counter_.load();
}

void HalfAsyncCommunicator::SendByCommunicator() {
  int batches = BatchesCounter();
  VLOG(1) << "HalfAsyncCommunicator::BatchesCounter = " << batches;
  if (batches <= 0) return;

  std::vector<std::future<void>> tasks;
  tasks.reserve(send_varname_to_ctx_.size());

  for (auto &iter : send_varname_to_ctx_) {
    auto &ctx = iter.second;
    auto send_recv_task = [this, &ctx, batches] {
      auto &varnames = ctx.origin_varnames;
      auto &table_id = ctx.table_id;
      size_t var_nums = varnames.size();

      std::vector<std::vector<std::shared_ptr<Variable>>> vars;
      vars.resize(var_nums);
      for (size_t i = 0; i < var_nums; i++) {
        auto &var_name = varnames[i];
        auto &var_queue = send_varname_to_queue_[var_name];
        for (int j = 0; j < batches; j++) vars[i].push_back(var_queue->Pop());
        MergeVars<float>(var_name, vars[i], send_scope_.get(), 1);
      }

      if (ctx.is_sparse) {
        PADDLE_ENFORCE_EQ(
982 983
            varnames.size(),
            1,
T
tangwei12 已提交
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
            platform::errors::InvalidArgument(
                "sparse variables can only be merged by one variables"));
        RpcSendSparse(varnames[0], table_id, *send_scope_);
      } else {
        RpcSendDense(ctx, *send_scope_);
      }
    };
    tasks.emplace_back(send_threadpool_->enqueue(std::move(send_recv_task)));
  }
  for (auto &task : tasks) {
    task.wait();
  }
  return;
}

void HalfAsyncCommunicator::BarrierWeakUp() {
  barrier_counter_.store(0);
  barrier_cond_.notify_all();
}

void SyncCommunicator::BarrierSend() {
  if (!running_) return;
  BarrierWithTable(0);
  VLOG(4) << "BarrierSend with SyncCommunicator";
}

void SyncCommunicator::BarrierRecv() {
  if (!running_) return;
  BarrierWithTable(1);

  VLOG(4) << "BarrierRecv with SyncCommunicator";
}

1017 1018 1019
void GeoCommunicator::Send(
    const std::vector<std::string> &var_names,
    const framework::Scope &scope) {  // last op in program
1020 1021
  platform::RecordEvent record_event(
      "GeoCommunicator->Send", platform::TracerEventType::Communication, 1);
T
tangwei12 已提交
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
  waiting_ = false;
  auto before_send = GetCurrentUS();
  auto table_name = var_names[0];

  size_t splited_var_nums =
      send_varname_to_ctx_[table_name].splited_varnames.size();

  std::unordered_map<std::string, std::unordered_set<int64_t>> ids_table;

  for (size_t j = 0; j < splited_var_nums; j++) {
    ids_table.insert(std::pair<std::string, std::unordered_set<int64_t>>(
        send_varname_to_ctx_[table_name].splited_varnames[j],
        std::unordered_set<int64_t>()));
  }

  auto *var = scope.FindVar(table_name);

1039 1040
  PADDLE_ENFORCE_EQ(var->IsType<phi::SelectedRows>(),
                    true,
T
tangwei12 已提交
1041 1042
                    platform::errors::InvalidArgument(
                        "Only need to send Sparse Grad in Geo mode."));
1043
  auto &rows = var->Get<phi::SelectedRows>().rows();
T
tangwei12 已提交
1044 1045

  // insert ids which has not been record
1046 1047 1048
  // VLOG(0) << "fl-ps > table_name: " << table_name << " splited_var_nums: " <<
  // splited_var_nums << " rows size: " << rows.size();
  for (size_t j = 0; j < rows.size(); j++) {  // batch_size == rows.size()
T
tangwei12 已提交
1049 1050 1051
    auto ep_idx = rows[j] % splited_var_nums;
    ids_table.at(send_varname_to_ctx_[table_name].splited_varnames[ep_idx])
        .insert(rows[j]);
1052
    // VLOG(0) << " id: " << rows[j] << " ";
T
tangwei12 已提交
1053 1054 1055 1056 1057 1058 1059
  }

  for (auto &iter : ids_table) {
    auto &key = iter.first;
    auto &sparse_ids_set = iter.second;
    auto sparse_ids_vec = std::make_shared<std::vector<int64_t>>();
    sparse_ids_vec->assign(sparse_ids_set.begin(), sparse_ids_set.end());
Z
zhaocaibei123 已提交
1060
    sparse_id_queues_.at(key)->Put(sparse_ids_vec);
T
tangwei12 已提交
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
    VLOG(3) << "push " << sparse_ids_vec->size() << " ids to " << key
            << "'s queue";
  }

  auto after_send = GetCurrentUS();
  VLOG(2) << "run send op finish. use time " << (after_send - before_send);
}

void GeoCommunicator::InitImpl(const RpcCtxMap &send_varname_to_ctx,
                               const RecvCtxMap &recv_varname_to_ctx,
                               Scope *recv_scope) {
  send_varname_to_ctx_ = std::move(send_varname_to_ctx);
1073 1074
  recv_varname_to_ctx_ = std::move(
      recv_varname_to_ctx);  // dense_map - key: table_id, value: params
T
tangwei12 已提交
1075 1076
  recv_scope_ = std::move(recv_scope);

1077 1078 1079
  for (auto it = send_varname_to_ctx_.begin();
       it != send_varname_to_ctx_.end();) {
    auto &ctx = it->second;
Z
zhaocaibei123 已提交
1080 1081
    if (!ctx.is_sparse) {
      parallel_task_nums_ += 1;
1082
      it++;
Z
zhaocaibei123 已提交
1083 1084
      continue;
    }
T
tangwei12 已提交
1085
    auto &varnames = ctx.origin_varnames;
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
    if (varnames.empty()) {
      VLOG(0) << "ERROR! sparse variables num can not be zero";
    }
    auto &varname = varnames[0];  // embedding_0.w_0@GRAD
    auto &ids = ctx.remote_sparse_ids;
    if (!ids.empty()) {
      it = send_varname_to_ctx_.erase(it);
      continue;
    } else {
      it++;
    }
    for (auto &splited_var : ctx.splited_varnames) {  // embedding_0.w_0.block0
T
tangwei12 已提交
1098 1099
      parallel_task_nums_ += 1;
      sparse_id_queues_.insert(
1100 1101 1102
          std::pair<std::string,
                    paddle::framework::Channel<
                        std::shared_ptr<std::vector<int64_t>>>>(
T
tangwei12 已提交
1103
              splited_var,
Z
zhaocaibei123 已提交
1104 1105
              paddle::framework::MakeChannel<
                  std::shared_ptr<std::vector<int64_t>>>(send_queue_size_)));
T
tangwei12 已提交
1106 1107
    }
  }
1108 1109 1110 1111 1112
  send_threadpool_ = std::make_unique<ThreadPool>(thread_pool_size_);
  delta_scope_ = std::make_shared<Scope>();
  old_scope_ = std::make_shared<Scope>();
  pserver_scope_ = std::make_shared<Scope>();
  return;
T
tangwei12 已提交
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
}

void GeoCommunicator::InitParams(const RecvCtxMap &recv_varname_to_ctx) {
  std::vector<std::future<void>> tasks;
  tasks.reserve(recv_varname_to_ctx_.size());

  for (auto &iter : recv_varname_to_ctx_) {
    auto &table_id = iter.first;
    auto &varnames = iter.second;
    auto recv_task = [this, &table_id, &varnames] {
      InitDense(varnames, table_id);
    };
1125 1126 1127
    if (send_threadpool_ == nullptr) {
      VLOG(0) << "ERROR! send_threadpool_ is nullptr";
    }
T
tangwei12 已提交
1128 1129 1130 1131 1132 1133 1134 1135 1136
    tasks.emplace_back(send_threadpool_->enqueue(std::move(recv_task)));
  }

  for (auto &task : tasks) {
    task.wait();
  }

  for (auto &iter : send_varname_to_ctx_) {
    auto &ctx = iter.second;
1137 1138 1139
    if (!ctx.is_sparse) {
      continue;
    }
T
tangwei12 已提交
1140 1141 1142
    auto &varname = ctx.origin_varnames[0];
    auto &table_id = ctx.table_id;
    auto param = varname.substr(0, varname.size() - 5);
1143
    VLOG(0) << "InitSparse: " << param << ", " << table_id;
T
tangwei12 已提交
1144 1145 1146 1147 1148 1149 1150
    InitSparse(param, table_id);
  }
  return;
}

void GeoCommunicator::InitDense(std::vector<std::string> &varnames,
                                int table_id) {
1151
  VLOG(1) << "init dense table " << table_id << " begin";
T
tangwei12 已提交
1152 1153 1154
  if (trainer_id_ == 0) {
    RpcSendDenseParam(varnames, table_id, *recv_scope_);
    BarrierWithTable(1);
T
tangwei12 已提交
1155
    VLOG(1) << "push dense param to table " << table_id
T
tangwei12 已提交
1156 1157 1158 1159
            << " from 0' trainer done";
  } else {
    BarrierWithTable(1);
    RpcRecvDense(varnames, table_id, recv_scope_);
1160
    VLOG(1) << "pull dense param from table " << table_id
T
tangwei12 已提交
1161 1162 1163 1164 1165 1166 1167 1168 1169
            << " from 0' trainer done";
  }

  // copy to old_scope
  for (auto &t : varnames) {
    auto *global_var = recv_scope_->FindVar(t);
    global_var->GetMutable<framework::LoDTensor>();
    auto *old_var = old_scope_->Var(t);
    old_var->GetMutable<framework::LoDTensor>();
1170
    framework::CopyVariable(*global_var, old_var);  // src, dst
Z
zhaocaibei123 已提交
1171 1172 1173 1174
    // init pserver_scope_
    auto *pserver_var = pserver_scope_->Var(t);
    pserver_var->GetMutable<framework::LoDTensor>();
    framework::CopyVariable(*global_var, pserver_var);
T
tangwei12 已提交
1175 1176 1177 1178 1179
  }
  VLOG(1) << "init dense table " << table_id << " done";
}

void GeoCommunicator::SendDense(const CommContext &send_ctx) {
1180 1181 1182
  platform::RecordEvent record_event("GeoCommunicator->SendDense",
                                     platform::TracerEventType::Communication,
                                     1);
T
tangwei12 已提交
1183 1184 1185 1186 1187 1188 1189
  auto &var_names = send_ctx.origin_varnames;
  auto &table_id = send_ctx.table_id;
  for (auto &varname : var_names) {
    auto param_name = GradToParam(varname);
    auto *var_latest = recv_scope_->FindVar(param_name);
    auto *var_timestamp = old_scope_->FindVar(param_name);

1190 1191
    PADDLE_ENFORCE_EQ(var_latest->IsInitialized(),
                      true,
T
tangwei12 已提交
1192 1193
                      platform::errors::Unavailable(
                          "%s is not initialized, please check", param_name));
1194 1195
    PADDLE_ENFORCE_EQ(var_timestamp->IsInitialized(),
                      true,
T
tangwei12 已提交
1196 1197 1198 1199 1200 1201
                      platform::errors::Unavailable(
                          "%s is not initialized, please check", param_name));

    auto &t_latest = var_latest->Get<framework::LoDTensor>();
    auto t_timestamp = var_timestamp->GetMutable<framework::LoDTensor>();

L
Leo Chen 已提交
1202
    phi::CPUContext cpu_ctx;
T
tangwei12 已提交
1203 1204 1205 1206
    auto *var_delta = delta_scope_->Var(varname);
    auto *t_delta = var_delta->GetMutable<framework::LoDTensor>();
    t_delta->mutable_data<float>(t_latest.dims(), cpu_ctx.GetPlace());

L
Leo Chen 已提交
1207
    auto blas = phi::funcs::GetBlas<phi::CPUContext, float>(cpu_ctx);
1208 1209 1210 1211
    blas.VSUB(t_latest.numel(),
              t_latest.data<float>(),
              t_timestamp->data<float>(),
              t_delta->data<float>());
T
tangwei12 已提交
1212 1213 1214 1215

    float coefficient = 1.0 / static_cast<float>(trainers_);
    blas.SCAL(t_latest.numel(), coefficient, t_delta->data<float>());

1216 1217 1218 1219
    blas.VADD(t_latest.numel(),
              t_timestamp->data<float>(),
              t_delta->data<float>(),
              t_timestamp->data<float>());
T
tangwei12 已提交
1220 1221 1222 1223 1224 1225 1226
  }
  RpcSendDense(send_ctx, *delta_scope_);
  VLOG(1) << "Finish Send Dense " << var_names[0] << ", table_id: " << table_id;
  return;
}

void GeoCommunicator::RecvDense(const CommContext &send_ctx) {
1227 1228 1229
  platform::RecordEvent record_event("GeoCommunicator->RecvDense",
                                     platform::TracerEventType::Communication,
                                     1);
T
tangwei12 已提交
1230 1231 1232 1233 1234
  auto &table_id = send_ctx.table_id;
  auto &varnames = recv_varname_to_ctx_.at(table_id);
  // 1. recv from pserver
  RpcRecvDense(varnames, table_id, pserver_scope_.get());

1235 1236
  // 2.1 pserver - old => delta; 2.2 latest + delta => latest 2.3 old =>
  // pserver
L
Leo Chen 已提交
1237
  phi::CPUContext cpu_ctx;
T
tangwei12 已提交
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
  for (auto &varname : varnames) {
    auto *var_latest = recv_scope_->FindVar(varname);
    auto t_latest = var_latest->GetMutable<framework::LoDTensor>();

    auto *var_old = old_scope_->FindVar(varname);
    auto t_old = var_old->GetMutable<framework::LoDTensor>();

    auto *var_pserver = pserver_scope_->FindVar(varname);
    auto t_pserver = var_pserver->Get<framework::LoDTensor>();

    auto *var_delta = delta_scope_->Var(varname);
    auto *t_delta = var_delta->GetMutable<framework::LoDTensor>();
    t_delta->mutable_data<float>(t_latest->dims(), cpu_ctx.GetPlace());

L
Leo Chen 已提交
1252
    auto blas = phi::funcs::GetBlas<phi::CPUContext, float>(cpu_ctx);
1253 1254 1255
    blas.VSUB(t_latest->numel(),
              t_pserver.data<float>(),
              t_old->data<float>(),
T
tangwei12 已提交
1256
              t_delta->data<float>());
1257 1258 1259 1260 1261 1262
    blas.VADD(t_latest->numel(),
              t_latest->data<float>(),
              t_delta->data<float>(),
              t_latest->data<float>());
    blas.VCOPY(
        t_latest->numel(), t_pserver.data<float>(), t_old->data<float>());
T
tangwei12 已提交
1263 1264 1265 1266 1267 1268
  }
  VLOG(1) << "Finish Recv Dense " << varnames[0] << ", table_id: " << table_id;
  return;
}

void GeoCommunicator::InitSparse(const std::string &var_name, int table_id) {
T
tangwei12 已提交
1269
  VLOG(1) << "Init Sparse " << var_name << " : table " << table_id << " begin.";
T
tangwei12 已提交
1270 1271 1272
  if (trainer_id_ == 0) {
    RpcSendSparseParam(var_name, table_id, *recv_scope_);
    BarrierWithTable(1);
T
tangwei12 已提交
1273
    VLOG(1) << "push sparse param to table " << table_id
T
tangwei12 已提交
1274 1275 1276 1277
            << " from 0' trainer done";
  } else {
    BarrierWithTable(1);
    RpcRecvSparse(var_name, table_id, recv_scope_);
T
tangwei12 已提交
1278
    VLOG(1) << "pull sparse param to table " << table_id
T
tangwei12 已提交
1279 1280 1281
            << " from 0' trainer done";
  }

T
tangwei12 已提交
1282
  VLOG(1) << "Init Sparse " << var_name << " : table " << table_id << " done.";
T
tangwei12 已提交
1283 1284
  auto *global_var = recv_scope_->FindVar(var_name);
  auto *var = old_scope_->Var(var_name);
1285
  framework::CopyVariable(*global_var, var);  // src, dst
T
tangwei12 已提交
1286 1287 1288 1289 1290
  return;
}

std::vector<int64_t> GeoCommunicator::MergeSparseIds(
    const std::string &send_varname) {
1291 1292 1293
  platform::RecordEvent record_event("GeoCommunicator->MergeSparseIds",
                                     platform::TracerEventType::Communication,
                                     1);
T
tangwei12 已提交
1294 1295
  size_t merge_num = 0, wait_times = 0;
  std::unordered_set<int64_t> sparse_ids;
1296 1297
  while (merge_num <
         static_cast<size_t>(max_merge_var_num_)) {  // -> geo_step: 100
T
tangwei12 已提交
1298 1299 1300
    VLOG(3) << "Merge Number of " << send_varname << " = " << merge_num;
    if (sparse_id_queues_.at(send_varname)->Size() > 0) {
      wait_times = 0;
Z
zhaocaibei123 已提交
1301 1302
      std::shared_ptr<std::vector<int64_t>> pop_ids = nullptr;
      sparse_id_queues_.at(send_varname)->Get(pop_ids);
T
tangwei12 已提交
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
      for (size_t j = 0; j < pop_ids->size(); j++) {
        sparse_ids.insert(pop_ids->at(j));
      }
      merge_num += 1;
      VLOG(3) << "sparse_id_queues_(" << send_varname << ") pushed";
    } else if (sparse_id_queues_.at(send_varname)->Size() == 0) {
      VLOG(3) << "wait_times -> " << wait_times;
      if (wait_times >= static_cast<size_t>(send_wait_times_)) {
        break;
      }
      std::this_thread::sleep_for(std::chrono::milliseconds(10));
      wait_times++;
      continue;
    }
  }
  std::vector<int64_t> res;
  res.assign(sparse_ids.begin(), sparse_ids.end());
  return res;
}

void GeoCommunicator::SendSparse(const std::string &varname,
1324 1325
                                 std::vector<int64_t> &sparse_ids,
                                 int table_id,
T
tangwei12 已提交
1326
                                 int ep_idx) {
1327 1328 1329
  platform::RecordEvent record_event("GeoCommunicator->SendSparse",
                                     platform::TracerEventType::Communication,
                                     1);
Z
zhaocaibei123 已提交
1330 1331 1332
  if (sparse_ids.size() == 0) {
    return;
  }
T
tangwei12 已提交
1333 1334 1335 1336 1337 1338 1339 1340
  std::string param_name = SplitedGradToParam(varname);
  VLOG(1) << "In GeoCommunicator::SendSparse(" << varname << " " << param_name
          << ", ids.size = " << sparse_ids.size() << ", table_id: " << table_id
          << ", ep_idx: " << ep_idx;

  auto *var_latest = recv_scope_->FindVar(param_name);
  auto *var_old = old_scope_->FindVar(param_name);

1341 1342
  PADDLE_ENFORCE_EQ(var_latest->IsInitialized(),
                    true,
T
tangwei12 已提交
1343 1344
                    platform::errors::Unavailable(
                        "%s is not initialized, please check", param_name));
1345 1346
  PADDLE_ENFORCE_EQ(var_old->IsInitialized(),
                    true,
T
tangwei12 已提交
1347 1348 1349 1350 1351 1352 1353
                    platform::errors::Unavailable(
                        "%s is not initialized, please check", param_name));

  auto &t_latest = var_latest->Get<framework::LoDTensor>();
  auto *t_old = var_old->GetMutable<framework::LoDTensor>();

  auto dims1 = t_latest.dims()[1];
L
Leo Chen 已提交
1354
  phi::CPUContext cpu_ctx;
T
tangwei12 已提交
1355 1356

  auto *var_delta = delta_scope_->Var(varname);
1357
  auto *t_delta = var_delta->GetMutable<phi::SelectedRows>();
T
tangwei12 已提交
1358 1359 1360 1361 1362 1363 1364
  auto *var_t_value = t_delta->mutable_value();
  var_t_value->Resize({static_cast<int64_t>(sparse_ids.size()), dims1});
  auto *t_value = var_t_value->mutable_data<float>(cpu_ctx.GetPlace());

  t_delta->set_rows(sparse_ids);
  t_delta->set_height(t_latest.dims()[0]);

L
Leo Chen 已提交
1365
  auto blas = phi::funcs::GetBlas<phi::CPUContext, float>(cpu_ctx);
T
tangwei12 已提交
1366 1367 1368 1369
  float coefficient = 1.0 / static_cast<float>(trainers_);

  std::vector<float *> push_g_vec;
  for (auto j = 0; j < static_cast<int>(sparse_ids.size()); ++j) {
1370 1371
    blas.VSUB(dims1,
              t_latest.data<float>() + sparse_ids[j] * dims1,
T
tangwei12 已提交
1372 1373 1374
              t_old->data<float>() + sparse_ids[j] * dims1,
              t_value + j * dims1);
    blas.SCAL(dims1, coefficient, t_value + j * dims1);
1375 1376
    blas.VADD(dims1,
              t_old->data<float>() + sparse_ids[j] * dims1,
T
tangwei12 已提交
1377 1378 1379
              t_value + j * dims1,
              t_old->data<float>() + sparse_ids[j] * dims1);
    push_g_vec.push_back(t_value + j * dims1);
Z
zhaocaibei123 已提交
1380 1381 1382 1383

    VLOG(5) << "DEBUG GeoCommunicator::SendSparse send sparse key "
            << sparse_ids[j] << " value[0] " << push_g_vec[j][0]
            << " value[-1] " << push_g_vec[j][dims1 - 1];
T
tangwei12 已提交
1384 1385 1386 1387 1388
  }

  ++_async_call_num;
  DownpourBrpcClosure *closure = new DownpourBrpcClosure(1, [this](void *done) {
    int ret = 0;
1389
    auto *closure = (DownpourBrpcClosure *)done;  // NOLINT
T
tangwei12 已提交
1390 1391 1392 1393 1394 1395
    if (closure->check_response(0, PS_PUSH_SPARSE_TABLE) != 0) {
      ret = -1;
    }
    closure->set_promise_value(ret);
    --_async_call_num;
  });
Z
zhaocaibei123 已提交
1396
  auto status = _worker_ptr->PushSparseRawGradientPartial(
1397 1398 1399 1400 1401 1402
      table_id,
      (const uint64_t *)sparse_ids.data(),
      (const float **)push_g_vec.data(),
      sparse_ids.size(),
      closure,
      ep_idx);
T
tangwei12 已提交
1403 1404 1405 1406 1407 1408 1409
  status.wait();

  VLOG(1) << "Finish Send Sparse " << varname
          << ", ids.size = " << sparse_ids.size() << ", table_id: " << table_id;
  return;
}

1410 1411
void GeoCommunicator::RecvSparse(const std::string &varname,
                                 int table_id,
T
tangwei12 已提交
1412
                                 int ep_idx) {
1413 1414 1415
  platform::RecordEvent record_event("GeoCommunicator->RecvSparse",
                                     platform::TracerEventType::Communication,
                                     1);
T
tangwei12 已提交
1416 1417 1418
  // 1. recv from pserver
  std::vector<uint64_t> keys;
  std::vector<float> values;
Z
zhaocaibei123 已提交
1419
  auto status = _worker_ptr->PullGeoParam(table_id, &values, &keys, ep_idx);
T
tangwei12 已提交
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
  status.wait();

  std::string param = SplitedGradToParam(varname);
  VLOG(1) << "RecvSparse receive var: " << varname << " " << param << ", "
          << table_id << "; ids Size: " << keys.size()
          << "; values size: " << values.size();

  auto *var_latest = recv_scope_->FindVar(param);
  auto *var_old = old_scope_->FindVar(param);

  auto *t_latest = var_latest->GetMutable<framework::LoDTensor>();
  auto *t_old = var_old->GetMutable<framework::LoDTensor>();

  auto dims1 = t_latest->dims()[1];
  auto numel = keys.size() * dims1;

  std::vector<float> v_delta;
  v_delta.resize(numel);

L
Leo Chen 已提交
1439 1440
  phi::CPUContext cpu_ctx;
  auto blas = phi::funcs::GetBlas<phi::CPUContext, float>(cpu_ctx);
T
tangwei12 已提交
1441 1442

  for (auto j = 0; j < static_cast<int>(keys.size()); ++j) {
Z
zhaocaibei123 已提交
1443 1444 1445
    VLOG(5) << "DEBUG GeoCommunicator::RecvSparse recv sparse key" << keys[j]
            << "value[0] " << values[j * dims1] << " value[-1] "
            << values[j * dims1 + dims1 - 1];
T
tangwei12 已提交
1446 1447 1448
    float *latest_data = t_latest->data<float>() + keys[j] * dims1;
    float *old_data = t_old->data<float>() + keys[j] * dims1;
    // pserver - old => delta
1449 1450
    blas.VSUB(
        dims1, values.data() + j * dims1, old_data, v_delta.data() + j * dims1);
T
tangwei12 已提交
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
    // latest + delta => latest
    blas.VADD(dims1, latest_data, v_delta.data() + j * dims1, latest_data);
    // pserver => old
    blas.VCOPY(dims1, values.data() + j * dims1, old_data);
  }
  VLOG(1) << "Finish Recv Sparse " << param << ", table_id: " << table_id;
}

void GeoCommunicator::MainThread() {
  VLOG(3) << "MainThread start and wait";

  while (waiting_ && running_) {
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    VLOG(3) << "wait for running";
  }

  while (running_) {
    std::vector<std::future<void>> tasks;
    tasks.reserve(parallel_task_nums_);

    for (auto &iter : send_varname_to_ctx_) {
      auto &ctx = iter.second;
      auto &varnames = ctx.origin_varnames;
      auto &table_id = ctx.table_id;

      if (ctx.is_sparse) {
        PADDLE_ENFORCE_EQ(
1478 1479
            varnames.size(),
            1,
T
tangwei12 已提交
1480 1481 1482 1483 1484 1485
            platform::errors::InvalidArgument(
                "sparse variables can only be merged by one variables"));
        int pserver_num = static_cast<int>(ctx.epmap.size());
        for (int ep_idx = 0; ep_idx < pserver_num; ep_idx++) {
          // varname: emb@GRAD, param_name: emb, splited_varname: emb.delta0
          auto send_recv_task = [this, table_id, ep_idx, &ctx] {
1486 1487 1488
            auto splited_varname =
                ctx.splited_varnames[ep_idx];  // embedding_0.w_0.block0
                                               // embedding_1.w_0.block0
T
tangwei12 已提交
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
            auto sparse_ids = MergeSparseIds(splited_varname);
            SendSparse(splited_varname, sparse_ids, table_id, ep_idx);
            RecvSparse(splited_varname, table_id, ep_idx);
          };
          tasks.emplace_back(
              send_threadpool_->enqueue(std::move(send_recv_task)));
        }
      } else {
        auto send_recv_task = [this, &ctx] {
          SendDense(ctx);
          RecvDense(ctx);
        };
        tasks.emplace_back(
            send_threadpool_->enqueue(std::move(send_recv_task)));
      }
    }
    for (auto &task : tasks) {
      task.wait();
    }
  }
}

1511 1512 1513 1514 1515 1516 1517
void FLCommunicator::InitBrpcClient(
    const std::string &dist_desc,
    const std::vector<std::string> &host_sign_list) {
  auto fleet = paddle::distributed::FleetWrapper::GetInstance();
  if (_worker_ptr.get() == nullptr) {
    VLOG(0) << "fl-ps > FLCommunicator::InitBrpcClient get _worker_ptr";
    _worker_ptr =
1518 1519
        fleet->worker_ptr_;  // FleetWrapper::InitWorker must be excuted
                             // before, but no need for Coordinator
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
  }
  if (coordinator_client_ptr_ == nullptr) {
    coordinator_client_ptr_.reset(new CoordinatorClient);
  }
  int16_t servers = host_sign_list.size();
  coordinator_client_ptr_->_env = &ps_env_;
  coordinator_client_ptr_->_env->SetPsServers(&host_sign_list, servers);
}

void FLCommunicator::StartCoordinatorClient(
    const std::vector<std::string> &trainer_endpoints) {
  if (coordinator_client_ptr_ == nullptr) {
    LOG(ERROR) << "coordinator_client_ptr_ is null";
    return;
  }
  coordinator_client_ptr_->Initialize(trainer_endpoints);
  VLOG(0) << "fl-ps > StartCoordinatorClient finish!";
}

void FLCommunicator::StartCoordinatorServer() {
  if (coordinator_client_ptr_ == nullptr) {
    LOG(ERROR) << "coordinator_client_ptr_ is null";
  }
  int ret = coordinator_client_ptr_->StartClientService();
  if (ret != 0) {
    LOG(ERROR) << "coordinator_client_ptr_ StartClientService failed";
  }
  VLOG(0) << "fl-ps > StartCoordinatorServer finished!";
  return;
}

std::unordered_map<uint32_t, std::string> FLCommunicator::QueryFLClientsInfo() {
  return coordinator_client_ptr_->QueryFLClientsInfo();
}

void FLCommunicator::SaveFLStrategy(
    const std::unordered_map<uint32_t, std::string> &fl_strategy) {
  coordinator_client_ptr_->SaveFLStrategy(fl_strategy);
  return;
}

void FLCommunicator::SendThreadAsync() {
  while (is_running_) {
    RpcSendFLStrategy();
  }
  return;
}

void FLCommunicator::RpcSendFLStrategy() {
  std::set<uint32_t> clients = coordinator_client_ptr_->GetFLClientIds();
  coordinator_client_ptr_->WaitForFLStrategyReady();
  for (auto client_id : clients) {
    coordinator_client_ptr_->SendFLStrategy(client_id);
  }
  coordinator_client_ptr_->ResetFLStrategyFlag();
  VLOG(0) << "fl-ps > RpcSendFLStrategy finished!";
  return;
}

void FLCommunicator::StartCoordinator(
    const std::string &self_endpoint,
    const std::vector<std::string> &trainer_endpoints) {
  coordinator_client_ptr_->SetEndpoint(self_endpoint);
  StartCoordinatorClient(trainer_endpoints);
  StartCoordinatorServer();
  async_send_thread_.reset(
      new std::thread(&FLCommunicator::SendThreadAsync, this));
}

T
tangwei12 已提交
1589 1590
}  // namespace distributed
}  // namespace paddle