communicator.cc 40.9 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 30
#include "paddle/fluid/operators/distributed/parameter_recv.h"
#include "paddle/fluid/operators/distributed/parameter_send.h"

31 32 33
DECLARE_int32(communicator_max_merge_var_num);
DECLARE_int32(communicator_send_queue_size);

Q
Qiao Longfei 已提交
34 35
DEFINE_bool(communicator_independent_recv_thread, true,
            "use an independent to recv vars from parameter server");
36
DEFINE_int32(communicator_min_send_grad_num_before_recv, 20,
37
             "max grad num to send before recv parameters");
38
DEFINE_int32(communicator_thread_pool_size, 5, "thread num to do send or recv");
Q
Qiao Longfei 已提交
39 40 41
DEFINE_int32(communicator_send_wait_times, 5,
             "times that send thread will wait if merge num does not reach "
             "max_merge_var_num");
42 43
DEFINE_bool(communicator_fake_rpc, false,
            "fake mode does not really send any thing");
44 45
DEFINE_bool(communicator_merge_sparse_grad, true,
            "merge sparse gradient before sending");
46 47
DEFINE_int32(communicator_merge_sparse_bucket, 2000,
             "number of threads for sparse var");
Q
Qiao Longfei 已提交
48

Q
Qiao Longfei 已提交
49 50 51 52
namespace paddle {
namespace operators {
namespace distributed {

Q
Qiao Longfei 已提交
53 54 55 56 57 58
inline double GetCurrentUS() {
  struct timeval time;
  gettimeofday(&time, NULL);
  return 1e+6 * time.tv_sec + time.tv_usec;
}

59 60 61 62 63 64 65
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];
  }
}

1
123malin 已提交
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
void Communicator::SetEnvFlagsDefault() {
  env_flags_dict.clear();
  env_flags_dict.insert(std::pair<std::string, int>(
      "independent_recv_thread", FLAGS_communicator_independent_recv_thread));
  env_flags_dict.insert(std::pair<std::string, int>(
      "send_queue_size", FLAGS_communicator_send_queue_size));
  env_flags_dict.insert(std::pair<std::string, int>(
      "min_send_grad_num_before_recv",
      FLAGS_communicator_min_send_grad_num_before_recv));
  env_flags_dict.insert(std::pair<std::string, int>(
      "thread_pool_size", FLAGS_communicator_thread_pool_size));
  env_flags_dict.insert(std::pair<std::string, int>(
      "send_wait_times", FLAGS_communicator_send_wait_times));
  env_flags_dict.insert(std::pair<std::string, int>(
      "max_merge_var_num", FLAGS_communicator_max_merge_var_num));
  env_flags_dict.insert(
      std::pair<std::string, int>("fake_rpc", FLAGS_communicator_fake_rpc));
  env_flags_dict.insert(std::pair<std::string, int>(
      "merge_sparse_grad", FLAGS_communicator_merge_sparse_grad));
  env_flags_dict.insert(std::pair<std::string, int>(
      "is_sgd_optimizer", FLAGS_communicator_is_sgd_optimizer));

  return;
}

Communicator::Communicator() { SetEnvFlagsDefault(); }

Communicator::Communicator(const std::map<std::string, int> &env_flags) {
  SetEnvFlagsDefault();
  for (auto &iter : env_flags) {
    std::string flag_name = iter.first;
    int val_ = iter.second;
    env_flags_dict.at(flag_name) = val_;
  }
  return;
}

T
tangwei12 已提交
103
std::once_flag Communicator::init_flag_;
104
std::shared_ptr<Communicator> Communicator::communicator_(nullptr);
Q
can run  
Qiao Longfei 已提交
105

T
tangwei12 已提交
106 107 108 109 110 111 112
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);

113 114 115 116 117 118 119
  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>>>(
1
123malin 已提交
120
              env_flags_dict["send_queue_size"]);
121 122
    }
    send_threadpool_.reset(
1
123malin 已提交
123
        new ::ThreadPool(env_flags_dict["thread_pool_size"]));
