communicator.cc 46.7 KB
Newer Older
Q
Qiao Longfei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* 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. */

#include "paddle/fluid/operators/distributed/communicator.h"
Q
Qiao Longfei 已提交
16
#include <gflags/gflags.h>
17
#include <paddle/fluid/framework/program_desc.h>
Q
Qiao Longfei 已提交
18
#include <chrono>  // NOLINT
19
#include <map>
Q
Qiao Longfei 已提交
20
#include <thread>  // NOLINT
21
#include <unordered_set>
Q
Qiao Longfei 已提交
22
#include "paddle/fluid/framework/eigen.h"
Q
Qiao Longfei 已提交
23 24
#include "paddle/fluid/framework/selected_rows.h"
#include "paddle/fluid/framework/tensor_util.h"
25
#include "paddle/fluid/framework/threadpool.h"
Q
Qiao Longfei 已提交
26
#include "paddle/fluid/framework/variable_helper.h"
C
Chengmo 已提交
27
#include "paddle/fluid/operators/distributed/distributed.h"
Q
Qiao Longfei 已提交
28 29
#include "paddle/fluid/operators/distributed/parameter_recv.h"
#include "paddle/fluid/operators/distributed/parameter_send.h"
T
tangwei12 已提交
30
#include "paddle/fluid/string/printf.h"
31
#include "paddle/fluid/string/split.h"
Q
Qiao Longfei 已提交
32

Q
Qiao Longfei 已提交
33 34 35 36
namespace paddle {
namespace operators {
namespace distributed {

37 38 39 40
using Tree =
    std::map<std::string, std::map<std::string, std::vector<std::string>>>;
using RpcCtxMap = operators::distributed::RpcCtxMap;

Q
Qiao Longfei 已提交
41 42 43 44 45 46
inline double GetCurrentUS() {
  struct timeval time;
  gettimeofday(&time, NULL);
  return 1e+6 * time.tv_sec + time.tv_usec;
}

47 48 49 50 51 52 53
template <typename T>
inline void VSUB(int n, const T *x, const T *y, T *z) {
  for (int i = 0; i < n; ++i) {
    z[i] = x[i] - y[i];
  }
}

54
Communicator::Communicator() {}
1
123malin 已提交
55

56 57 58
Communicator::Communicator(const std::map<std::string, std::string> &envs_) {
  for (auto &iter : envs_) {
    envs[iter.first] = iter.second;
1
123malin 已提交
59 60 61
  }
}

T
tangwei12 已提交
62
std::once_flag Communicator::init_flag_;
63
std::shared_ptr<Communicator> Communicator::communicator_(nullptr);
Q
can run  
Qiao Longfei 已提交
64

T
tangwei12 已提交
65 66 67 68 69 70 71
void AsyncCommunicator::InitImpl(const RpcCtxMap &send_varname_to_ctx,
                                 const RpcCtxMap &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);

72 73 74 75 76 77 78
  if (send_varname_to_ctx.size() == 0) {
    VLOG(0) << "nothing need to be send, will not start send_thread";
  } else {
    send_scope_.reset(new Scope());
    for (auto &iter : send_varname_to_ctx_) {
      send_varname_to_queue_[iter.first] =
          std::make_shared<BlockingQueue<std::shared_ptr<Variable>>>(
79
              send_queue_size_);
80
    }
81
    send_threadpool_.reset(new ::ThreadPool(thread_pool_size_));
82 83 84 85 86
  }