124 125 126 127 128 129
  }

  if (recv_varname_to_ctx.size() == 0) {
    VLOG(0) << "nothing need to be received, will not start recv_thread";
  } else {
    recv_threadpool_.reset(
1
123malin 已提交
130
        new ::ThreadPool(env_flags_dict["thread_pool_size"]));
Q
Qiao Longfei 已提交
131 132 133
  }
}

T
tangwei12 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
void AsyncCommunicator::InitImpl(const paddle::framework::ProgramDesc &program,
                                 Scope *param_scope) {
  using RpcCtxMap = operators::distributed::RpcCtxMap;
  VLOG(3) << "ProcessGraph";
  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 已提交
151 152
      auto merge_add = boost::get<bool>(op->GetNullableAttr("merge_add"));
      if (!merge_add) {
1
123malin 已提交
153
        merge_add = static_cast<bool>(env_flags_dict["is_sgd_optimizer"]);
1
123malin 已提交
154 155 156
      }
      auto use_send_handler =
          boost::get<bool>(op->GetNullableAttr("use_send_handler"));
T
tangwei12 已提交
157
      send_varname_to_ctx[send_var_name] = operators::distributed::RpcContext(
1
123malin 已提交
158 159
          send_var_name, send_varnames, epmap, height_section, trainer_id,
          merge_add, use_send_handler);
T
tangwei12 已提交
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
      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, "recv should not run!");
      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() {
186 187 188 189
  if (FLAGS_v >= 3) {
    std::string msg("~Communicator");
    fwrite(msg.c_str(), msg.length(), 1, stdout);
  }
Q
Qiao Longfei 已提交
190 191 192
  running_ = false;
  if (send_thread_) send_thread_->join();
  if (recv_thread_) recv_thread_->join();
193 194 195 196
  if (FLAGS_v >= 3) {
    std::string msg("~Communicator done");
    fwrite(msg.c_str(), msg.length(), 1, stdout);
  }
Q
Qiao Longfei 已提交
197 198
}