  if (recv_varname_to_ctx.size() == 0) {
    VLOG(0) << "nothing need to be received, will not start recv_thread";
  } else {
87
    recv_threadpool_.reset(new ::ThreadPool(thread_pool_size_));
Q
Qiao Longfei 已提交
88 89 90
  }
}

T
tangwei12 已提交
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
void AsyncCommunicator::InitImpl(const paddle::framework::ProgramDesc &program,
                                 Scope *param_scope) {
  RpcCtxMap send_varname_to_ctx;
  RpcCtxMap recv_varname_to_ctx;
  for (auto *op : program.Block(0).AllOps()) {
    VLOG(3) << "node name " << op->Type();
    if (op->Type() == "send") {
      auto send_var_name = op->Input("X")[0];
      auto send_varnames = boost::get<std::vector<std::string>>(
          op->GetNullableAttr("send_varnames"));
      auto epmap =
          boost::get<std::vector<std::string>>(op->GetNullableAttr("epmap"));
      auto height_section =
          boost::get<std::vector<int64_t>>(op->GetNullableAttr("sections"));
      auto trainer_id = boost::get<int>(op->GetNullableAttr("trainer_id"));
1
123malin 已提交
106 107
      auto merge_add = boost::get<bool>(op->GetNullableAttr("merge_add"));
      if (!merge_add) {
108
        merge_add = is_sgd_optimizer_;
1
123malin 已提交
109 110 111
      }
      auto use_send_handler =
          boost::get<bool>(op->GetNullableAttr("use_send_handler"));
T
tangwei12 已提交
112
      send_varname_to_ctx[send_var_name] = operators::distributed::RpcContext(
1
123malin 已提交
113 114
          send_var_name, send_varnames, epmap, height_section, trainer_id,
          merge_add, use_send_handler);
T
tangwei12 已提交
115 116 117 118
      VLOG(3) << "find and init an send op: "
              << send_varname_to_ctx[send_var_name];
    } else if (op->Type() == "recv") {
      auto do_not_run = boost::get<int>(op->GetNullableAttr("do_not_run"));
119 120 121
      PADDLE_ENFORCE_GT(do_not_run, 0,
                        platform::errors::InvalidArgument(
                            "recv op's attr `do_not_run` must be True!"));
T
tangwei12 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
      auto recv_var_name = op->Output("Out")[0];
      auto recv_varnames = boost::get<std::vector<std::string>>(
          op->GetNullableAttr("recv_varnames"));
      auto epmap =
          boost::get<std::vector<std::string>>(op->GetNullableAttr("epmap"));
      auto trainer_id = boost::get<int>(op->GetNullableAttr("trainer_id"));
      recv_varname_to_ctx[recv_var_name] = operators::distributed::RpcContext(
          recv_var_name, recv_varnames, epmap, {}, trainer_id);
    }
  }

  // init communicator here
  if (send_varname_to_ctx.size() == 0 && recv_varname_to_ctx.size() == 0) {
    LOG(WARNING) << "no var need to send and recv!!";
  }

  operators::distributed::AsyncCommunicator::InitImpl(
      send_varname_to_ctx, recv_varname_to_ctx, param_scope);
}

AsyncCommunicator::~AsyncCommunicator() {
Q
Qiao Longfei 已提交
143 144 145 146 147
  running_ = false;
  if (send_thread_) send_thread_->join();
  if (recv_thread_) recv_thread_->join();
}

T
tangwei12 已提交
148
void AsyncCommunicator::SendThread() {
Q
Qiao Longfei 已提交
149
  VLOG(3) << "SendThread start!";
Q
Qiao Longfei 已提交
150 151 152
  while (running_) {
    std::vector<std::future<void>> task_futures;
    task_futures.reserve(send_varname_to_ctx_.size());
153
    VLOG(4) << "run send graph";
Q
Qiao Longfei 已提交
154
    auto before_run_send_graph = GetCurrentUS();
Q
Qiao Longfei 已提交
155
    for (auto &iter : send_varname_to_queue_) {
Q
Qiao Longfei 已提交
156 157
      auto &var_name = iter.first;
      auto &var_queue = iter.second;
Q
Qiao Longfei 已提交
158
      if (var_queue->Size() > 0) {
Q
Qiao Longfei 已提交
159
        auto send_task = [this, &var_name, &var_queue] {
160
          VLOG(4) << var_name << " merge and send";
Q
Qiao Longfei 已提交
161
          std::vector<std::shared_ptr<Variable>> vars;
162 163
          int merged_var_num = 0;
          int wait_times = 0;
164
          while (merged_var_num < max_merge_var_num_) {
Q
Qiao Longfei 已提交
165
            if (var_queue->Size() == 0) {
166
              VLOG(4) << "wait_times -> " << wait_times;
167
              if (wait_times >= send_wait_times_) {
Q
Qiao Longfei 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180 181
                break;
              }
              std::this_thread::sleep_for(std::chrono::milliseconds(10));
              wait_times++;
              continue;
            } else {
              wait_times = 0;

              vars.push_back(var_queue->Pop());
              // only count the send number of the first var
              if (var_name == send_varname_to_queue_.begin()->first) {
                grad_num_.fetch_add(1, std::memory_order_relaxed);
              }
              merged_var_num++;
182
            }
Q
Qiao Longfei 已提交
183
          }
Q
Qiao Longfei 已提交
184
          auto before_merge = GetCurrentUS();
1
123malin 已提交
185 186 187 188 189 190 191
          auto &ctx = send_varname_to_ctx_.at(var_name);
          if (ctx.use_send_handler) {
            MergeVars<float>(var_name, vars, send_scope_.get(), ctx.merge_add);
          } else {
            MergeVars<int64_t>(var_name, vars, send_scope_.get(),
                               ctx.merge_add);
          }
Q
Qiao Longfei 已提交
192
          auto after_merge = GetCurrentUS();
193
          VLOG(4) << "merge " << merged_var_num << " " << var_name
Q
Qiao Longfei 已提交
194
                  << " use time " << after_merge - before_merge;
Q
Qiao Longfei 已提交
195
          auto send_functor = distributed::ParameterSend<float>();
196
          send_functor(ctx, *send_scope_, true, 1);
Q
Qiao Longfei 已提交
197
          auto after_send = GetCurrentUS();
198
          VLOG(4) << "send " << var_name << " use time "
Q
Qiao Longfei 已提交
199
                  << after_send - after_merge;
Q
Qiao Longfei 已提交
200 201 202
        };
        task_futures.emplace_back(
            send_threadpool_->enqueue(std::move(send_task)));
Q
Qiao Longfei 已提交
203
      } else {
204
        VLOG(4) << var_name << " queue empty";
Q
Qiao Longfei 已提交
205
      }
Q
Qiao Longfei 已提交
206 207 208
    }
    for (auto &task_f : task_futures) {
      task_f.wait();
Q
Qiao Longfei 已提交
209
    }
Q
Qiao Longfei 已提交
210
    auto after_run_send_graph = GetCurrentUS();
211

212
    VLOG(4) << "run send graph use time "
213
            << after_run_send_graph - before_run_send_graph;
T
tangwei12 已提交
214
    Recv();
Q
Qiao Longfei 已提交
215
  }
216
  VLOG(0) << "communicator stopped, send thread exit";
Q
Qiao Longfei 已提交
217 218
}

T
tangwei12 已提交
219
void AsyncCommunicator::RecvThread() {
Q
Qiao Longfei 已提交
220
  VLOG(3) << "RecvThread start!";
Q
Qiao Longfei 已提交
221
  while (running_) {
222
    int grad_num = grad_num_.load();
223
    if (grad_num > min_send_grad_num_before_recv_) {
224 225 226 227 228
      RecvAll();
      grad_num_.store(0);
    } else {
      std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
Q
Qiao Longfei 已提交
229
  }
230
  VLOG(0) << "communicator stopped, recv thread exit";
Q
Qiao Longfei 已提交
231 232
}

T
tangwei12 已提交
233
void AsyncCommunicator::Recv() {
234
  if (independent_recv_thread_) {
T
tangwei12 已提交
235
    return;
236 237
  }

T
tangwei12 已提交
238 239 240 241 242 243
  auto grad_num = grad_num_.load();
  if (grad_num > 0) {
    RecvAll();
    grad_num_.store(0);
  } else {
    std::this_thread::sleep_for(std::chrono::milliseconds(10));
244 245 246
  }
}

T
tangwei12 已提交
247 248 249 250 251 252 253 254 255 256 257
void AsyncCommunicator::RecvAll() {
  VLOG(3) << "parallel run recv graph";
  if (!running_) return;
  auto before_send = GetCurrentUS();
  std::vector<std::future<void>> task_futures;
  task_futures.reserve(recv_varname_to_ctx_.size());
  for (auto &iter : recv_varname_to_ctx_) {
    auto recv_task = [this, &iter] {
      auto &var_name = iter.first;
      VLOG(4) << "recv var " << var_name;
      auto recv_functor = distributed::ParameterRecv<float>();
258
      recv_functor(iter.second, *recv_scope_);
T
tangwei12 已提交
259 260 261 262 263 264 265
    };
    task_futures.emplace_back(recv_threadpool_->enqueue(std::move(recv_task)));
  }
  for (auto &task : task_futures) {
    task.wait();
  }
  auto after_recv = GetCurrentUS();
266
  VLOG(3) << "run recv graph use time " << after_recv - before_send;
267 268
}

T
tangwei12 已提交
269
void AsyncCommunicator::Start() {
270 271 272 273 274 275 276 277
  VLOG(0) << "Communicator start";
  if (!communicator_) {
    VLOG(0) << "Communicator is not inited, do nothing";
  } else {
    VLOG(1) << "start send thread and recv thread";
    running_ = true;
    // start send and recv thread
    send_thread_.reset(
T
tangwei12 已提交
278
        new std::thread(std::bind(&AsyncCommunicator::SendThread, this)));
279
    if (independent_recv_thread_) {
280
      recv_thread_.reset(
T
tangwei12 已提交
281
          new std::thread(std::bind(&AsyncCommunicator::RecvThread, this)));
282 283 284 285
    }
  }
}

T
tangwei12 已提交
286
void AsyncCommunicator::Stop() {
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
  VLOG(0) << "Communicator stop";
  running_ = false;
  if (!communicator_) {
    VLOG(0) << "Communicator is not inited, do nothing";
  } else {
    if (send_thread_) {
      VLOG(1) << "stop send thread";
      send_thread_->join();
      send_thread_.reset(nullptr);
    }
    if (recv_thread_) {
      VLOG(1) << "stop recv thread";
      recv_thread_->join();
      recv_thread_.reset(nullptr);
    }
Q
Qiao Longfei 已提交
302
  }
303
  VLOG(0) << "Communicator stop done";
Q
Qiao Longfei 已提交
304 305
}

306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
void AsyncCommunicator::Send(const std::vector<std::string> &var_names,
                             const std::vector<std::string> &var_tables,
                             const framework::Scope &scope) {
  PADDLE_ENFORCE_EQ(
      var_names.size(), 1,
      platform::errors::InvalidArgument("var_names.size() == 1 is permitted"));
  auto var_name = var_names[0];
  // push var into send queue by var_name
  auto *grad_var = scope.FindVar(var_name);
  PADDLE_ENFORCE_EQ(
      grad_var->IsInitialized(), true,
      platform::errors::InvalidArgument("grad var should be inited"));

  auto tmp_grad_var = std::make_shared<Variable>();
  framework::CopyVariable(*grad_var, tmp_grad_var.get());
  auto &queue = send_varname_to_queue_.at(var_name);
  VLOG(3) << "send " << var_name << " queue size " << queue->Size();
  queue->Push(tmp_grad_var);
}
325 326 327 328 329 330

GeoSgdCommunicator::~GeoSgdCommunicator() {
  running_ = false;
  if (send_thread_) send_thread_->join();
}

331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
void GeoSgdCommunicator::InitImpl(const paddle::framework::ProgramDesc &program,
                                  Scope *recv_scope) {
  training_scope_ = std::move(recv_scope);

  auto geo_send_varnames = envs["geo_send_varnames"];
  auto varnames = paddle::string::Split(geo_send_varnames, '#');

  for (auto &var_name : varnames) {
    auto var_attr_str = envs.at(var_name);
    auto var_attrs = paddle::string::Split(var_attr_str, '#');
    auto split_varnames = paddle::string::Split(var_attrs[0], '&');
    auto sections = paddle::string::Split(var_attrs[1], '&');
    auto endpoints = paddle::string::Split(var_attrs[2], '&');
    bool is_sparse = static_cast<bool>(std::stoi(var_attrs[3]));

346 347
    std::string send_var_name = VarToDeltaVar(var_name);
    std::vector<std::string> send_var_names;
348
    for (auto origin_var_name : split_varnames) {
349 350 351 352
      send_var_names.push_back(VarToDeltaVar(origin_var_name));
    }

    std::vector<int64_t> vars_sections_int = {};
353
    for (std::string str : sections) {
354 355 356 357 358 359
      int64_t str2i = std::stol(str.c_str());
      vars_sections_int.push_back(str2i);
    }

    var_list_[var_name] = is_sparse;
    send_varname_to_ctx_[send_var_name] = operators::distributed::RpcContext(
360
        send_var_name, send_var_names, endpoints, vars_sections_int, 0);
361
    recv_varname_to_ctx_[var_name] = operators::distributed::RpcContext(
362
        var_name, split_varnames, endpoints, vars_sections_int, 0);
C
Chengmo 已提交
363

364 365 366 367 368 369
    absolute_section_[var_name] = operators::ToAbsoluteSection(
        send_varname_to_ctx_[send_var_name].height_sections);

    vars_first_dimension_[var_name] = 0;
    for (int64_t section : vars_sections_int) {
      vars_first_dimension_[var_name] += section;
C
Chengmo 已提交
370
    }
371
    send_var_nums_ += split_varnames.size();
372 373 374 375 376 377
  }

  if (send_varname_to_ctx_.size() == 0 && recv_varname_to_ctx_.size() == 0) {
    LOG(WARNING) << "no var need to send and recv!!";
  }

378
  send_threadpool_.reset(new ::ThreadPool(thread_pool_size_));
379 380
  need_push_queue_ =
      std::make_shared<BlockingQueue<std::shared_ptr<SparseIdsMap>>>(
381
          geo_need_push_nums_);
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
  delta_scope_.reset(new Scope());
  old_scope_.reset(new Scope());
  pserver_scope_.reset(new Scope());
}

void GeoSgdCommunicator::Start() {
  VLOG(0) << "Geo Sgd Communicator start";
  if (!communicator_) {
    VLOG(0) << "Geo Sgd Communicator is not inited, do nothing";
  } else {
    VLOG(0) << "start send thread ";
    running_ = true;
    // start send and recv thread
    send_thread_.reset(
        new std::thread(std::bind(&GeoSgdCommunicator::SendThread, this)));
  }
}

void GeoSgdCommunicator::Stop() {
  VLOG(0) << "Geo Sgd Communicator stop";
  running_ = false;
  if (!communicator_) {
    VLOG(0) << "Geo Sgd Communicator is not inited, do nothing";
  } else {
    if (send_thread_) {
      VLOG(1) << "stop send thread";
      send_thread_->join();
      send_thread_.reset(nullptr);
    }
  }
  VLOG(0) << "Geo Sgd Communicator stop done";
}

415 416
void GeoSgdCommunicator::Send(const std::vector<std::string> &sparse_var_names,
                              const std::vector<std::string> &sparse_var_tables,
417
                              const framework::Scope &scope) {
418
  if (sparse_var_names.size() == 1 && sparse_var_names[0] == "param_init") {
419 420 421 422 423 424 425 426 427 428 429 430 431
    for (auto &iter : var_list_) {
      // For sparse param, old_scope store LoDTensor,
      // pserver_scope store SelectedRows.
      auto local_var_name = iter.first;
      if (var_list_[local_var_name] == true) {
        GeoSgdSparseParamInit(training_scope_, pserver_scope_.get(),
                              local_var_name);
      } else {
        GeoSgdDenseParamInit(training_scope_, pserver_scope_.get(),
                             local_var_name);
      }
      GeoSgdDenseParamInit(training_scope_, old_scope_.get(), local_var_name);
    }
C
Chengmo 已提交
432
    return;
433 434 435
  }

  std::shared_ptr<SparseIdsMap> ids_table = std::make_shared<SparseIdsMap>();
C
Chengmo 已提交
436
  auto before_run_send = GetCurrentUS();
437 438 439
  for (size_t i = 0; i < sparse_var_tables.size(); i++) {
    if (ids_table->find(sparse_var_tables[i]) == ids_table->end()) {
      // create empty set for new sparse var
C
Chengmo 已提交
440 441 442 443 444 445
      auto splited_var_nums =
          recv_varname_to_ctx_[sparse_var_tables[i]].splited_var_names.size();
      ids_table->insert(
          std::pair<std::string, std::vector<std::unordered_set<int64_t>>>(
              sparse_var_tables[i],
              std::vector<std::unordered_set<int64_t>>{splited_var_nums}));
446 447 448 449 450 451
    }
    auto *var = scope.FindVar(sparse_var_names[i]);
    auto var_tensor = var->Get<framework::LoDTensor>();
    int element_number = var_tensor.numel();
    int *var_mutable_data = var_tensor.mutable_data<int>(var_tensor.place());
    // insert ids which has not been record
452
    for (int j = 0; j < element_number; j++) {
C
Chengmo 已提交
453 454 455
      auto ep_idx = GetSectionIndex(var_mutable_data[j],
                                    absolute_section_[sparse_var_tables[i]]);
      ids_table->at(sparse_var_tables[i])[ep_idx].insert(var_mutable_data[j]);
456 457 458 459 460
      VLOG(4) << "Sparse var " << sparse_var_tables[i] << " insert "
              << var_mutable_data[j];
    }
  }
  need_push_queue_->Push(ids_table);
C
Chengmo 已提交
461
  auto after_run_send = GetCurrentUS();
462
  VLOG(4) << "run send_op use time " << after_run_send - before_run_send;
463 464 465 466 467 468 469 470
}

void GeoSgdCommunicator::SendThread() {
  VLOG(0) << "SendThread start!";
  auto before_run_training = GetCurrentUS();

  while (running_) {
    std::vector<std::future<void>> task_futures;
471
    task_futures.reserve(send_var_nums_);
472

473
    int wait_times = 0;
474
    while (ids_send_vec_.size() < static_cast<size_t>(geo_need_push_nums_)) {
475 476
      VLOG(4) << "ids_send_vec_ Size: " << ids_send_vec_.size();
      if (need_push_queue_->Size() > 0) {
C
Chengmo 已提交
477
        wait_times = 0;
478 479
        ids_send_vec_.push_back(*(need_push_queue_->Pop()));
        VLOG(4) << "ids_send_vec_ pushed";
C
Chengmo 已提交
480
      } else if (need_push_queue_->Size() == 0) {
481
        VLOG(4) << "wait_times -> " << wait_times;
482
        if (wait_times >= send_wait_times_) {
C
Chengmo 已提交
483 484 485 486 487
          break;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
        wait_times++;
        continue;
488 489 490
      }
    }

491
    if (ids_send_vec_.size() >= static_cast<size_t>(geo_need_push_nums_)) {
492
      auto after_run_training = GetCurrentUS();
493
      VLOG(4) << "run Training use time "
494 495
              << after_run_training - before_run_training;
      before_run_training = GetCurrentUS();
496
      VLOG(4) << "Start send after get need_push_num";
497 498 499

      for (auto &iter : send_varname_to_ctx_) {
        auto &var_name = iter.first;
C
Chengmo 已提交
500 501 502 503 504
        if (var_list_[DeltaVarToVar(var_name)] == true) {
          // sparse var: merge->send->recv
          for (auto &splited_var_name : iter.second.splited_var_names) {
            auto send_task = [this, &var_name, &splited_var_name] {
              auto before_run_geo = GetCurrentUS();
505
              VLOG(4) << "ids_send_vec_ size: " << ids_send_vec_.size();
C
Chengmo 已提交
506 507 508 509 510
              auto ids_set =
                  SparseIdsMerge(ids_send_vec_, var_name, splited_var_name);
              SendUpdateSparseVars(var_name, splited_var_name, ids_set);
              RecvUpdateSparseVars(var_name, splited_var_name);
              auto after_run_geo = GetCurrentUS();
511
              VLOG(3) << "run GEO-SGD var " << splited_var_name << " use time "
C
Chengmo 已提交
512 513 514 515
                      << after_run_geo - before_run_geo;
            };
            task_futures.emplace_back(
                send_threadpool_->enqueue(std::move(send_task)));
516
          }
C
Chengmo 已提交
517
        } else {
518 519 520 521 522 523 524 525 526 527 528 529
          for (auto &splited_var_name : iter.second.splited_var_names) {
            auto send_task = [this, &var_name, &splited_var_name] {
              auto before_run_geo = GetCurrentUS();
              SendUpdateDenseVars(var_name, splited_var_name);
              RecvUpdateDenseVars(var_name, splited_var_name);
              auto after_run_geo = GetCurrentUS();
              VLOG(3) << "run GEO-SGD var " << splited_var_name << " use time "
                      << after_run_geo - before_run_geo;
            };
            task_futures.emplace_back(
                send_threadpool_->enqueue(std::move(send_task)));
          }
C
Chengmo 已提交
530
        }
531
      }
C
Chengmo 已提交
532 533 534 535
      for (auto &task_f : task_futures) {
        task_f.wait();
      }
      ids_send_vec_.clear();
536 537 538 539 540
    }
  }
}

std::unordered_set<int64_t> GeoSgdCommunicator::SparseIdsMerge(
C
Chengmo 已提交
541 542
    const std::vector<SparseIdsMap> &ids_send_vec, const std::string &var_name,
    const std::string &splited_var_name) {
543
  // every batch has some sparse id, merge them into one unoredered_set
544
  VLOG(4) << "Sparse Ids merge var: " << var_name
T
tianshuo78520a 已提交
545
          << " split var: " << splited_var_name;
546
  auto before_run_ids_merge_ = GetCurrentUS();
C
Chengmo 已提交
547 548
  auto origin_var_name = DeltaVarToVar(var_name);
  auto splited_var_index = GetSplitedVarIndex(var_name, splited_var_name);
549 550
  std::unordered_set<int64_t> ids_set;
  for (auto ids_map : ids_send_vec) {
C
Chengmo 已提交
551
    for (auto id : ids_map[origin_var_name][splited_var_index]) {
552 553 554 555
      ids_set.insert(id);
    }
  }
  auto after_run_ids_merge_ = GetCurrentUS();
556
  VLOG(4) << "run SparseIdsMerge " << splited_var_name << " has nums "
C
Chengmo 已提交
557
          << ids_set.size() << " use time "
558 559 560 561
          << after_run_ids_merge_ - before_run_ids_merge_;
  return ids_set;
}

562 563
void GeoSgdCommunicator::SendUpdateDenseVars(
    const std::string &var_name, const std::string &splited_var_name) {
564 565
  // calc var_delata = (var_training - var_old)/trainer_nums
  // calc var_old += var_delta
C
Chengmo 已提交
566 567
  // var_name: param.delta
  auto origin_var_name = DeltaVarToVar(var_name);
568
  auto splited_var_index = GetSplitedVarIndex(var_name, splited_var_name);
T
tianshuo78520a 已提交
569 570
  VLOG(4) << "Dense var: " << var_name << " 's split var: " << splited_var_name
          << " split var index: " << splited_var_index;
571
  auto before_run_send_dense = GetCurrentUS();
572
  auto cpu_ctx = paddle::platform::CPUDeviceContext();
573

C
Chengmo 已提交
574
  auto *var_x = training_scope_->FindVar(origin_var_name);
575 576
  auto var_x_tensor = var_x->Get<framework::LoDTensor>();

C
Chengmo 已提交
577
  auto *var_y = old_scope_->FindVar(origin_var_name);
578 579 580
  auto var_y_tensor = var_y->Get<framework::LoDTensor>();

  auto dims = var_x_tensor.dims();
581 582 583 584 585 586 587 588 589 590 591 592
  auto total_element = var_x_tensor.numel();
  int64_t section = 0;
  int64_t begin_loc = 0;
  int64_t dimension = 0;

  size_t out_num = send_varname_to_ctx_[var_name].height_sections.size();
  if (out_num > 1) {
    section = send_varname_to_ctx_[var_name].height_sections[splited_var_index];
    dims[0] = section;
    begin_loc = absolute_section_[origin_var_name][splited_var_index];
    dimension = total_element / vars_first_dimension_[origin_var_name];
    total_element = section * dimension;
T
tianshuo78520a 已提交
593
    VLOG(4) << "Dense split var: " << splited_var_name
594 595 596 597
            << " section: " << section << " dimension: " << dimension
            << " begin loc: " << begin_loc << " total_element "
            << total_element;
  }
598

599 600
  auto *var_x_data = var_x_tensor.mutable_data<float>(var_x_tensor.place()) +
                     begin_loc * dimension;
T
tianshuo78520a 已提交
601
  VLOG(4) << "Dense split var: " << splited_var_name << " var_x_data[0] "
602 603 604 605
          << var_x_data[0] << " var_x_data[end] "
          << var_x_data[total_element - 1];
  auto *var_y_data = var_y_tensor.mutable_data<float>(var_y_tensor.place()) +
                     begin_loc * dimension;
T
tianshuo78520a 已提交
606
  VLOG(4) << "Dense split var: " << splited_var_name << " var_y_data[0] "
607 608
          << var_y_data[0] << " var_y_data[end] "
          << var_y_data[total_element - 1];
609 610

  // create delta var in delta scope
611 612 613 614 615
  auto *var_z_tensor =
      delta_scope_->Var(splited_var_name)->GetMutable<framework::LoDTensor>();
  var_z_tensor->Resize(dims);
  var_z_tensor->mutable_data<float>(dims, cpu_ctx.GetPlace());
  auto *var_z_data = var_z_tensor->mutable_data<float>(cpu_ctx.GetPlace());
616

T
tianshuo78520a 已提交
617
  VLOG(4) << "Dense split var: " << splited_var_name << "var_z_data[0] "
618 619
          << var_z_data[0] << " var_z_data[end] "
          << var_z_data[total_element - 1];
620 621 622

  // calc sub = var_training - var_old
  auto blas = math::GetBlas<paddle::platform::CPUDeviceContext, float>(cpu_ctx);
623
  blas.VSUB(total_element, var_x_data, var_y_data, var_z_data);
T
tianshuo78520a 已提交
624
  VLOG(4) << "Dense split var: " << splited_var_name << " var_z_data[0] "
625 626
          << var_z_data[0] << " var_z_data[end] "
          << var_z_data[total_element - 1];
627 628 629

  // calc var_delta = sub / trainer_nums
  float trainer_param = 1.0 / static_cast<float>(trainer_nums_);
630
  blas.SCAL(total_element, trainer_param, var_z_data);
631 632

  // calc var_old += var_delta
633
  blas.VADD(total_element, var_y_data, var_z_data, var_y_data);
T
tianshuo78520a 已提交
634
  VLOG(4) << "Dense split var: " << splited_var_name << " var_y_data[0] "
635 636
          << var_y_data[0] << " var_y_data[end] "
          << var_y_data[total_element - 1];
637 638

  auto after_run_send_dense = GetCurrentUS();
639
  VLOG(4) << "run send update dense var " << var_name << " use time "
640
          << after_run_send_dense - before_run_send_dense;
C
Chengmo 已提交
641 642

  auto before_send_dense = GetCurrentUS();
643 644 645 646
  RpcSend(var_name, splited_var_name, splited_var_index);
  auto after_send_dense = GetCurrentUS();
  VLOG(4) << "send " << splited_var_name << " use time "
          << after_send_dense - before_send_dense;
647 648 649
}

void GeoSgdCommunicator::SendUpdateSparseVars(
C
Chengmo 已提交
650 651
    const std::string &var_name, const std::string &splited_var_name,
    const std::unordered_set<int64_t> &ids_table) {
652 653
  // calc var_delata = (var_training - var_old)/trainer_nums
  // calc var_old += var_delta
C
Chengmo 已提交
654 655
  // var_name: param.delta, splited_var_name: param.block0.delta
  // origin_var_name: param
656 657 658
  auto before_run_send_sparse = GetCurrentUS();

  auto ids_num = ids_table.size();
C
Chengmo 已提交
659 660 661 662
  VLOG(4) << "Sparse Ids nums is : " << ids_num;
  auto origin_var_name = DeltaVarToVar(var_name);

  auto *var_x = training_scope_->FindVar(origin_var_name);
663 664
  auto var_x_tensor = var_x->Get<framework::LoDTensor>();

C
Chengmo 已提交
665
  auto *var_y = old_scope_.get()->FindVar(origin_var_name);
666 667 668 669 670 671 672 673
  auto var_y_tensor = var_y->Get<framework::LoDTensor>();

  auto dims = var_x_tensor.dims();
  auto row_numel = dims[1];

  float *x_value = var_x_tensor.mutable_data<float>(var_x_tensor.place());
  float *y_value = var_y_tensor.mutable_data<float>(var_y_tensor.place());

C
Chengmo 已提交
674
  auto *var_z = delta_scope_->Var(splited_var_name);
675 676 677 678 679 680 681
  auto *var_z_select_rows = var_z->GetMutable<framework::SelectedRows>();
  auto *var_z_value = var_z_select_rows->mutable_value();
  var_z_value->Resize({static_cast<int64_t>(ids_num), row_numel});
  auto *z_value = var_z_value->mutable_data<float>(var_x_tensor.place());

  std::vector<int64_t> new_rows;
  new_rows.insert(new_rows.begin(), ids_table.begin(), ids_table.end());
C
Chengmo 已提交
682 683 684 685

  auto cpu_ctx = paddle::platform::CPUDeviceContext();
  auto blas = math::GetBlas<paddle::platform::CPUDeviceContext, float>(cpu_ctx);
  float avg = 1 / static_cast<float>(trainer_nums_);
686
  for (size_t y = 0; y < new_rows.size(); y++) {
C
Chengmo 已提交
687 688 689 690 691 692 693
    auto ids = new_rows[y];

    float *x_val = x_value + ids * row_numel;
    float *y_val = y_value + ids * row_numel;
    float *z_val = z_value + y * row_numel;

    std::vector<float> row_delta(row_numel, 0);
694
    blas.VSUB(row_numel, x_val, y_val, row_delta.data());
C
Chengmo 已提交
695 696 697
    blas.SCAL(row_numel, avg, row_delta.data());
    blas.VADD(row_numel, row_delta.data(), y_val, y_val);
    blas.VCOPY(row_numel, row_delta.data(), z_val);
698
  }
C
Chengmo 已提交
699

700
  auto after_run_send_sparse = GetCurrentUS();
701
  VLOG(4) << "run send update sparse var " << splited_var_name << " use time "
702
          << after_run_send_sparse - before_run_send_sparse;
C
Chengmo 已提交
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717

  auto splited_var_index = GetSplitedVarIndex(var_name, splited_var_name);
  std::vector<int64_t> send_rows;
  send_rows.reserve(new_rows.size());
  for (auto idx : new_rows) {
    send_rows.push_back(idx -
                        absolute_section_[origin_var_name][splited_var_index]);
  }
  var_z_select_rows->set_rows(send_rows);
  var_z_select_rows->set_height(
      send_varname_to_ctx_[var_name].height_sections[splited_var_index]);

  auto before_send_sparse = GetCurrentUS();
  RpcSend(var_name, splited_var_name, splited_var_index);
  auto after_send_sparse = GetCurrentUS();
718
  VLOG(4) << "send " << splited_var_name << " has nums " << new_rows.size()
C
Chengmo 已提交
719
          << " use time " << after_send_sparse - before_send_sparse;
720 721
}

722 723
void GeoSgdCommunicator::RecvUpdateDenseVars(
    const std::string &var_name, const std::string &splited_var_name) {
724 725
  // calc var_training += var_pserver - var_old
  // calc var_old = var_pserver
C
Chengmo 已提交
726 727 728 729
  // var_name: param.delta

  // step1: recv dense var from pserver
  auto origin_var_name = DeltaVarToVar(var_name);
730 731 732
  auto origin_splited_var_name = DeltaVarToVar(splited_var_name);
  auto splited_var_index = GetSplitedVarIndex(var_name, splited_var_name);
  auto cpu_ctx = paddle::platform::CPUDeviceContext();
C
Chengmo 已提交
733 734

  auto before_run_recv = GetCurrentUS();
735 736 737 738
  VLOG(4) << "Dense recv origin_var_name: " << origin_var_name
          << " origin_splited_var_name: " << origin_splited_var_name
          << " splited_var_index: " << splited_var_index;
  RpcRecv(origin_var_name, origin_splited_var_name, splited_var_index);
C
Chengmo 已提交
739
  auto after_run_recv = GetCurrentUS();
740
  VLOG(4) << "recv var " << origin_splited_var_name << " use time "
C
Chengmo 已提交
741 742 743 744 745 746 747 748 749 750
          << after_run_recv - before_run_recv;

  // step2: update dense var
  auto before_run_update = GetCurrentUS();
  auto *var_x = training_scope_->FindVar(origin_var_name);
  auto var_x_tensor = var_x->Get<framework::LoDTensor>();

  auto *var_y = old_scope_->FindVar(origin_var_name);
  auto var_y_tensor = var_y->Get<framework::LoDTensor>();

751
  auto *var_z = pserver_scope_.get()->FindVar(origin_splited_var_name);
C
Chengmo 已提交
752
  auto var_z_tensor = var_z->Get<framework::LoDTensor>();
753 754 755 756 757 758 759 760 761 762 763
  auto dims = var_z_tensor.dims();
  auto total_element = var_z_tensor.numel();

  int64_t section = 0;
  int64_t begin_loc = 0;
  int64_t dimension = 0;
  size_t out_num = recv_varname_to_ctx_[origin_var_name].height_sections.size();
  if (out_num > 1) {
    section = dims[0];
    begin_loc = absolute_section_[origin_var_name][splited_var_index];
    dimension = total_element / section;
T
tianshuo78520a 已提交
764
    VLOG(4) << "Dense split var: " << splited_var_name
765 766 767 768 769 770 771
            << " section: " << section << " dimension: " << dimension
            << " begin loc: " << begin_loc << " total_element "
            << total_element;
  }

  auto *var_x_data = var_x_tensor.mutable_data<float>(var_x_tensor.place()) +
                     begin_loc * dimension;
T
tianshuo78520a 已提交
772
  VLOG(4) << "Dense split var: " << splited_var_name << " var_x_data[0] "
773 774 775 776 777
          << var_x_data[0] << " var_x_data[end] "
          << var_x_data[total_element - 1];

  auto *var_y_data = var_y_tensor.mutable_data<float>(var_y_tensor.place()) +
                     begin_loc * dimension;
T
tianshuo78520a 已提交
778
  VLOG(4) << "Dense split var: " << splited_var_name << " var_y_data[0] "
779 780 781 782
          << var_y_data[0] << " var_y_data[end] "
          << var_y_data[total_element - 1];

  auto *var_z_data = var_z_tensor.mutable_data<float>(cpu_ctx.GetPlace());
T
tianshuo78520a 已提交
783
  VLOG(4) << "Dense split var: " << splited_var_name << " var_z_data[0] "
784 785 786 787 788 789 790 791 792 793
          << var_z_data[0] << " var_z_data[end] "
          << var_z_data[total_element - 1];

  auto *var_y_sub_tensor = old_scope_->Var(origin_splited_var_name)
                               ->GetMutable<framework::LoDTensor>();
  var_y_sub_tensor->Resize(dims);
  var_y_sub_tensor->mutable_data<float>(dims, cpu_ctx.GetPlace());
  auto *var_y_sub_data =
      var_y_sub_tensor->mutable_data<float>(cpu_ctx.GetPlace());

T
tianshuo78520a 已提交
794
  VLOG(4) << "Dense split var: " << splited_var_name << " var_y_sub_data[0] "
795 796
          << var_y_sub_data[0] << " var_y_sub_data[end] "
          << var_y_sub_data[total_element - 1];
C
Chengmo 已提交
797 798

  auto blas = math::GetBlas<paddle::platform::CPUDeviceContext, float>(cpu_ctx);
799

C
Chengmo 已提交
800
  // calc sub = pserver - old
801
  blas.VSUB(total_element, var_z_data, var_y_data, var_y_sub_data);
T
tianshuo78520a 已提交
802
  VLOG(4) << "Dense split var: " << splited_var_name << " var_y_sub_data[0] "
803 804 805 806 807
          << var_y_sub_data[0] << " var_y_sub_data[end] "
          << var_y_sub_data[total_element - 1];

  // calc train += sub
  blas.VADD(total_element, var_x_data, var_y_sub_data, var_x_data);
T
tianshuo78520a 已提交
808
  VLOG(4) << "Dense split var: " << splited_var_name << " var_x_data[0] "
809 810 811
          << var_x_data[0] << " var_x_data[end] "
          << var_x_data[total_element - 1];

C
Chengmo 已提交
812
  // calc old = pserver
813
  blas.VCOPY(total_element, var_z_data, var_y_data);
T
tianshuo78520a 已提交
814
  VLOG(4) << "Dense split var: " << splited_var_name << " var_y_data[0] "
815 816 817
          << var_y_data[0] << " var_y_data[end] "
          << var_y_data[total_element - 1];

C
Chengmo 已提交
818
  auto after_run_update = GetCurrentUS();
819
  VLOG(4) << "dense var update " << origin_splited_var_name << " use time "
C
Chengmo 已提交
820 821 822 823 824
          << after_run_update - before_run_update;
}

void GeoSgdCommunicator::RecvUpdateSparseVars(
    const std::string &var_name, const std::string &splited_var_name) {
T
tianshuo78520a 已提交
825
  // step 1: recv split var from pserver
C
Chengmo 已提交
826 827 828 829
  auto splited_var_index = GetSplitedVarIndex(var_name, splited_var_name);
  auto origin_var_name = DeltaVarToVar(var_name);
  auto origin_splited_var_name = DeltaVarToVar(splited_var_name);

830
  auto before_run_recv = GetCurrentUS();
C
Chengmo 已提交
831 832
  RpcRecv(origin_var_name, origin_splited_var_name, splited_var_index);
  auto after_run_recv = GetCurrentUS();
833
  VLOG(4) << "recv var " << origin_splited_var_name << " use time "
C
Chengmo 已提交
834
          << after_run_recv - before_run_recv;
835

C
Chengmo 已提交
836 837 838
  // step 2: update sparse var
  auto before_run_update = GetCurrentUS();
  auto *var_x = training_scope_->FindVar(origin_var_name);
839
  auto var_x_tensor = var_x->Get<framework::LoDTensor>();
C
Chengmo 已提交
840
  auto dims = var_x_tensor.dims();
841 842
  float *x_value = var_x_tensor.mutable_data<float>(var_x_tensor.place());

C
Chengmo 已提交
843
  auto *var_y = old_scope_->FindVar(origin_var_name);
844 845 846
  auto var_y_tensor = var_y->Get<framework::LoDTensor>();
  float *y_value = var_y_tensor.mutable_data<float>(var_y_tensor.place());

C
Chengmo 已提交
847 848 849 850 851 852 853 854 855 856
  auto *var_z = pserver_scope_.get()->FindVar(origin_splited_var_name);
  auto var_z_slr = var_z->GetMutable<framework::SelectedRows>();
  auto row_size = var_z_slr->rows().size();

  std::vector<int64_t> new_rows;
  new_rows.reserve(row_size);

  for (auto ids : var_z_slr->rows()) {
    new_rows.push_back(ids +
                       absolute_section_[origin_var_name][splited_var_index]);
857 858
  }

C
Chengmo 已提交
859 860 861 862 863 864
  auto *new_value = var_z_slr->mutable_value();
  auto row_numel = dims[1];
  auto *z_value = new_value->mutable_data<float>(var_x_tensor.place());

  auto cpu_ctx = paddle::platform::CPUDeviceContext();
  auto blas = math::GetBlas<paddle::platform::CPUDeviceContext, float>(cpu_ctx);
865
  for (size_t y = 0; y < new_rows.size(); y++) {
C
Chengmo 已提交
866 867 868 869 870 871 872 873
    std::vector<float> row_delta(row_numel, 0);

    auto ids = new_rows[y];

    float *x_val = x_value + ids * row_numel;
    float *y_val = y_value + ids * row_numel;
    float *z_val = z_value + y * row_numel;

874
    blas.VSUB(row_numel, z_val, y_val, row_delta.data());
C
Chengmo 已提交
875 876 877 878 879
    blas.VADD(row_numel, row_delta.data(), x_val, x_val);
    blas.VCOPY(row_numel, z_val, y_val);
  }

  auto after_run_update = GetCurrentUS();
880
  VLOG(4) << "sparse var recv update " << origin_splited_var_name << " has num "
C
Chengmo 已提交
881 882
          << new_rows.size() << " use time "
          << after_run_update - before_run_update;
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
}

void GeoSgdCommunicator::GeoSgdSparseParamInit(framework::Scope *scope_x,
                                               framework::Scope *scope_y,
                                               const std::string var_name) {
  // create selectedrows var from lodtensor var info
  auto *var_x = scope_x->Var(var_name);
  auto *var_y = scope_y->Var(var_name);

  auto var_x_tensor = var_x->Get<framework::LoDTensor>();
  auto *var_y_select_rows = var_y->GetMutable<framework::SelectedRows>();

  auto dims = var_x_tensor.dims();
  auto rows = dims[0];
  auto row_numel = dims[1];

  var_y_select_rows->set_height(rows);
  std::vector<int64_t> new_rows{};
  var_y_select_rows->set_rows(new_rows);
  auto *var_y_value = var_y_select_rows->mutable_value();
  var_y_value->Resize({rows, row_numel});
  var_y_value->mutable_data<float>(var_x_tensor.place());
}

void GeoSgdCommunicator::GeoSgdDenseParamInit(framework::Scope *scope_x,
                                              framework::Scope *scope_y,
                                              const std::string var_name) {
  auto *var_x = scope_x->Var(var_name);
  auto *var_y = scope_y->Var(var_name);
  framework::CopyVariable(*var_x, var_y);
}

C
Chengmo 已提交
915 916 917 918 919 920 921 922 923 924 925
void GeoSgdCommunicator::RpcSend(const std::string &origin_var_name,
                                 const std::string &splited_var_name,
                                 const size_t &splited_var_index) {
  auto trainer_id = send_varname_to_ctx_[origin_var_name].trainer_id;
  auto endpoint =
      send_varname_to_ctx_[origin_var_name].epmap[splited_var_index];

  platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
  auto &cpu_ctx_send = *pool.Get(platform::CPUPlace());
  distributed::RPCClient *rpc_client =
      distributed::RPCClient::GetInstance<RPCCLIENT_T>(trainer_id);
926 927 928
  auto handle = rpc_client->AsyncSendVar(endpoint, cpu_ctx_send,
                                         *delta_scope_.get(), splited_var_name);
  handle->Wait();
C
Chengmo 已提交
929 930 931 932 933 934 935 936 937 938 939 940
}

void GeoSgdCommunicator::RpcRecv(const std::string &var_name,
                                 const std::string &splited_var_name,
                                 const size_t &splited_var_index) {
  auto train_id = recv_varname_to_ctx_[var_name].trainer_id;
  auto endpoint = recv_varname_to_ctx_[var_name].epmap[splited_var_index];
  platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
  auto &cpu_ctx_recv = *pool.Get(platform::CPUPlace());
  distributed::RPCClient *rpc_client =
      distributed::RPCClient::GetInstance<RPCCLIENT_T>(train_id);
  pserver_scope_->Var(splited_var_name);
941 942 943 944
  auto handle = rpc_client->AsyncGetVar(endpoint, cpu_ctx_recv,
                                        *pserver_scope_.get(), splited_var_name,
                                        splited_var_name, splited_var_name);
  handle->Wait();
C
Chengmo 已提交
945 946 947 948
}

void GeoSgdCommunicator::Recv() {}

949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
void HalfAsyncCommunicator::InitImpl(const RpcCtxMap &send_varname_to_ctx,
                                     const RpcCtxMap &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);

  if (send_varname_to_ctx.size() == 0) {
    VLOG(0) << "nothing need to be send, will not start send_thread";
  } else {
    send_scope_.reset(new Scope());
    for (auto &iter : send_varname_to_ctx_) {
      send_varname_to_queue_[iter.first] =
          std::make_shared<BlockingQueue<std::shared_ptr<Variable>>>(
              send_queue_size_);
    }
965

966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
    consume_threadpool_.reset(new ::ThreadPool(thread_pool_size_));
  }

  if (recv_varname_to_ctx.size() == 0) {
    VLOG(0) << "nothing need to be received, will not start recv_thread";
  } else {
    recv_threadpool_.reset(new ::ThreadPool(thread_pool_size_));
  }
}

void HalfAsyncCommunicator::InitImpl(
    const paddle::framework::ProgramDesc &program, Scope *param_scope) {
  RpcCtxMap send_varname_to_ctx;
  RpcCtxMap recv_varname_to_ctx;
  for (auto *op : program.Block(0).AllOps()) {
    VLOG(3) << "node name " << op->Type();
    if (op->Type() == "send") {
      auto send_var_name = op->Input("X")[0];
      auto send_varnames = boost::get<std::vector<std::string>>(
          op->GetNullableAttr("send_varnames"));
      auto epmap =
          boost::get<std::vector<std::string>>(op->GetNullableAttr("epmap"));
      auto height_section =
          boost::get<std::vector<int64_t>>(op->GetNullableAttr("sections"));
      auto trainer_id = boost::get<int>(op->GetNullableAttr("trainer_id"));
      send_varname_to_ctx[send_var_name] = operators::distributed::RpcContext(
          send_var_name, send_varnames, epmap, height_section, trainer_id);
      VLOG(3) << "find and init an send op: "
              << send_varname_to_ctx[send_var_name];
    } else if (op->Type() == "recv") {
      auto do_not_run = boost::get<int>(op->GetNullableAttr("do_not_run"));
      PADDLE_ENFORCE_GT(do_not_run, 0,
                        platform::errors::InvalidArgument(
                            "recv op's attr `do_not_run` must be True!"));
      auto recv_var_name = op->Output("Out")[0];
      auto recv_varnames = boost::get<std::vector<std::string>>(
          op->GetNullableAttr("recv_varnames"));
      auto epmap =
          boost::get<std::vector<std::string>>(op->GetNullableAttr("epmap"));
      auto trainer_id = boost::get<int>(op->GetNullableAttr("trainer_id"));
      recv_varname_to_ctx[recv_var_name] = operators::distributed::RpcContext(
          recv_var_name, recv_varnames, epmap, {}, trainer_id);
T
tangwei12 已提交
1008 1009
      VLOG(3) << "find and init an recv op: "
              << recv_varname_to_ctx[recv_var_name];
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
    }
  }

  // init communicator here
  if (send_varname_to_ctx.size() == 0 && recv_varname_to_ctx.size() == 0) {
    LOG(WARNING) << "no var need to send and recv!!";
  }

  operators::distributed::HalfAsyncCommunicator::InitImpl(
      send_varname_to_ctx, recv_varname_to_ctx, param_scope);
}

HalfAsyncCommunicator::~HalfAsyncCommunicator() {
  running_ = false;
  if (consume_thread_) consume_thread_->join();
}

void HalfAsyncCommunicator::ConsumeThread() {
  VLOG(3) << "ConsumeThread start!";
  while (running_) {
    while (running_) {
T
tangwei12 已提交
1031 1032
      if (barrier_counter_.load() >= barrier_trigger_.load() &&
          barrier_trigger_.load() != 0) {
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
        break;
      } else {
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
      }
    }

    std::vector<std::future<void>> task_futures;
    task_futures.reserve(send_varname_to_ctx_.size());
    VLOG(3) << "run send graph";
    auto before_run_send_graph = GetCurrentUS();
    for (auto &iter : send_varname_to_queue_) {
      auto &var_name = iter.first;
      auto &var_queue = iter.second;
      if (var_queue->Size() > 0) {
        auto send_task = [this, &var_name, &var_queue] {
          VLOG(3) << var_name << " merge and send";
          std::vector<std::shared_ptr<Variable>> vars;
          size_t merged_var_num = 0;
          size_t wait_times = 0;
          while (merged_var_num < static_cast<size_t>(max_merge_var_num_)) {
            if (var_queue->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;
            } else {
              wait_times = 0;
              vars.push_back(var_queue->Pop());
              merged_var_num++;
            }
          }
          auto before_merge = GetCurrentUS();

          MergeVars<float>(var_name, vars, send_scope_.get(), false);

          auto after_merge = GetCurrentUS();
          VLOG(3) << "merge " << merged_var_num << " " << var_name
                  << " use time " << after_merge - before_merge;

          auto send_functor = distributed::ParameterSend<float>();
          auto &ctx = send_varname_to_ctx_.at(var_name);
          send_functor(ctx, *send_scope_, true, 1);

          auto after_send = GetCurrentUS();
          VLOG(3) << "send " << var_name << " use time "
                  << after_send - after_merge;
        };
        task_futures.emplace_back(
            consume_threadpool_->enqueue(std::move(send_task)));
      } else {
        VLOG(4) << var_name << " queue empty";
      }
    }
    for (auto &task_f : task_futures) {
      task_f.wait();
    }
    auto after_run_send_graph = GetCurrentUS();

    VLOG(3) << "run send graph use time "
            << after_run_send_graph - before_run_send_graph;

T
tangwei12 已提交
1097 1098 1099
    BarrierSend();
    Recv();
    BarrierRecv();
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
    BarrierWeakUp();
  }
  VLOG(0) << "communicator stopped, send thread exit";
}

void HalfAsyncCommunicator::Send(const std::vector<std::string> &var_names,
                                 const std::vector<std::string> &var_tables,
                                 const framework::Scope &scope) {
  PADDLE_ENFORCE_EQ(
      var_names.size(), 1,
      platform::errors::InvalidArgument("var_names.size() == 1 is permitted"));
  auto var_name = var_names[0];
  VLOG(3) << "communicator send " << var_name;
  // push var into send queue by var_name
  auto *grad_var = scope.FindVar(var_name);
  PADDLE_ENFORCE_EQ(
      grad_var->IsInitialized(), true,
      platform::errors::InvalidArgument("grad var should is not initialized."));
  auto tmp_grad_var = std::make_shared<Variable>();
  framework::CopyVariable(*grad_var, tmp_grad_var.get());
  auto &queue = send_varname_to_queue_.at(var_name);
  VLOG(3) << "send " << var_name << " queue size " << queue->Size();
  queue->Push(tmp_grad_var);
}

void HalfAsyncCommunicator::Recv() {
  VLOG(3) << "parallel run recv graph";
  if (!running_) return;
  auto before_send = GetCurrentUS();
  std::vector<std::future<void>> task_futures;
  task_futures.reserve(recv_varname_to_ctx_.size());
  for (auto &iter : recv_varname_to_ctx_) {
    auto recv_task = [this, &iter] {
      auto &var_name = iter.first;
      VLOG(4) << "recv var " << var_name;
      auto recv_functor = distributed::ParameterRecv<float>();
      recv_functor(iter.second, *recv_scope_);
    };
    task_futures.emplace_back(recv_threadpool_->enqueue(std::move(recv_task)));
  }
  for (auto &task : task_futures) {
    task.wait();
  }
  auto after_recv = GetCurrentUS();
  VLOG(3) << "run recv graph use time " << after_recv - before_send;
}

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

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::BarrierWeakUp() {
  barrier_counter_.store(0);
  barrier_cond_.notify_all();
}

void HalfAsyncCommunicator::Start() {
  VLOG(0) << "Communicator start";
  if (!communicator_) {
    VLOG(0) << "Communicator is not inited, do nothing";
  } else {
    VLOG(1) << "start send thread and recv thread";

    BarrierTriggerReset(max_merge_var_num_);
    running_ = true;
    consume_thread_.reset(new std::thread(
        std::bind(&HalfAsyncCommunicator::ConsumeThread, this)));
  }
}

void HalfAsyncCommunicator::Stop() {
  VLOG(0) << "Communicator stop";
  running_ = false;
  if (!communicator_) {
    VLOG(0) << "Communicator is not inited, do nothing";
  } else {
    if (consume_thread_) {
      VLOG(4) << "stop send thread";
      consume_thread_->join();
      consume_thread_.reset(nullptr);
    }
  }
  VLOG(0) << "Communicator stop done";
}
1201

T
tangwei12 已提交
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
void SyncCommunicator::BarrierSend() {
  if (!running_) return;

  distributed::RPCClient *rpc_client =
      distributed::RPCClient::GetInstance<RPCCLIENT_T>(trainer_id_);

  std::vector<distributed::VarHandlePtr> rets;

  for (auto &ep : pserver_endpoints_) {
    rets.push_back(rpc_client->AsyncSendBatchBarrier(ep));
  }

  for (size_t i = 0; i < rets.size(); i++) {
    PADDLE_ENFORCE_NE(rets[i]->Wait(), 0U, platform::errors::External(
                                               "internal error in RPCClient"));
  }

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

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

  distributed::RPCClient *rpc_client =
      distributed::RPCClient::GetInstance<RPCCLIENT_T>(trainer_id_);

  std::vector<distributed::VarHandlePtr> rets;
  for (auto &ep : pserver_endpoints_) {
    rets.push_back(rpc_client->AsyncSendFetchBarrier(ep));
  }

  for (size_t i = 0; i < rets.size(); i++) {
    PADDLE_ENFORCE_NE(rets[i]->Wait(), 0U, platform::errors::External(
                                               "internal error in RPCClient"));
  }

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

SyncCommunicator::~SyncCommunicator() {
  running_ = false;
  if (consume_thread_) consume_thread_->join();
}
Q
Qiao Longfei 已提交
1245 1246 1247
}  // namespace distributed
}  // namespace operators
}  // namespace paddle