T
tangwei12 已提交
199
void AsyncCommunicator::SendThread() {
Q
Qiao Longfei 已提交
200
  VLOG(3) << "SendThread start!";
Q
Qiao Longfei 已提交
201 202 203
  while (running_) {
    std::vector<std::future<void>> task_futures;
    task_futures.reserve(send_varname_to_ctx_.size());
204
    VLOG(4) << "run send graph";
Q
Qiao Longfei 已提交
205
    auto before_run_send_graph = GetCurrentUS();
Q
Qiao Longfei 已提交
206
    for (auto &iter : send_varname_to_queue_) {
Q
Qiao Longfei 已提交
207 208
      auto &var_name = iter.first;
      auto &var_queue = iter.second;
Q
Qiao Longfei 已提交
209
      if (var_queue->Size() > 0) {
Q
Qiao Longfei 已提交
210
        auto send_task = [this, &var_name, &var_queue] {
211
          VLOG(4) << var_name << " merge and send";
Q
Qiao Longfei 已提交
212
          std::vector<std::shared_ptr<Variable>> vars;
213 214
          int merged_var_num = 0;
          int wait_times = 0;
1
123malin 已提交
215
          while (merged_var_num < env_flags_dict["max_merge_var_num"]) {
Q
Qiao Longfei 已提交
216
            if (var_queue->Size() == 0) {
217
              VLOG(4) << "wait_times -> " << wait_times;
1
123malin 已提交
218
              if (wait_times >= env_flags_dict["send_wait_times"]) {
Q
Qiao Longfei 已提交
219 220 221 222 223 224 225 226 227 228 229 230 231 232
                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++;
233
            }
Q
Qiao Longfei 已提交
234
          }
Q
Qiao Longfei 已提交
235
          auto before_merge = GetCurrentUS();
1
123malin 已提交
236 237 238 239 240 241 242
          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 已提交
243
          auto after_merge = GetCurrentUS();
244
          VLOG(4) << "merge " << merged_var_num << " " << var_name
Q
Qiao Longfei 已提交
245
                  << " use time " << after_merge - before_merge;
Q
Qiao Longfei 已提交
246
          auto send_functor = distributed::ParameterSend<float>();
1
123malin 已提交
247
          if (!env_flags_dict["fake_rpc"]) {
248
            send_functor(ctx, *send_scope_, true, 1);
249
          }
Q
Qiao Longfei 已提交
250
          auto after_send = GetCurrentUS();
251
          VLOG(4) << "send " << var_name << " use time "
Q
Qiao Longfei 已提交
252
                  << after_send - after_merge;
Q
Qiao Longfei 已提交
253 254 255
        };
        task_futures.emplace_back(
            send_threadpool_->enqueue(std::move(send_task)));
Q
Qiao Longfei 已提交
256
      } else {
257
        VLOG(4) << var_name << " queue empty";
Q
Qiao Longfei 已提交
258
      }
Q
Qiao Longfei 已提交
259 260 261
    }
    for (auto &task_f : task_futures) {
      task_f.wait();
Q
Qiao Longfei 已提交
262
    }
Q
Qiao Longfei 已提交
263
    auto after_run_send_graph = GetCurrentUS();
264

265
    VLOG(4) << "run send graph use time "
266
            << after_run_send_graph - before_run_send_graph;
T
tangwei12 已提交
267
    Recv();
Q
Qiao Longfei 已提交
268
  }
269
  VLOG(0) << "communicator stopped, send thread exit";
Q
Qiao Longfei 已提交
270 271
}

T
tangwei12 已提交
272
void AsyncCommunicator::RecvThread() {
Q
Qiao Longfei 已提交
273
  VLOG(3) << "RecvThread start!";
Q
Qiao Longfei 已提交
274
  while (running_) {
275
    int grad_num = grad_num_.load();
1
123malin 已提交
276
    if (grad_num > env_flags_dict["min_send_grad_num_before_recv"]) {
277 278 279 280 281 282
      VLOG(1) << "current grad num " << grad_num;
      RecvAll();
      grad_num_.store(0);
    } else {
      std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
Q
Qiao Longfei 已提交
283
  }
284
  VLOG(0) << "communicator stopped, recv thread exit";
Q
Qiao Longfei 已提交
285 286
}

T
tangwei12 已提交
287 288
void AsyncCommunicator::Send(const std::string &var_name,
                             const framework::Scope &scope) {
Q
Qiao Longfei 已提交
289 290 291 292
  VLOG(3) << "communicator send " << var_name;
  // push var into send queue by var_name
  auto *grad_var = scope.FindVar(var_name);
  PADDLE_ENFORCE(grad_var->IsInitialized(), "grad var should be inited");
293
  if (grad_var->IsType<framework::SelectedRows>() &&
1
123malin 已提交
294
      !env_flags_dict["merge_sparse_grad"]) {
295 296
    auto send_functor = distributed::ParameterSend<float>();
    auto &ctx = send_varname_to_ctx_.at(var_name);
1
123malin 已提交
297
    if (!env_flags_dict["fake_rpc"]) {
298
      send_functor(ctx, scope, true, 1);
299 300 301 302 303 304 305 306
    }
  } else {
    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);
  }
Q
Qiao Longfei 已提交
307 308
}

T
tangwei12 已提交
309
void AsyncCommunicator::Recv() {
1
123malin 已提交
310
  if (env_flags_dict["independent_recv_thread"]) {
T
tangwei12 已提交
311
    return;
312 313
  }

T
tangwei12 已提交
314 315 316 317 318 319
  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));
320 321 322
  }
}

T
tangwei12 已提交
323 324 325 326 327 328 329 330 331 332 333
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>();
1
123malin 已提交
334
      if (!env_flags_dict["fake_rpc"]) {
T
tangwei12 已提交
335 336 337 338 339 340 341 342 343
        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();
344
  VLOG(3) << "run recv graph use time " << after_recv - before_send;
345 346
}

T
tangwei12 已提交
347
void AsyncCommunicator::Start() {
348 349 350 351 352 353 354 355
  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 已提交
356
        new std::thread(std::bind(&AsyncCommunicator::SendThread, this)));
1
123malin 已提交
357
    if (env_flags_dict["independent_recv_thread"]) {
358
      recv_thread_.reset(
T
tangwei12 已提交
359
          new std::thread(std::bind(&AsyncCommunicator::RecvThread, this)));
360 361 362 363
    }
  }
}

T
tangwei12 已提交
364
void AsyncCommunicator::Stop() {
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
  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 已提交
380
  }
381
  VLOG(0) << "Communicator stop done";
Q
Qiao Longfei 已提交
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 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
void AsyncCommunicator::Send(const std::vector<std::string> &sparse_var_names,
                             const std::vector<std::string> &sparse_var_tables,
                             const framework::Scope &scope) {}

void AsyncCommunicator::InitImpl(
    const paddle::framework::ProgramDesc &program, Scope *param_scope,
    std::map<std::string, std::map<std::string, std::vector<std::string>>>
        &vars_info,
    const int &trainers, const int &geo_need_push_nums) {}

GeoSgdCommunicator::~GeoSgdCommunicator() {
  if (FLAGS_v >= 3) {
    std::string msg("~Geo Sgd Communicator");
    fwrite(msg.c_str(), msg.length(), 1, stdout);
  }
  running_ = false;
  if (send_thread_) send_thread_->join();
  if (FLAGS_v >= 3) {
    std::string msg("~Geo Sgd Communicator done");
    fwrite(msg.c_str(), msg.length(), 1, stdout);
  }
}

void GeoSgdCommunicator::InitImpl(
    const paddle::framework::ProgramDesc &program, Scope *training_scope,
    std::map<std::string, std::map<std::string, std::vector<std::string>>>
        &vars_info,
    const int &trainers, const int &geo_need_push_nums) {
  training_scope_ = std::move(training_scope);
  trainer_nums_ = std::move(trainers);
  geo_need_push_nums_ = std::move(geo_need_push_nums);

  // get all send information from graph, build vars_to_send
  VLOG(0) << "Trainer nums: " << trainer_nums_;
  VLOG(0) << "geo_sgd_push_before_local_train_nums: " << geo_need_push_nums_;

  // process var info from transpiler
  for (auto &iter : vars_info) {
    // change var name in delta scope: "var" -> "var.delta"
    std::string var_name = iter.first;
    std::string send_var_name = VarToDeltaVar(var_name);
    std::vector<std::string> vars_names = iter.second["var_names"];
    std::vector<std::string> send_var_names;
    for (auto origin_var_name : vars_names) {
      send_var_names.push_back(VarToDeltaVar(origin_var_name));
    }

    // get vars section for split
    std::vector<std::string> vars_sections_str = iter.second["sections"];
    std::vector<int64_t> vars_sections_int = {};
    for (std::string str : vars_sections_str) {
      int64_t str2i = std::stol(str.c_str());
      vars_sections_int.push_back(str2i);
    }

    std::vector<std::string> vars_epmap = iter.second["epmap"];

    // record var is sparse or not
    bool is_sparse = iter.second["is_sparse"].front() == std::string("True");
    var_list_[var_name] = is_sparse;

    send_varname_to_ctx_[send_var_name] = operators::distributed::RpcContext(
        send_var_name, send_var_names, vars_epmap, vars_sections_int, 0);
    recv_varname_to_ctx_[var_name] = operators::distributed::RpcContext(
        var_name, vars_names, vars_epmap, vars_sections_int, 0);
C
Chengmo 已提交
449

450 451 452 453 454 455
    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 已提交
456
    }
457 458

    send_var_nums_ += vars_names.size();
459 460 461 462 463 464
  }

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

1
123malin 已提交
465
  send_threadpool_.reset(new ::ThreadPool(env_flags_dict["thread_pool_size"]));
466 467 468 469 470 471 472 473 474 475 476 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
  need_push_queue_ =
      std::make_shared<BlockingQueue<std::shared_ptr<SparseIdsMap>>>(
          geo_need_push_nums);
  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";
}

void GeoSgdCommunicator::Send(const std::string &var_name,
                              const framework::Scope &scope) {
  // when execute trainer startup program, recv parameter from pserver
  // training_scope & pserver_scope param will copy it
  if (var_name == "param_init") {
    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);
    }
  }
}

void GeoSgdCommunicator::Send(const std::vector<std::string> &sparse_var_names,
                              const std::vector<std::string> &sparse_var_tables,
                              const framework::Scope &scope) {
  // SparseIdsMap = std::unordered_map<std::string,std::unordered_set<int64_t>>
  std::shared_ptr<SparseIdsMap> ids_table = std::make_shared<SparseIdsMap>();
C
Chengmo 已提交
528
  auto before_run_send = GetCurrentUS();
529 530 531
  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 已提交
532 533 534 535 536 537
      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}));
538 539 540 541 542 543
    }
    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
544
    for (int j = 0; j < element_number; j++) {
C
Chengmo 已提交
545 546 547
      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]);
548 549 550 551 552
      VLOG(4) << "Sparse var " << sparse_var_tables[i] << " insert "
              << var_mutable_data[j];
    }
  }
  need_push_queue_->Push(ids_table);
C
Chengmo 已提交
553
  auto after_run_send = GetCurrentUS();
554
  VLOG(4) << "run send_op use time " << after_run_send - before_run_send;
555 556 557 558 559 560 561 562
}

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

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

565
    int wait_times = 0;
C
Chengmo 已提交
566
    while (ids_send_vec_.size() < geo_need_push_nums_) {
567 568
      VLOG(4) << "ids_send_vec_ Size: " << ids_send_vec_.size();
      if (need_push_queue_->Size() > 0) {
C
Chengmo 已提交
569
        wait_times = 0;
570 571
        ids_send_vec_.push_back(*(need_push_queue_->Pop()));
        VLOG(4) << "ids_send_vec_ pushed";
C
Chengmo 已提交
572
      } else if (need_push_queue_->Size() == 0) {
573
        VLOG(4) << "wait_times -> " << wait_times;
1
123malin 已提交
574
        if (wait_times >= env_flags_dict["send_wait_times"]) {
C
Chengmo 已提交
575 576 577 578 579
          break;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
        wait_times++;
        continue;
580 581 582 583 584
      }
    }

    if (ids_send_vec_.size() >= geo_need_push_nums_) {
      auto after_run_training = GetCurrentUS();
585
      VLOG(4) << "run Training use time "
586 587
              << after_run_training - before_run_training;
      before_run_training = GetCurrentUS();
588
      VLOG(4) << "Start send after get need_push_num";
589 590 591

      for (auto &iter : send_varname_to_ctx_) {
        auto &var_name = iter.first;
C
Chengmo 已提交
592 593 594 595 596
        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();
597
              VLOG(4) << "ids_send_vec_ size: " << ids_send_vec_.size();
C
Chengmo 已提交
598 599 600 601 602
              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();
603
              VLOG(3) << "run GEO-SGD var " << splited_var_name << " use time "
C
Chengmo 已提交
604 605 606 607
                      << after_run_geo - before_run_geo;
            };
            task_futures.emplace_back(
                send_threadpool_->enqueue(std::move(send_task)));
608
          }
C
Chengmo 已提交
609
        } else {
610 611 612 613 614 615 616 617 618 619 620 621
          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 已提交
622
        }
623
      }
C
Chengmo 已提交
624 625 626 627
      for (auto &task_f : task_futures) {
        task_f.wait();
      }
      ids_send_vec_.clear();
628 629 630 631 632
    }
  }
}

std::unordered_set<int64_t> GeoSgdCommunicator::SparseIdsMerge(
C
Chengmo 已提交
633 634
    const std::vector<SparseIdsMap> &ids_send_vec, const std::string &var_name,
    const std::string &splited_var_name) {
635
  // every batch has some sparse id, merge them into one unoredered_set
636
  VLOG(4) << "Sparse Ids merge var: " << var_name
C
Chengmo 已提交
637
          << " splited var: " << splited_var_name;
638
  auto before_run_ids_merge_ = GetCurrentUS();
C
Chengmo 已提交
639 640
  auto origin_var_name = DeltaVarToVar(var_name);
  auto splited_var_index = GetSplitedVarIndex(var_name, splited_var_name);
641 642
  std::unordered_set<int64_t> ids_set;
  for (auto ids_map : ids_send_vec) {
C
Chengmo 已提交
643
    for (auto id : ids_map[origin_var_name][splited_var_index]) {
644 645 646 647
      ids_set.insert(id);
    }
  }
  auto after_run_ids_merge_ = GetCurrentUS();
648
  VLOG(4) << "run SparseIdsMerge " << splited_var_name << " has nums "
C
Chengmo 已提交
649
          << ids_set.size() << " use time "
650 651 652 653
          << after_run_ids_merge_ - before_run_ids_merge_;
  return ids_set;
}

654 655
void GeoSgdCommunicator::SendUpdateDenseVars(
    const std::string &var_name, const std::string &splited_var_name) {
656 657
  // calc var_delata = (var_training - var_old)/trainer_nums
  // calc var_old += var_delta
C
Chengmo 已提交
658 659
  // var_name: param.delta
  auto origin_var_name = DeltaVarToVar(var_name);
660 661 662 663
  auto splited_var_index = GetSplitedVarIndex(var_name, splited_var_name);
  VLOG(4) << "Dense var: " << var_name
          << " 's splited var: " << splited_var_name
          << " splited var index: " << splited_var_index;
664
  auto before_run_send_dense = GetCurrentUS();
665
  auto cpu_ctx = paddle::platform::CPUDeviceContext();
666

C
Chengmo 已提交
667
  auto *var_x = training_scope_->FindVar(origin_var_name);
668 669
  auto var_x_tensor = var_x->Get<framework::LoDTensor>();

C
Chengmo 已提交
670
  auto *var_y = old_scope_->FindVar(origin_var_name);
671 672 673
  auto var_y_tensor = var_y->Get<framework::LoDTensor>();

  auto dims = var_x_tensor.dims();
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
  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;
    VLOG(4) << "Dense splited var: " << splited_var_name
            << " section: " << section << " dimension: " << dimension
            << " begin loc: " << begin_loc << " total_element "
            << total_element;
  }
691

692 693 694 695 696 697 698 699 700 701
  auto *var_x_data = var_x_tensor.mutable_data<float>(var_x_tensor.place()) +
                     begin_loc * dimension;
  VLOG(4) << "Dense splited var: " << splited_var_name << " var_x_data[0] "
          << 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;
  VLOG(4) << "Dense splited var: " << splited_var_name << " var_y_data[0] "
          << var_y_data[0] << " var_y_data[end] "
          << var_y_data[total_element - 1];
702 703

  // create delta var in delta scope
704 705 706 707 708
  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());
709

710 711 712
  VLOG(4) << "Dense splited var: " << splited_var_name << "var_z_data[0] "
          << var_z_data[0] << " var_z_data[end] "
          << var_z_data[total_element - 1];
713 714 715

  // calc sub = var_training - var_old
  auto blas = math::GetBlas<paddle::platform::CPUDeviceContext, float>(cpu_ctx);
716 717 718 719
  blas.VSUB(total_element, var_x_data, var_y_data, var_z_data);
  VLOG(4) << "Dense splited var: " << splited_var_name << " var_z_data[0] "
          << var_z_data[0] << " var_z_data[end] "
          << var_z_data[total_element - 1];
720 721 722

  // calc var_delta = sub / trainer_nums
  float trainer_param = 1.0 / static_cast<float>(trainer_nums_);
723
  blas.SCAL(total_element, trainer_param, var_z_data);
724 725

  // calc var_old += var_delta
726 727 728 729
  blas.VADD(total_element, var_y_data, var_z_data, var_y_data);
  VLOG(4) << "Dense splited var: " << splited_var_name << " var_y_data[0] "
          << var_y_data[0] << " var_y_data[end] "
          << var_y_data[total_element - 1];
730 731

  auto after_run_send_dense = GetCurrentUS();
732
  VLOG(4) << "run send update dense var " << var_name << " use time "
733
          << after_run_send_dense - before_run_send_dense;
C
Chengmo 已提交
734 735

  auto before_send_dense = GetCurrentUS();
736 737 738 739
  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;
740 741 742
}

void GeoSgdCommunicator::SendUpdateSparseVars(
C
Chengmo 已提交
743 744
    const std::string &var_name, const std::string &splited_var_name,
    const std::unordered_set<int64_t> &ids_table) {
745 746
  // calc var_delata = (var_training - var_old)/trainer_nums
  // calc var_old += var_delta
C
Chengmo 已提交
747 748
  // var_name: param.delta, splited_var_name: param.block0.delta
  // origin_var_name: param
749 750 751
  auto before_run_send_sparse = GetCurrentUS();

  auto ids_num = ids_table.size();
C
Chengmo 已提交
752 753 754 755
  VLOG(4) << "Sparse Ids nums is : " << ids_num;
  auto origin_var_name = DeltaVarToVar(var_name);

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

C
Chengmo 已提交
758
  auto *var_y = old_scope_.get()->FindVar(origin_var_name);
759 760 761 762 763 764 765 766
  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 已提交
767
  auto *var_z = delta_scope_->Var(splited_var_name);
768 769 770 771 772 773 774
  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 已提交
775 776 777 778

  auto cpu_ctx = paddle::platform::CPUDeviceContext();
  auto blas = math::GetBlas<paddle::platform::CPUDeviceContext, float>(cpu_ctx);
  float avg = 1 / static_cast<float>(trainer_nums_);
779
  for (size_t y = 0; y < new_rows.size(); y++) {
C
Chengmo 已提交
780 781 782 783 784 785 786
    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);
787
    blas.VSUB(row_numel, x_val, y_val, row_delta.data());
C
Chengmo 已提交
788 789 790
    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);
791
  }
C
Chengmo 已提交
792

793
  auto after_run_send_sparse = GetCurrentUS();
794
  VLOG(4) << "run send update sparse var " << splited_var_name << " use time "
795
          << after_run_send_sparse - before_run_send_sparse;
C
Chengmo 已提交
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810

  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();
811
  VLOG(4) << "send " << splited_var_name << " has nums " << new_rows.size()
C
Chengmo 已提交
812
          << " use time " << after_send_sparse - before_send_sparse;
813 814
}

815 816
void GeoSgdCommunicator::RecvUpdateDenseVars(
    const std::string &var_name, const std::string &splited_var_name) {
817 818
  // calc var_training += var_pserver - var_old
  // calc var_old = var_pserver
C
Chengmo 已提交
819 820 821 822
  // var_name: param.delta

  // step1: recv dense var from pserver
  auto origin_var_name = DeltaVarToVar(var_name);
823 824 825
  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 已提交
826 827

  auto before_run_recv = GetCurrentUS();
828 829 830 831
  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 已提交
832
  auto after_run_recv = GetCurrentUS();
833
  VLOG(4) << "recv var " << origin_splited_var_name << " use time "
C
Chengmo 已提交
834 835 836 837 838 839 840 841 842 843
          << 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>();

844
  auto *var_z = pserver_scope_.get()->FindVar(origin_splited_var_name);
C
Chengmo 已提交
845
  auto var_z_tensor = var_z->Get<framework::LoDTensor>();
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
  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;
    VLOG(4) << "Dense splited var: " << splited_var_name
            << " 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;
  VLOG(4) << "Dense splited var: " << splited_var_name << " var_x_data[0] "
          << 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;
  VLOG(4) << "Dense splited var: " << splited_var_name << " var_y_data[0] "
          << 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());
  VLOG(4) << "Dense splited var: " << splited_var_name << " var_z_data[0] "
          << 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());

  VLOG(4) << "Dense splited var: " << splited_var_name << " var_y_sub_data[0] "
          << var_y_sub_data[0] << " var_y_sub_data[end] "
          << var_y_sub_data[total_element - 1];
C
Chengmo 已提交
890 891

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

C
Chengmo 已提交
893
  // calc sub = pserver - old
894 895 896 897 898 899 900 901 902 903 904
  blas.VSUB(total_element, var_z_data, var_y_data, var_y_sub_data);
  VLOG(4) << "Dense splited var: " << splited_var_name << " var_y_sub_data[0] "
          << 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);
  VLOG(4) << "Dense splited var: " << splited_var_name << " var_x_data[0] "
          << var_x_data[0] << " var_x_data[end] "
          << var_x_data[total_element - 1];

C
Chengmo 已提交
905
  // calc old = pserver
906 907 908 909 910
  blas.VCOPY(total_element, var_z_data, var_y_data);
  VLOG(4) << "Dense splited var: " << splited_var_name << " var_y_data[0] "
          << var_y_data[0] << " var_y_data[end] "
          << var_y_data[total_element - 1];

C
Chengmo 已提交
911
  auto after_run_update = GetCurrentUS();
912
  VLOG(4) << "dense var update " << origin_splited_var_name << " use time "
C
Chengmo 已提交
913 914 915 916 917 918 919 920 921 922
          << after_run_update - before_run_update;
}

void GeoSgdCommunicator::RecvUpdateSparseVars(
    const std::string &var_name, const std::string &splited_var_name) {
  // step 1: recv splited var from pserver
  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);

923
  auto before_run_recv = GetCurrentUS();
C
Chengmo 已提交
924 925
  RpcRecv(origin_var_name, origin_splited_var_name, splited_var_index);
  auto after_run_recv = GetCurrentUS();
926
  VLOG(4) << "recv var " << origin_splited_var_name << " use time "
C
Chengmo 已提交
927
          << after_run_recv - before_run_recv;
928

C
Chengmo 已提交
929 930 931
  // step 2: update sparse var
  auto before_run_update = GetCurrentUS();
  auto *var_x = training_scope_->FindVar(origin_var_name);
932
  auto var_x_tensor = var_x->Get<framework::LoDTensor>();
C
Chengmo 已提交
933
  auto dims = var_x_tensor.dims();
934 935
  float *x_value = var_x_tensor.mutable_data<float>(var_x_tensor.place());

C
Chengmo 已提交
936
  auto *var_y = old_scope_->FindVar(origin_var_name);
937 938 939
  auto var_y_tensor = var_y->Get<framework::LoDTensor>();
  float *y_value = var_y_tensor.mutable_data<float>(var_y_tensor.place());

C
Chengmo 已提交
940 941 942 943 944 945 946 947 948 949
  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]);
950 951
  }

C
Chengmo 已提交
952 953 954 955 956 957
  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);
958
  for (size_t y = 0; y < new_rows.size(); y++) {
C
Chengmo 已提交
959 960 961 962 963 964 965 966
    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;

967
    blas.VSUB(row_numel, z_val, y_val, row_delta.data());
C
Chengmo 已提交
968 969 970 971 972
    blas.VADD(row_numel, row_delta.data(), x_val, x_val);
    blas.VCOPY(row_numel, z_val, y_val);
  }

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

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 已提交
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
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);
1019 1020 1021
  auto handle = rpc_client->AsyncSendVar(endpoint, cpu_ctx_send,
                                         *delta_scope_.get(), splited_var_name);
  handle->Wait();
C
Chengmo 已提交
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
}

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);
1034 1035 1036 1037
  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 已提交
1038 1039 1040 1041
}

void GeoSgdCommunicator::Recv() {}

1042 1043 1044 1045 1046 1047 1048
void GeoSgdCommunicator::InitImpl(const RpcCtxMap &send_varname_to_ctx,
                                  const RpcCtxMap &recv_varname_to_ctx,
                                  Scope *recv_scope) {}

void GeoSgdCommunicator::InitImpl(const paddle::framework::ProgramDesc &program,
                                  Scope *recv_scope) {}

Q
Qiao Longfei 已提交
1049 1050 1051
}  // namespace distributed
}  // namespace operators
}  // namespace paddle