fleet_wrapper.cc 56.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "paddle/fluid/framework/fleet/fleet_wrapper.h"
30 31

#include "glog/logging.h"
32
#include "paddle/fluid/framework/op_registry.h"
33 34 35 36 37 38

namespace paddle {
namespace framework {

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

#ifdef PADDLE_WITH_PSLIB
std::shared_ptr<paddle::distributed::PSlib> FleetWrapper::pslib_ptr_ = NULL;
#endif
44

45 46 47 48 49 50 51 52
void FleetWrapper::SetClient2ClientConfig(int request_timeout_ms,
                                          int connect_timeout_ms,
                                          int max_retry) {
  client2client_request_timeout_ms_ = request_timeout_ms;
  client2client_connect_timeout_ms_ = connect_timeout_ms;
  client2client_max_retry_ = max_retry;
}

53 54 55
void FleetWrapper::InitServer(const std::string& dist_desc, int index) {
#ifdef PADDLE_WITH_PSLIB
  if (!is_initialized_) {
D
dongdaxiang 已提交
56
    VLOG(3) << "Going to init server";
57 58 59 60 61
    pslib_ptr_ = std::shared_ptr<paddle::distributed::PSlib>(
        new paddle::distributed::PSlib());
    pslib_ptr_->init_server(dist_desc, index);
    is_initialized_ = true;
  } else {
D
dongdaxiang 已提交
62
    VLOG(3) << "Server can be initialized only once";
63 64 65 66 67 68 69 70 71
  }
#endif
}

void FleetWrapper::InitWorker(const std::string& dist_desc,
                              const std::vector<uint64_t>& host_sign_list,
                              int node_num, int index) {
#ifdef PADDLE_WITH_PSLIB
  if (!is_initialized_) {
D
dongdaxiang 已提交
72
    VLOG(3) << "Going to init worker";
73 74 75 76 77 78 79
    pslib_ptr_ = std::shared_ptr<paddle::distributed::PSlib>(
        new paddle::distributed::PSlib());
    pslib_ptr_->init_worker(dist_desc,
                            const_cast<uint64_t*>(host_sign_list.data()),
                            node_num, index);
    is_initialized_ = true;
  } else {
D
dongdaxiang 已提交
80
    VLOG(3) << "Worker can be initialized only once";
81 82 83 84 85 86
  }
#endif
}

void FleetWrapper::StopServer() {
#ifdef PADDLE_WITH_PSLIB
D
dongdaxiang 已提交
87
  VLOG(3) << "Going to stop server";
88 89 90 91
  pslib_ptr_->stop_server();
#endif
}

92 93 94 95 96 97 98
void FleetWrapper::FinalizeWorker() {
#ifdef PADDLE_WITH_PSLIB
  VLOG(3) << "Going to finalize worker";
  pslib_ptr_->finalize_worker();
#endif
}

99 100
uint64_t FleetWrapper::RunServer() {
#ifdef PADDLE_WITH_PSLIB
D
dongdaxiang 已提交
101
  VLOG(3) << "Going to run server";
102 103 104 105 106 107
  return pslib_ptr_->run_server();
#else
  return 0;
#endif
}

108 109 110 111 112 113 114 115 116 117
uint64_t FleetWrapper::RunServer(const std::string& ip, uint32_t port) {
#ifdef PADDLE_WITH_PSLIB
  VLOG(3) << "Going to run server with ip " << ip << " port " << port;
  auto ret = pslib_ptr_->run_server(ip, port);
  return ret;
#else
  return 0;
#endif
}

118 119 120
void FleetWrapper::GatherServers(const std::vector<uint64_t>& host_sign_list,
                                 int node_num) {
#ifdef PADDLE_WITH_PSLIB
D
dongdaxiang 已提交
121
  VLOG(3) << "Going to gather server ips";
122 123 124 125 126
  pslib_ptr_->gather_servers(const_cast<uint64_t*>(host_sign_list.data()),
                             node_num);
#endif
}

D
dongdaxiang 已提交
127
void FleetWrapper::GatherClients(const std::vector<uint64_t>& host_sign_list) {
X
xjqbest 已提交
128 129 130
#ifdef PADDLE_WITH_PSLIB
  VLOG(3) << "Going to gather client ips";
  size_t len = host_sign_list.size();
D
dongdaxiang 已提交
131
  pslib_ptr_->gather_clients(const_cast<uint64_t*>(host_sign_list.data()), len);
X
xjqbest 已提交
132 133 134 135 136 137 138 139 140 141 142 143 144 145
#endif
}

std::vector<uint64_t> FleetWrapper::GetClientsInfo() {
#ifdef PADDLE_WITH_PSLIB
  VLOG(3) << "Going to get client info";
  return pslib_ptr_->get_client_info();
#endif
  return std::vector<uint64_t>();
}

void FleetWrapper::CreateClient2ClientConnection() {
#ifdef PADDLE_WITH_PSLIB
  VLOG(3) << "Going to create client2client connection";
146 147 148
  pslib_ptr_->create_client2client_connection(client2client_request_timeout_ms_,
                                              client2client_connect_timeout_ms_,
                                              client2client_max_retry_);
X
xjqbest 已提交
149 150 151
#endif
}

T
Thunderbrook 已提交
152 153 154 155 156 157 158 159 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 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
#ifdef PADDLE_WITH_PSLIB
void FleetWrapper::HeterPullSparseVars(
    int workerid, std::shared_ptr<HeterTask> task, const uint64_t table_id,
    const std::vector<std::string>& var_names, int fea_value_dim,
    const std::vector<std::string>& var_emb_names) {
  std::vector<::std::future<int32_t>> pull_sparse_status;
  pull_sparse_status.resize(0);
  auto& scope = *(task->scope_);
  auto& fea_keys = (task->features_)[table_id];
  auto& fea_values = (task->feature_values_)[table_id];
  fea_keys.clear();
  for (size_t var_index = 0; var_index < var_names.size(); ++var_index) {
    const std::string& name = var_names[var_index];
    Variable* var = scope.FindVar(name);
    if (var == nullptr) {
      continue;
    }
    LoDTensor* tensor = var->GetMutable<LoDTensor>();
    CHECK(tensor != nullptr) << "tensor of var " << name << " is null";
    int64_t* ids = tensor->data<int64_t>();
    size_t len = tensor->numel();

    // skip slots which do not have embedding
    const std::string& emb_name = var_emb_names[var_index];
    Variable* emb_var = scope.FindVar(emb_name);
    if (emb_var == nullptr) {
      continue;
    }

    for (auto i = 0u; i < len; ++i) {
      if (ids[i] == 0u) {
        continue;
      }
      fea_keys.push_back(static_cast<uint64_t>(ids[i]));
    }
  }
  fea_values.resize(fea_keys.size() + 1);
  for (auto& t : fea_values) {
    t.resize(fea_value_dim);
  }
  std::vector<float*> pull_result_ptr;
  for (auto& t : fea_values) {
    pull_result_ptr.push_back(t.data());
  }
  auto status = pslib_ptr_->_worker_ptr->heter_pull_sparse(
      workerid, pull_result_ptr.data(), table_id, fea_keys.data(),
      fea_keys.size(), task->taskid_);
  pull_sparse_status.push_back(std::move(status));
  for (auto& t : pull_sparse_status) {
    t.wait();
    auto status = t.get();
    if (status != 0) {
      LOG(ERROR) << "fleet pull sparse failed, status[" << status << "]";
      sleep(sleep_seconds_before_fail_exit_);
      exit(-1);
    }
  }
}

void FleetWrapper::HeterPushSparseVars(
T
Thunderbrook 已提交
212 213
    std::shared_ptr<HeterTask> task, const Scope& scope,
    const uint64_t table_id, const std::vector<std::string>& sparse_key_names,
T
Thunderbrook 已提交
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
    const std::vector<std::string>& sparse_grad_names, const int emb_dim,
    std::vector<::std::future<int32_t>>* push_sparse_status, const bool use_cvm,
    const bool dump_slot, const bool no_cvm) {
  int batch_size = task->cur_batch_;
  int offset = 2;
  int slot_offset = 0;
  int grad_dim = emb_dim;
  int show_index = 0;
  int click_index = 1;
  auto& fea_keys = (task->features_)[table_id];
  auto& fea_labels = (task->feature_labels_)[table_id];
  auto& push_values = (task->feature_grads_)[table_id];
  auto& sparse_push_keys = (task->sparse_push_keys_)[table_id];

  if (use_cvm) {
    offset = 0;
    grad_dim = emb_dim - 2;
  }
  if (no_cvm) {
    offset = 0;
    grad_dim = emb_dim;
  }
  if (dump_slot) {
    slot_offset = 1;
    show_index = 1;
    click_index = 2;
  }
  CHECK_GE(grad_dim, 0);

  sparse_push_keys.clear();
  sparse_push_keys.reserve(fea_keys.size() + 1);
  push_values.resize(fea_keys.size() + 1);
  for (auto& t : push_values) {
    t.resize(emb_dim + offset + slot_offset);
  }
  uint64_t fea_idx = 0u;
  for (size_t i = 0;
       i < sparse_key_names.size() && i < sparse_grad_names.size(); ++i) {
    Variable* var = scope.FindVar(sparse_key_names[i]);
    if (var == nullptr) {
      continue;
    }
    LoDTensor* tensor = var->GetMutable<LoDTensor>();
    if (tensor == nullptr) {
      LOG(ERROR) << "tensor of var[" << sparse_key_names[i] << "] is null";
      exit(-1);
    }
    size_t len = tensor->numel();
    int64_t* ids = tensor->data<int64_t>();
    int slot = 0;
    if (dump_slot) {
265
      slot = std::stoi(sparse_key_names[i]);
T
Thunderbrook 已提交
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
    }
    Variable* g_var = scope.FindVar(sparse_grad_names[i]);
    if (g_var == nullptr) {
      continue;
    }
    LoDTensor* g_tensor = g_var->GetMutable<LoDTensor>();
    if (g_tensor == nullptr) {
      LOG(ERROR) << "tensor of var[" << sparse_key_names[i] << "] is null";
      exit(-1);
    }
    float* g = g_tensor->data<float>();

    if (scale_sparse_gradient_with_batch_size_ && grad_dim > 0) {
      int dim = emb_dim + offset;
      Eigen::Map<
          Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>
          g_mat(g, g_tensor->numel() / dim, dim);
      g_mat.rightCols(grad_dim) *= batch_size;
    }
    for (auto id_idx = 0u; id_idx < len; ++id_idx) {
      if (ids[id_idx] == 0) {
        g += emb_dim;
        continue;
      }
      sparse_push_keys.push_back(ids[id_idx]);
      CHECK(fea_idx < push_values.size());

      if (use_cvm || no_cvm) {
        memcpy(push_values[fea_idx].data() + offset + slot_offset, g,
               sizeof(float) * emb_dim);
      } else {
        CHECK(fea_idx < fea_labels.size());
        memcpy(push_values[fea_idx].data() + offset + slot_offset, g,
               sizeof(float) * emb_dim);
        push_values[fea_idx][show_index] = 1.0f;
        push_values[fea_idx][click_index] =
            static_cast<float>(fea_labels[fea_idx]);
      }
      if (dump_slot) {
        push_values[fea_idx][0] = static_cast<float>(slot);
      }
      g += emb_dim;
      fea_idx++;
    }
  }
  // slots whose embedding has been stop gradient or
  // not involved in forward-backward
  uint64_t no_grad_fea_num = 0u;
  for (size_t i = sparse_grad_names.size(); i < sparse_key_names.size(); ++i) {
    Variable* var = scope.FindVar(sparse_key_names[i]);
    if (var == nullptr) {
      continue;
    }
    LoDTensor* tensor = var->GetMutable<LoDTensor>();
    if (tensor == nullptr) {
      LOG(ERROR) << "tensor of var[" << sparse_key_names[i] << "] is null";
      exit(-1);
    }
    size_t len = tensor->numel();
    int64_t* ids = tensor->data<int64_t>();
    for (auto id_idx = 0u; id_idx < len; ++id_idx) {
      if (ids[id_idx] == 0) {
        continue;
      }
      ++no_grad_fea_num;
    }
  }
  CHECK(fea_idx + no_grad_fea_num == fea_keys.size())
      << "fea_idx: " << fea_idx << " no_grad_fea_num: " << no_grad_fea_num
      << " features size: " << fea_keys.size();
  CHECK(fea_idx == sparse_push_keys.size());
  if (fea_idx == 0) {
    return;
  }
  std::vector<float*> push_g_vec;
  for (auto i = 0u; i < sparse_push_keys.size(); ++i) {
    push_g_vec.push_back(push_values[i].data());
  }
  auto status = pslib_ptr_->_worker_ptr->push_sparse(
      table_id, sparse_push_keys.data(), (const float**)push_g_vec.data(),
      sparse_push_keys.size());
  push_sparse_status->push_back(std::move(status));
}
#endif

int FleetWrapper::RegisterHeterCallback(HeterCallBackFunc handler) {
#ifdef PADDLE_WITH_PSLIB
  VLOG(3) << "calling FleetWrapper::RegisterHeterCallback";
  VLOG(3) << "pslib_ptr_=" << pslib_ptr_;
  VLOG(3) << "_worker_ptr=" << pslib_ptr_->_worker_ptr;
  return pslib_ptr_->_worker_ptr->registe_heter_callback(handler);
T
Thunderbrook 已提交
357

T
Thunderbrook 已提交
358 359 360 361 362 363 364
#else
  VLOG(0) << "FleetWrapper::RegisterHeterCallback"
          << " does nothing when no pslib";
#endif
  return 0;
}

365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 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 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 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
void FleetWrapper::PullSparseToLocal(const uint64_t table_id,
                                     int fea_value_dim) {
#ifdef PADDLE_WITH_PSLIB
  size_t fea_keys_size = local_tables_.size();
  if (fea_keys_size == 0) {
    return;
  }
  local_table_shard_num_ = fea_keys_size;
  platform::Timer timeline;
  std::vector<std::thread> threads(fea_keys_size);
  auto ptl_func = [this, &table_id](int i) {
    size_t key_size = this->local_tables_[i].size();
    std::vector<uint64_t> keys;
    keys.reserve(key_size);
    std::vector<float*> pull_result_ptr;
    pull_result_ptr.reserve(key_size);

    for (auto& kv : this->local_tables_[i]) {
      keys.emplace_back(kv.first);
      pull_result_ptr.emplace_back(kv.second.data());
    }
    auto tt = pslib_ptr_->_worker_ptr->pull_sparse(
        pull_result_ptr.data(), table_id, keys.data(), key_size);
    tt.wait();
    auto status = tt.get();
    if (status != 0) {
      LOG(ERROR) << "fleet pull sparse failed, status[" << status << "]";
      sleep(sleep_seconds_before_fail_exit_);
      exit(-1);
    } else {
      VLOG(3) << "FleetWrapper Pull sparse to local done with table size: "
              << pull_result_ptr.size();
    }
  };
  timeline.Start();
  for (size_t i = 0; i < threads.size(); i++) {
    threads[i] = std::thread(ptl_func, i);
  }
  for (std::thread& t : threads) {
    t.join();
  }
  local_pull_pool_.reset(new ::ThreadPool(pull_local_thread_num_));
  timeline.Pause();
#endif
}

void FleetWrapper::PullSparseVarsFromLocal(
    const Scope& scope, const uint64_t table_id,
    const std::vector<std::string>& var_names, std::vector<uint64_t>* fea_keys,
    std::vector<std::vector<float>>* fea_values, int fea_value_dim) {
#ifdef PADDLE_WITH_PSLIB
  fea_keys->clear();
  fea_keys->resize(0);
  fea_keys->reserve(MAX_FEASIGN_NUM);
  for (auto name : var_names) {
    Variable* var = scope.FindVar(name);
    if (var == nullptr) {
      continue;
    }
    LoDTensor* tensor = var->GetMutable<LoDTensor>();
    CHECK(tensor != nullptr) << "tensor of var " << name << " is null";
    int64_t* ids = tensor->data<int64_t>();
    size_t len = tensor->numel();
    for (auto i = 0u; i < len; ++i) {
      if (ids[i] == 0u) {
        continue;
      }
      fea_keys->push_back(static_cast<uint64_t>(ids[i]));
    }
  }
  fea_values->resize(fea_keys->size() + 1);
  for (auto& t : *fea_values) {
    t.resize(fea_value_dim);
  }
  size_t key_length = fea_keys->size();
  int local_step = key_length / pull_local_thread_num_;
  std::vector<std::future<void>> task_futures;
  task_futures.reserve(key_length / local_step + 1);
  for (size_t i = 0; i < key_length; i += local_step) {
    size_t end = i + local_step < key_length ? i + local_step : key_length;
    auto pull_local_task = [this, i, end, &fea_values, &fea_keys,
                            &fea_value_dim] {
      for (size_t j = i; j < end; j++) {
        std::memcpy((*fea_values)[j].data(),
                    local_tables_[(*fea_keys)[j] % local_table_shard_num_]
                                 [(*fea_keys)[j]]
                                     .data(),
                    fea_value_dim * sizeof(float));
      }
    };
    task_futures.emplace_back(
        local_pull_pool_->enqueue(std::move(pull_local_task)));
  }
  for (auto& tf : task_futures) {
    tf.wait();
  }
#endif
}

void FleetWrapper::ClearLocalTable() {
#ifdef PADDLE_WITH_PSLIB
  for (auto& t : local_tables_) {
    t.clear();
  }
#endif
}

std::future<int32_t> FleetWrapper::PullSparseVarsAsync(
    const Scope& scope, const uint64_t table_id,
    const std::vector<std::string>& var_names, std::vector<uint64_t>* fea_keys,
    std::vector<std::vector<float>>* fea_values, int fea_value_dim) {
#ifdef PADDLE_WITH_PSLIB
  fea_keys->clear();
  fea_keys->resize(0);
  fea_keys->reserve(MAX_FEASIGN_NUM);
  for (auto name : var_names) {
    Variable* var = scope.FindVar(name);
    if (var == nullptr) {
      continue;
    }
    LoDTensor* tensor = var->GetMutable<LoDTensor>();
    CHECK(tensor != nullptr) << "tensor of var " << name << " is null";
    int64_t* ids = tensor->data<int64_t>();
    size_t len = tensor->numel();
    for (auto i = 0u; i < len; ++i) {
      if (ids[i] == 0u) {
        continue;
      }
      fea_keys->push_back(static_cast<uint64_t>(ids[i]));
    }
  }
  fea_values->resize(fea_keys->size() + 1);
  for (auto& t : *fea_values) {
    t.resize(fea_value_dim);
  }
  std::vector<float*> pull_result_ptr;
  for (auto& t : *fea_values) {
    pull_result_ptr.push_back(t.data());
  }
  return pslib_ptr_->_worker_ptr->pull_sparse(
      pull_result_ptr.data(), table_id, fea_keys->data(), fea_keys->size());
#endif
  return std::future<int32_t>();
}

510 511 512
void FleetWrapper::PullSparseVarsSync(
    const Scope& scope, const uint64_t table_id,
    const std::vector<std::string>& var_names, std::vector<uint64_t>* fea_keys,
513 514
    std::vector<std::vector<float>>* fea_values, int fea_value_dim,
    const std::vector<std::string>& var_emb_names) {
515 516 517 518 519 520
#ifdef PADDLE_WITH_PSLIB
  std::vector<::std::future<int32_t>> pull_sparse_status;
  pull_sparse_status.resize(0);
  fea_keys->clear();
  fea_keys->resize(0);
  fea_keys->reserve(MAX_FEASIGN_NUM);
521 522
  for (size_t var_index = 0; var_index < var_names.size(); ++var_index) {
    const std::string& name = var_names[var_index];
523
    Variable* var = scope.FindVar(name);
524 525 526
    if (var == nullptr) {
      continue;
    }
527
    LoDTensor* tensor = var->GetMutable<LoDTensor>();
528
    CHECK(tensor != nullptr) << "tensor of var " << name << " is null";
529
    int64_t* ids = tensor->data<int64_t>();
530
    size_t len = tensor->numel();
531 532 533 534 535 536 537 538

    // skip slots which do not have embedding
    const std::string& emb_name = var_emb_names[var_index];
    Variable* emb_var = scope.FindVar(emb_name);
    if (emb_var == nullptr) {
      continue;
    }

539 540 541 542 543 544 545
    for (auto i = 0u; i < len; ++i) {
      if (ids[i] == 0u) {
        continue;
      }
      fea_keys->push_back(static_cast<uint64_t>(ids[i]));
    }
  }
D
dongdaxiang 已提交
546 547 548 549 550 551 552 553
  fea_values->resize(fea_keys->size() + 1);
  for (auto& t : *fea_values) {
    t.resize(fea_value_dim);
  }
  std::vector<float*> pull_result_ptr;
  for (auto& t : *fea_values) {
    pull_result_ptr.push_back(t.data());
  }
T
Thunderbrook 已提交
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583

  int32_t cnt = 0;
  while (true) {
    pull_sparse_status.clear();
    auto status = pslib_ptr_->_worker_ptr->pull_sparse(
        pull_result_ptr.data(), table_id, fea_keys->data(), fea_keys->size());
    pull_sparse_status.push_back(std::move(status));
    bool flag = true;
    for (auto& t : pull_sparse_status) {
      t.wait();
      int32_t status = -1;
      try {
        status = t.get();
      } catch (const std::future_error& e) {
        VLOG(0) << "Caught a future_error with code" << e.code()
                << ", Message:" << e.what();
      }
      if (status != 0) {
        VLOG(0) << "fleet pull sparse failed, status[" << status << "]";
        sleep(sleep_seconds_before_fail_exit_);
        flag = false;
        cnt++;
      }
      if (cnt > 3) {
        VLOG(0) << "fleet pull sparse failed, retry 3 times";
        exit(-1);
      }
    }
    if (flag) {
      break;
584 585 586 587 588
    }
  }
#endif
}

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

650 651 652
void FleetWrapper::PullDenseVarsAsync(
    const Scope& scope, const uint64_t tid,
    const std::vector<std::string>& var_names,
T
Thunderbrook 已提交
653
    std::vector<::std::future<int32_t>>* pull_dense_status, bool in_cpu) {
654
#ifdef PADDLE_WITH_PSLIB
X
xujiaqi01 已提交
655 656
  auto& regions = _regions[tid];
  regions.clear();
657 658
  regions.resize(var_names.size());
  for (auto i = 0u; i < var_names.size(); ++i) {
T
Thunderbrook 已提交
659 660 661 662 663
    std::string varname = var_names[i];
    if (!in_cpu) {
      varname = var_names[i] + "pin";
    }
    Variable* var = scope.FindVar(varname);
664 665 666
    LoDTensor* tensor = var->GetMutable<LoDTensor>();
    float* w = tensor->data<float>();
    paddle::ps::Region reg(w, tensor->numel());
667
    regions[i] = std::move(reg);
668 669 670 671 672 673 674 675 676 677 678
  }
  auto status =
      pslib_ptr_->_worker_ptr->pull_dense(regions.data(), regions.size(), tid);
  pull_dense_status->push_back(std::move(status));
#endif
}

void FleetWrapper::PullDenseVarsSync(
    const Scope& scope, const uint64_t tid,
    const std::vector<std::string>& var_names) {
#ifdef PADDLE_WITH_PSLIB
X
xujiaqi01 已提交
679 680
  auto& regions = _regions[tid];
  regions.clear();
681 682 683 684 685 686 687 688
  regions.reserve(var_names.size());
  for (auto& t : var_names) {
    Variable* var = scope.FindVar(t);
    LoDTensor* tensor = var->GetMutable<LoDTensor>();
    float* w = tensor->data<float>();
    paddle::ps::Region reg(w, tensor->numel());
    regions.emplace_back(std::move(reg));
  }
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
  int32_t status = -1;
  int32_t cnt = 0;
  while (true) {
    auto tt = pslib_ptr_->_worker_ptr->pull_dense(regions.data(),
                                                  regions.size(), tid);
    bool flag = true;

    tt.wait();

    try {
      status = tt.get();
    } catch (const std::future_error& e) {
      VLOG(0) << "Caught a future_error with code" << e.code()
              << ", Message:" << e.what();
    }
    if (status != 0) {
      VLOG(0) << "fleet pull dense sync failed, status[" << status << "]";
      sleep(sleep_seconds_before_fail_exit_);
      flag = false;
      cnt++;
    }
    if (cnt > 3) {
      VLOG(0) << "fleet pull dense sync failed, retry 3 times";
      exit(-1);
    }

    if (flag) {
      break;
    }
  }
719 720 721
#endif
}

722
void FleetWrapper::PushDenseParamSync(
D
dongdaxiang 已提交
723
    const Scope& scope, const uint64_t table_id,
724 725 726 727 728 729
    const std::vector<std::string>& var_names) {
#ifdef PADDLE_WITH_PSLIB
  auto place = platform::CPUPlace();
  std::vector<paddle::ps::Region> regions;
  for (auto& t : var_names) {
    Variable* var = scope.FindVar(t);
X
xjqbest 已提交
730
    CHECK(var != nullptr) << "var[" << t << "] not found";
731
    LoDTensor* tensor = var->GetMutable<LoDTensor>();
732
    float* g = tensor->mutable_data<float>(place);
733 734 735
    paddle::ps::Region reg(g, tensor->numel());
    regions.emplace_back(std::move(reg));
  }
736 737 738 739 740
  auto push_status = pslib_ptr_->_worker_ptr->push_dense_param(
      regions.data(), regions.size(), table_id);
  push_status.wait();
  auto status = push_status.get();
  CHECK(status == 0) << "push dense param failed, status[" << status << "]";
741 742 743
#endif
}

D
dongdaxiang 已提交
744 745 746 747
void FleetWrapper::PushDenseVarsSync(
    Scope* scope, const uint64_t table_id,
    const std::vector<std::string>& var_names) {}

748 749
#if (defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)) && \
    (defined PADDLE_WITH_PSLIB)
T
Thunderbrook 已提交
750 751 752 753 754
void FleetWrapper::PushDenseVarsAsync(
    const Scope& scope, const uint64_t table_id,
    const std::vector<std::string>& var_names,
    std::vector<::std::future<int32_t>>* push_sparse_status,
    float scale_datanorm, int batch_size, const paddle::platform::Place& place,
755
    gpuStream_t stream, gpuEvent_t event) {
T
Thunderbrook 已提交
756 757 758 759 760 761 762 763 764 765 766 767 768 769
  std::vector<paddle::ps::Region> regions;
  for (auto& t : var_names) {
    Variable* var = scope.FindVar(t);
    LoDTensor* tensor = var->GetMutable<LoDTensor>();
    int count = tensor->numel();
    float* g_data = tensor->data<float>();

    Variable* pin_var = scope.FindVar(t + "pin");
    LoDTensor* pin_tensor = pin_var->GetMutable<LoDTensor>();
    float* pin_g = pin_tensor->mutable_data<float>(tensor->dims(),
                                                   platform::CUDAPinnedPlace());
    memory::Copy(platform::CUDAPinnedPlace(), pin_g,
                 BOOST_GET_CONST(platform::CUDAPlace, place), g_data,
                 sizeof(float) * count, stream);
770
#ifdef PADDLE_WITH_HIP
771
    PADDLE_ENFORCE_GPU_SUCCESS(hipEventRecord(event, stream));
772 773
    hipEventSynchronize(event);
#else
774
    PADDLE_ENFORCE_GPU_SUCCESS(cudaEventRecord(event, stream));
T
Thunderbrook 已提交
775
    cudaEventSynchronize(event);
776
#endif
T
Thunderbrook 已提交
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802

    float* g = pin_g;
    if (scale_datanorm >= 0) {
      if (t.find(".batch_size@GRAD") != std::string::npos ||
          t.find(".batch_sum@GRAD") != std::string::npos) {
        Eigen::Map<Eigen::MatrixXf> mat(g, 1, count);
        float scale = 1.0 / batch_size;
        mat *= scale;
      } else if (t.find(".batch_square_sum@GRAD") != std::string::npos) {
        VLOG(3) << "epsilon: " << scale_datanorm;
        for (int i = 0; i < count; ++i) {
          g[i] = (g[i] - batch_size * scale_datanorm) / batch_size +
                 batch_size * scale_datanorm;
        }
      }
    }
    paddle::ps::Region reg(g, count);
    regions.emplace_back(std::move(reg));
  }

  auto status = pslib_ptr_->_worker_ptr->push_dense(regions.data(),
                                                    regions.size(), table_id);
  if (push_sparse_status) {
    push_sparse_status->push_back(std::move(status));
  }
}
T
Thunderbrook 已提交
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
#endif

#ifdef PADDLE_WITH_XPU
void FleetWrapper::PushDenseVarsAsync(
    const Scope& scope, const uint64_t table_id,
    const std::vector<std::string>& var_names,
    std::vector<::std::future<int32_t>>* push_sparse_status,
    float scale_datanorm, int batch_size,
    const paddle::platform::Place& place) {
#ifdef PADDLE_WITH_PSLIB
  std::vector<paddle::ps::Region> regions;
  for (auto& t : var_names) {
    Variable* var = scope.FindVar(t);
    LoDTensor* tensor = var->GetMutable<LoDTensor>();
    int count = tensor->numel();
    float* g_data = tensor->data<float>();

    Variable* pin_var = scope.FindVar(t + "pin");
    LoDTensor* pin_tensor = pin_var->GetMutable<LoDTensor>();
    float* pin_g =
        pin_tensor->mutable_data<float>(tensor->dims(), platform::CPUPlace());
    memory::Copy(platform::CPUPlace(), pin_g,
                 BOOST_GET_CONST(platform::XPUPlace, place), g_data,
                 sizeof(float) * count);

    float* g = pin_g;
    if (scale_datanorm >= 0) {
      if (t.find(".batch_size@GRAD") != std::string::npos ||
          t.find(".batch_sum@GRAD") != std::string::npos) {
        Eigen::Map<Eigen::MatrixXf> mat(g, 1, count);
        float scale = 1.0 / batch_size;
        mat *= scale;
      } else if (t.find(".batch_square_sum@GRAD") != std::string::npos) {
        VLOG(3) << "epsilon: " << scale_datanorm;
        for (int i = 0; i < count; ++i) {
          g[i] = (g[i] - batch_size * scale_datanorm) / batch_size +
                 batch_size * scale_datanorm;
        }
      }
    }
    paddle::ps::Region reg(g, count);
    regions.emplace_back(std::move(reg));
  }
T
Thunderbrook 已提交
846

T
Thunderbrook 已提交
847 848 849 850 851 852 853
  auto status = pslib_ptr_->_worker_ptr->push_dense(regions.data(),
                                                    regions.size(), table_id);
  if (push_sparse_status) {
    push_sparse_status->push_back(std::move(status));
  }
#endif
}
T
Thunderbrook 已提交
854
#endif
855 856 857
void FleetWrapper::PushDenseVarsAsync(
    const Scope& scope, const uint64_t table_id,
    const std::vector<std::string>& var_names,
858 859
    std::vector<::std::future<int32_t>>* push_sparse_status,
    float scale_datanorm, int batch_size) {
860 861 862 863 864 865 866
#ifdef PADDLE_WITH_PSLIB
  std::vector<paddle::ps::Region> regions;
  for (auto& t : var_names) {
    Variable* var = scope.FindVar(t);
    LoDTensor* tensor = var->GetMutable<LoDTensor>();
    int count = tensor->numel();
    float* g = tensor->data<float>();
867 868 869 870 871 872 873 874 875 876 877 878 879 880
    if (scale_datanorm >= 0) {
      if (t.find(".batch_size@GRAD") != std::string::npos ||
          t.find(".batch_sum@GRAD") != std::string::npos) {
        Eigen::Map<Eigen::MatrixXf> mat(g, 1, count);
        float scale = 1.0 / batch_size;
        mat *= scale;
      } else if (t.find(".batch_square_sum@GRAD") != std::string::npos) {
        VLOG(3) << "epsilon: " << scale_datanorm;
        for (int i = 0; i < count; ++i) {
          g[i] = (g[i] - batch_size * scale_datanorm) / batch_size +
                 batch_size * scale_datanorm;
        }
      }
    }
881 882 883
    paddle::ps::Region reg(g, count);
    regions.emplace_back(std::move(reg));
  }
884

885 886
  auto status = pslib_ptr_->_worker_ptr->push_dense(regions.data(),
                                                    regions.size(), table_id);
887 888 889
  if (push_sparse_status) {
    push_sparse_status->push_back(std::move(status));
  }
890 891 892 893 894 895 896 897 898
#endif
}

void FleetWrapper::PushSparseVarsWithLabelAsync(
    const Scope& scope, const uint64_t table_id,
    const std::vector<uint64_t>& fea_keys, const std::vector<float>& fea_labels,
    const std::vector<std::string>& sparse_key_names,
    const std::vector<std::string>& sparse_grad_names, const int emb_dim,
    std::vector<std::vector<float>>* push_values,
899
    std::vector<::std::future<int32_t>>* push_sparse_status,
900
    const int batch_size, const bool use_cvm, const bool dump_slot,
901 902
    std::vector<uint64_t>* sparse_push_keys, const bool no_cvm,
    const bool scale_sparse_gradient_with_batch_size) {
903 904
#ifdef PADDLE_WITH_PSLIB
  int offset = 2;
T
Thunderbrook 已提交
905
  int slot_offset = 0;
906
  int grad_dim = emb_dim;
T
Thunderbrook 已提交
907 908
  int show_index = 0;
  int click_index = 1;
909 910 911 912
  if (use_cvm) {
    offset = 0;
    grad_dim = emb_dim - 2;
  }
913 914 915 916
  if (no_cvm) {
    offset = 0;
    grad_dim = emb_dim;
  }
T
Thunderbrook 已提交
917 918 919 920 921
  if (dump_slot) {
    slot_offset = 1;
    show_index = 1;
    click_index = 2;
  }
922
  CHECK_GE(grad_dim, 0);
923

924 925
  sparse_push_keys->clear();
  sparse_push_keys->reserve(fea_keys.size() + 1);
926 927
  push_values->resize(fea_keys.size() + 1);
  for (auto& t : *push_values) {
T
Thunderbrook 已提交
928
    t.resize(emb_dim + offset + slot_offset);
929
  }
930
  uint64_t fea_idx = 0u;
931 932
  for (size_t i = 0;
       i < sparse_key_names.size() && i < sparse_grad_names.size(); ++i) {
933
    Variable* var = scope.FindVar(sparse_key_names[i]);
934 935 936
    if (var == nullptr) {
      continue;
    }
937
    LoDTensor* tensor = var->GetMutable<LoDTensor>();
938 939
    if (tensor == nullptr) {
      LOG(ERROR) << "tensor of var[" << sparse_key_names[i] << "] is null";
940 941
      exit(-1);
    }
942
    size_t len = tensor->numel();
943
    int64_t* ids = tensor->data<int64_t>();
T
Thunderbrook 已提交
944 945
    int slot = 0;
    if (dump_slot) {
946
      try {
947 948
        slot = std::stoi(sparse_key_names[i]);
      } catch (std::invalid_argument const& e) {
949 950 951 952
        PADDLE_THROW(platform::errors::PreconditionNotMet(
            "sparse var's name: %s, doesn't support non-integer type name when "
            "dump_slot=True",
            sparse_key_names[i]));
953 954 955 956 957
      } catch (std::out_of_range const& e) {
        PADDLE_THROW(platform::errors::PreconditionNotMet(
            "sparse var's name: %s, integer type name out of range when "
            "dump_slot=True",
            sparse_key_names[i]));
958
      }
T
Thunderbrook 已提交
959
    }
960
    Variable* g_var = scope.FindVar(sparse_grad_names[i]);
961 962 963
    if (g_var == nullptr) {
      continue;
    }
964 965 966 967
    LoDTensor* g_tensor = g_var->GetMutable<LoDTensor>();
    if (g_tensor == nullptr) {
      LOG(ERROR) << "tensor of var[" << sparse_key_names[i] << "] is null";
      exit(-1);
968
    }
969 970
    float* g = g_tensor->data<float>();

971
    if (scale_sparse_gradient_with_batch_size && grad_dim > 0) {
972
      int dim = emb_dim;
973 974 975 976 977
      Eigen::Map<
          Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>
          g_mat(g, g_tensor->numel() / dim, dim);
      g_mat.rightCols(grad_dim) *= batch_size;
    }
978 979 980 981 982
    for (auto id_idx = 0u; id_idx < len; ++id_idx) {
      if (ids[id_idx] == 0) {
        g += emb_dim;
        continue;
      }
983
      sparse_push_keys->push_back(ids[id_idx]);
984
      CHECK(fea_idx < (*push_values).size());
T
Thunderbrook 已提交
985

986
      if (use_cvm || no_cvm) {
T
Thunderbrook 已提交
987
        memcpy((*push_values)[fea_idx].data() + offset + slot_offset, g,
988 989
               sizeof(float) * emb_dim);
      } else {
990
        CHECK(fea_idx < fea_labels.size());
T
Thunderbrook 已提交
991
        memcpy((*push_values)[fea_idx].data() + offset + slot_offset, g,
992
               sizeof(float) * emb_dim);
T
Thunderbrook 已提交
993 994 995 996 997 998
        (*push_values)[fea_idx][show_index] = 1.0f;
        (*push_values)[fea_idx][click_index] =
            static_cast<float>(fea_labels[fea_idx]);
      }
      if (dump_slot) {
        (*push_values)[fea_idx][0] = static_cast<float>(slot);
999
      }
1000 1001 1002 1003
      g += emb_dim;
      fea_idx++;
    }
  }
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
  // slots whose embedding has been stop gradient or
  // not involved in forward-backward
  uint64_t no_grad_fea_num = 0u;
  for (size_t i = sparse_grad_names.size(); i < sparse_key_names.size(); ++i) {
    Variable* var = scope.FindVar(sparse_key_names[i]);
    if (var == nullptr) {
      continue;
    }
    LoDTensor* tensor = var->GetMutable<LoDTensor>();
    if (tensor == nullptr) {
      LOG(ERROR) << "tensor of var[" << sparse_key_names[i] << "] is null";
      exit(-1);
    }
1017
    size_t len = tensor->numel();
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
    int64_t* ids = tensor->data<int64_t>();
    for (auto id_idx = 0u; id_idx < len; ++id_idx) {
      if (ids[id_idx] == 0) {
        continue;
      }
      ++no_grad_fea_num;
    }
  }
  CHECK(fea_idx + no_grad_fea_num == fea_keys.size())
      << "fea_idx: " << fea_idx << " no_grad_fea_num: " << no_grad_fea_num
      << " features size: " << fea_keys.size();
  CHECK(fea_idx == sparse_push_keys->size());
  if (fea_idx == 0) {
    return;
  }
1033
  std::vector<float*> push_g_vec;
1034
  for (auto i = 0u; i < sparse_push_keys->size(); ++i) {
1035 1036 1037
    push_g_vec.push_back((*push_values)[i].data());
  }
  auto status = pslib_ptr_->_worker_ptr->push_sparse(
1038 1039
      table_id, sparse_push_keys->data(), (const float**)push_g_vec.data(),
      sparse_push_keys->size());
1040 1041 1042 1043
  push_sparse_status->push_back(std::move(status));
#endif
}

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 1097 1098 1099 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
void FleetWrapper::PushSparseFromTensorWithLabelAsync(
    const Scope& scope, const uint64_t table_id, int fea_dim,
    uint64_t padding_id, bool scale_sparse, const std::string& accesor,
    const std::string& click_name, platform::Place place,
    const std::vector<std::string>& input_names,
    std::vector<const LoDTensor*>* inputs,
    std::vector<const LoDTensor*>* outputs) {
#ifdef PADDLE_WITH_PSLIB
  int show_index = 0;
  int click_index = 1;
  // these default values can not be used, it must be set.
  bool dump_slot = false;
  int slot_offset = 0;
  int grad_dim = 0;
  // don't worry, user do not have to care about all these flags
  if (accesor == "DownpourCtrAccessor") {
    dump_slot = true;
    slot_offset = 1;
    grad_dim = fea_dim - 2;
    show_index = 1;
    click_index = 2;
  } else if (accesor == "DownpourFeatureValueAccessor") {
    dump_slot = false;
    slot_offset = 0;
    grad_dim = fea_dim - 2;
  } else if (accesor == "DownpourSparseValueAccessor") {
    dump_slot = false;
    slot_offset = 0;
    grad_dim = fea_dim;
  }
  CHECK(grad_dim >= 0);  // NOLINT

  int batch_size = -1;
  for (auto* input : *inputs) {
    int cur_batch_size =
        input->lod().size() ? input->lod()[0].size() - 1 : input->dims()[0];
    if (batch_size == -1) {
      batch_size = cur_batch_size;
    } else {
      CHECK(batch_size == cur_batch_size);  // NOLINT
    }
  }
  CHECK(batch_size > 0);  // NOLINT

  std::vector<float> g;
  for (const framework::LoDTensor* g_tensor : *outputs) {
    size_t origin = g.size();
    size_t add = g_tensor->numel();
    g.resize(origin + add);
    memcpy(g.data() + origin, g_tensor->data<float>(), add);
  }
  if (scale_sparse && grad_dim > 0) {
    size_t dim = static_cast<size_t>(grad_dim);
    Eigen::Map<
        Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>
        g_mat(g.data(), g.size() / dim, dim);
    g_mat.rightCols(grad_dim) *= batch_size;
  }

  std::vector<float> fea_labels;
  fea_labels.reserve(MAX_FEASIGN_NUM / 100);
  framework::Variable* var = scope.FindVar(click_name);
  size_t global_idx = 0;
  if (click_name != "") {
    CHECK(var != nullptr);  // NOLINT
    framework::LoDTensor* label_tensor =
        var->GetMutable<framework::LoDTensor>();
    CHECK(label_tensor != nullptr);  // NOLINT
    int64_t* label_ptr = label_tensor->data<int64_t>();

    for (auto* tensor : *inputs) {
      const int64_t* ids = tensor->data<int64_t>();
      size_t fea_idx = 0;
      for (size_t lod_idx = 1; lod_idx < tensor->lod()[0].size(); ++lod_idx) {
        size_t cur =
            GetAbsoluteSum(tensor->lod()[0][lod_idx - 1],
                           tensor->lod()[0][lod_idx], 0, tensor->lod());
        for (size_t i = 0; i < cur; ++i, ++fea_idx) {
          if (static_cast<uint64_t>(ids[fea_idx]) == padding_id) {
            continue;
          }
          fea_labels.push_back(static_cast<float>(label_ptr[lod_idx - 1]));
          ++global_idx;
        }
      }
    }
  }
  std::vector<uint64_t> push_keys;
  push_keys.reserve(MAX_FEASIGN_NUM / 100);
  std::vector<std::vector<float>> push_values;
  push_values.reserve(MAX_FEASIGN_NUM / 100);
  size_t output_len = 0;
  size_t input_idx = 0;
  for (size_t index = 0; index < inputs->size(); ++index) {
    const framework::LoDTensor* tensor = inputs->at(index);
    const int64_t* ids = tensor->data<int64_t>();
    size_t len = tensor->numel();
    for (size_t i = 0; i < len; ++i, output_len += fea_dim) {
      if (static_cast<uint64_t>(ids[i]) == padding_id) {
        continue;
      }
      push_keys.emplace_back(ids[i]);
      push_values.emplace_back(fea_dim + slot_offset);
      float* data = push_values.back().data();
      if (!var) {
        memcpy(data + slot_offset, g.data() + output_len,
               sizeof(float) * fea_dim);
      } else {
        memcpy(data + slot_offset, g.data() + output_len,
               sizeof(float) * grad_dim);
        data[show_index] = 1.0f;
        data[click_index] = static_cast<float>(fea_labels.at(input_idx));
      }
      if (dump_slot) {
1158
        int slot = std::stoi(input_names[index]);
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
        data[0] = static_cast<float>(slot);
      }
      ++input_idx;
    }
  }

  CHECK(output_len == g.size());  // NOLINT
  if (click_name != "") {
    CHECK(input_idx == global_idx);  // NOLINT
  }

  std::vector<float*> push_g_vec(input_idx, nullptr);
  for (auto i = 0u; i < push_keys.size(); ++i) {
    push_g_vec[i] = push_values.at(i).data();
  }
  auto status = pslib_ptr_->_worker_ptr->push_sparse(
      table_id, push_keys.data(), (const float**)push_g_vec.data(),
      push_keys.size());
#endif
}

1180 1181 1182 1183
void FleetWrapper::LoadFromPaddleModel(Scope& scope, const uint64_t table_id,
                                       std::vector<std::string> var_list,
                                       std::string model_path,
                                       std::string model_proto_file,
1184
                                       std::vector<std::string> table_var_list,
1185
                                       bool load_combine) {
1186
#ifdef PADDLE_WITH_PSLIB
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 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 1245 1246 1247 1248 1249 1250 1251
  // load ProgramDesc from model file
  auto read_proto_func = [](const std::string& filename) -> ProgramDesc {
    std::string contents;
    std::ifstream fin(filename, std::ios::in | std::ios::binary);
    fin.seekg(0, std::ios::end);
    contents.resize(fin.tellg());
    fin.seekg(0, std::ios::beg);
    fin.read(&contents[0], contents.size());
    fin.close();
    ProgramDesc program_desc(contents);
    return program_desc;
  };
  const ProgramDesc old_program = read_proto_func(model_proto_file);
  Scope* old_scope = new Scope();
  auto& old_block = old_program.Block(0);
  auto place = platform::CPUPlace();
  std::vector<std::string> old_param_list;

  for (auto& t : var_list) {
    VarDesc* old_var_desc = old_block.FindVar(t);
    if (old_var_desc == nullptr) {
      continue;
    }
    // init variable in scope
    Variable* old_var = old_scope->Var(old_var_desc->Name());
    InitializeVariable(old_var, old_var_desc->GetType());
    old_param_list.push_back(t);
    if (load_combine) {
      continue;
    }
    // load variable from model
    paddle::framework::AttributeMap attrs;
    attrs.insert({"file_path", model_path + "/" + old_var_desc->Name()});
    auto load_op = paddle::framework::OpRegistry::CreateOp(
        "load", {}, {{"Out", {old_var_desc->Name()}}}, attrs);
    load_op->Run(*old_scope, place);
  }

  if (load_combine) {
    std::sort(old_param_list.begin(), old_param_list.end());
    paddle::framework::AttributeMap attrs;
    attrs.insert({"file_path", model_path});
    auto load_op = paddle::framework::OpRegistry::CreateOp(
        "load_combine", {}, {{"Out", old_param_list}}, attrs);
    load_op->Run(*old_scope, place);
  }

  for (auto& t : old_param_list) {
    Variable* old_var = old_scope->Var(t);
    // old model data, here we assume data type is float
    LoDTensor* old_tensor = old_var->GetMutable<LoDTensor>();
    float* old_data = old_tensor->data<float>();
    // new model data, here we assume data type is float
    Variable* var = scope.FindVar(t);
    CHECK(var != nullptr) << "var[" << t << "] not found";
    LoDTensor* tensor = var->GetMutable<LoDTensor>();
    float* data = tensor->data<float>();
    // copy from old data to new data
    if (old_tensor->numel() > tensor->numel()) {
      memcpy(data, old_data, tensor->numel() * sizeof(float));
    } else {
      memcpy(data, old_data, old_tensor->numel() * sizeof(float));
    }
  }
  delete old_scope;
1252 1253
  PushDenseParamSync(scope, table_id, table_var_list);
#endif
1254 1255
}

1256 1257 1258 1259 1260 1261
void FleetWrapper::LoadModel(const std::string& path, const int mode) {
#ifdef PADDLE_WITH_PSLIB
  auto ret = pslib_ptr_->_worker_ptr->load(path, std::to_string(mode));
  ret.wait();
  if (ret.get() != 0) {
    LOG(ERROR) << "load model from path:" << path << " failed";
1262
    sleep(sleep_seconds_before_fail_exit_);
1263 1264 1265 1266 1267 1268 1269
    exit(-1);
  }
#else
  VLOG(0) << "FleetWrapper::LoadModel does nothing when no pslib";
#endif
}

1270 1271 1272 1273 1274 1275 1276 1277 1278
void FleetWrapper::LoadModelOneTable(const uint64_t table_id,
                                     const std::string& path, const int mode) {
#ifdef PADDLE_WITH_PSLIB
  auto ret =
      pslib_ptr_->_worker_ptr->load(table_id, path, std::to_string(mode));
  ret.wait();
  if (ret.get() != 0) {
    LOG(ERROR) << "load model of table id: " << table_id
               << ", from path: " << path << " failed";
1279
    exit(-1);
1280 1281 1282 1283 1284 1285
  }
#else
  VLOG(0) << "FleetWrapper::LoadModel does nothing when no pslib";
#endif
}

1286 1287 1288
void FleetWrapper::LoadWithWhitelist(const uint64_t table_id,
                                     const std::string& path, const int mode) {
#ifdef PADDLE_WITH_PSLIB
1289 1290 1291 1292 1293 1294
  auto ret = pslib_ptr_->_worker_ptr->load_with_whitelist(table_id, path,
                                                          std::to_string(mode));
  ret.wait();
  if (ret.get() != 0) {
    LOG(ERROR) << "load model of table id: " << table_id
               << ", from path: " << path << " failed";
1295
    exit(-1);
1296
  }
1297 1298 1299 1300 1301
#else
  VLOG(0) << "FleetWrapper::LoadWhitelist does nothing when no pslib";
#endif
}

1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
void FleetWrapper::SaveMultiTableOnePath(const std::vector<int>& table_ids,
                                         const std::string& path,
                                         const int mode) {
#ifdef PADDLE_WITH_PSLIB
  auto ret = pslib_ptr_->_worker_ptr->save_multi_table_one_path(
      table_ids, path, std::to_string(mode));
  ret.wait();
  int32_t feasign_cnt = ret.get();
  if (feasign_cnt == -1) {
    LOG(ERROR) << "save model failed";
    sleep(sleep_seconds_before_fail_exit_);
    exit(-1);
  }
#else
  VLOG(0) << "FleetWrapper::SaveMultiTableOnePath does nothing when no pslib";
#endif
}

1320 1321 1322 1323 1324 1325 1326
void FleetWrapper::SaveModel(const std::string& path, const int mode) {
#ifdef PADDLE_WITH_PSLIB
  auto ret = pslib_ptr_->_worker_ptr->save(path, std::to_string(mode));
  ret.wait();
  int32_t feasign_cnt = ret.get();
  if (feasign_cnt == -1) {
    LOG(ERROR) << "save model failed";
1327
    sleep(sleep_seconds_before_fail_exit_);
1328 1329 1330 1331 1332 1333 1334
    exit(-1);
  }
#else
  VLOG(0) << "FleetWrapper::SaveModel does nothing when no pslib";
#endif
}

X
xujiaqi01 已提交
1335 1336 1337 1338 1339 1340 1341 1342 1343
void FleetWrapper::SaveModelOneTable(const uint64_t table_id,
                                     const std::string& path, const int mode) {
#ifdef PADDLE_WITH_PSLIB
  auto ret =
      pslib_ptr_->_worker_ptr->save(table_id, path, std::to_string(mode));
  ret.wait();
  if (ret.get() != 0) {
    LOG(ERROR) << "save model of table id: " << table_id
               << ", to path: " << path << " failed";
1344
    exit(-1);
X
xujiaqi01 已提交
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
  }
#else
  VLOG(0) << "FleetWrapper::SaveModelOneTable does nothing when no pslib";
#endif
}

void FleetWrapper::SaveModelOneTablePrefix(const uint64_t table_id,
                                           const std::string& path,
                                           const int mode,
                                           const std::string& prefix) {
#ifdef PADDLE_WITH_PSLIB
  auto ret = pslib_ptr_->_worker_ptr->save(table_id, path, std::to_string(mode),
                                           prefix);
  ret.wait();
  if (ret.get() != 0) {
    LOG(ERROR) << "save model (with prefix) of table id: " << table_id
               << ", to path: " << path << " failed";
1362
    exit(-1);
X
xujiaqi01 已提交
1363 1364 1365 1366 1367 1368
  }
#else
  VLOG(0) << "FleetWrapper::SaveModelOneTablePrefix does nothing when no pslib";
#endif
}

1369
void FleetWrapper::SetDate(const uint64_t table_id, const std::string& date) {
1370
#if (defined PADDLE_WITH_PSLIB) && (defined PADDLE_WITH_HETERPS)
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
  assert(date.size() == 8);
  int year = std::stoi(date.substr(0, 4));
  int month = std::stoi(date.substr(4, 2));
  int day = std::stoi(date.substr(6, 2));
  struct std::tm b;
  b.tm_year = year - 1900;
  b.tm_mon = month - 1;
  b.tm_mday = day;
  b.tm_hour = b.tm_min = b.tm_sec = 0;
  std::time_t seconds_from_1970 = std::mktime(&b);
  int day_id = seconds_from_1970 / 86400;
  auto ret = pslib_ptr_->_worker_ptr->set_day_id(table_id, day_id);
  ret.wait();
  if (ret.get() != 0) {
    LOG(ERROR) << "setdate : " << date << " failed";
1386
    exit(-1);
1387 1388
  }
#else
1389
  VLOG(0) << "FleetWrapper::SetDate does nothing when no pslib-gpu";
1390 1391 1392
#endif
}

1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
void FleetWrapper::PrintTableStat(const uint64_t table_id) {
#ifdef PADDLE_WITH_PSLIB
  auto ret = pslib_ptr_->_worker_ptr->print_table_stat(table_id);
  ret.wait();
  int32_t err_code = ret.get();
  if (err_code == -1) {
    LOG(ERROR) << "print table stat failed";
  }
#else
  VLOG(0) << "FleetWrapper::PrintTableStat does nothing when no pslib";
#endif
}

1406
void FleetWrapper::SetFileNumOneShard(const uint64_t table_id, int file_num) {
1407
#if (defined PADDLE_WITH_PSLIB) && (defined PADDLE_WITH_HETERPS)
1408 1409 1410 1411 1412 1413 1414 1415
  auto ret =
      pslib_ptr_->_worker_ptr->set_file_num_one_shard(table_id, file_num);
  ret.wait();
  int32_t err_code = ret.get();
  if (err_code == -1) {
    LOG(ERROR) << "set_file_num_one_shard failed";
  }
#else
1416
  VLOG(0) << "FleetWrapper::SetFileNumOneShard does nothing when no pslib-gpu";
1417 1418 1419
#endif
}

1420
double FleetWrapper::GetCacheThreshold(int table_id) {
1421 1422 1423 1424
#ifdef PADDLE_WITH_PSLIB
  double cache_threshold = 0.0;
  auto ret = pslib_ptr_->_worker_ptr->flush();
  ret.wait();
1425
  ret = pslib_ptr_->_worker_ptr->get_cache_threshold(table_id, cache_threshold);
1426 1427 1428
  ret.wait();
  if (cache_threshold < 0) {
    LOG(ERROR) << "get cache threshold failed";
1429
    sleep(sleep_seconds_before_fail_exit_);
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
    exit(-1);
  }
  return cache_threshold;
#else
  VLOG(0) << "FleetWrapper::GetCacheThreshold does nothing when no pslib";
  return 0.0;
#endif
}

void FleetWrapper::CacheShuffle(int table_id, const std::string& path,
                                const int mode, const double cache_threshold) {
#ifdef PADDLE_WITH_PSLIB
  auto ret = pslib_ptr_->_worker_ptr->cache_shuffle(
1443
      table_id, path, std::to_string(mode), std::to_string(cache_threshold));
1444 1445 1446 1447
  ret.wait();
  int32_t feasign_cnt = ret.get();
  if (feasign_cnt == -1) {
    LOG(ERROR) << "cache shuffle failed";
1448
    sleep(sleep_seconds_before_fail_exit_);
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
    exit(-1);
  }
#else
  VLOG(0) << "FleetWrapper::CacheShuffle does nothing when no pslib";
#endif
}

int32_t FleetWrapper::SaveCache(int table_id, const std::string& path,
                                const int mode) {
#ifdef PADDLE_WITH_PSLIB
1459 1460
  auto ret =
      pslib_ptr_->_worker_ptr->save_cache(table_id, path, std::to_string(mode));
1461 1462 1463 1464
  ret.wait();
  int32_t feasign_cnt = ret.get();
  if (feasign_cnt == -1) {
    LOG(ERROR) << "table save cache failed";
1465
    sleep(sleep_seconds_before_fail_exit_);
1466 1467 1468 1469 1470 1471 1472 1473 1474
    exit(-1);
  }
  return feasign_cnt;
#else
  VLOG(0) << "FleetWrapper::SaveCache does nothing when no pslib";
  return -1;
#endif
}

1475 1476 1477 1478
int32_t FleetWrapper::SaveWithWhitelist(int table_id, const std::string& path,
                                        const int mode,
                                        const std::string& whitelist_path) {
#ifdef PADDLE_WITH_PSLIB
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
  auto ret = pslib_ptr_->_worker_ptr->save_with_whitelist(
      table_id, path, std::to_string(mode), whitelist_path);
  ret.wait();
  int32_t feasign_cnt = ret.get();
  if (feasign_cnt == -1) {
    LOG(ERROR) << "table save cache failed";
    sleep(sleep_seconds_before_fail_exit_);
    exit(-1);
  }
  return feasign_cnt;
1489 1490 1491 1492 1493 1494
#else
  VLOG(0) << "FleetWrapper::SaveCache does nothing when no pslib";
  return -1;
#endif
}

1495 1496 1497 1498
void FleetWrapper::ShrinkSparseTable(int table_id) {
#ifdef PADDLE_WITH_PSLIB
  auto ret = pslib_ptr_->_worker_ptr->shrink(table_id);
  ret.wait();
1499 1500 1501 1502 1503
  int32_t err_code = ret.get();
  if (err_code == -1) {
    LOG(ERROR) << "Shrink Sparse Table failed";
    exit(-1);
  }
1504 1505 1506 1507 1508
#else
  VLOG(0) << "FleetWrapper::ShrinkSparseTable does nothing when no pslib";
#endif
}

1509 1510 1511 1512
void FleetWrapper::ClearModel() {
#ifdef PADDLE_WITH_PSLIB
  auto ret = pslib_ptr_->_worker_ptr->clear();
  ret.wait();
1513 1514 1515 1516
  int32_t err_code = ret.get();
  if (err_code == -1) {
    LOG(ERROR) << "Clear Model failed";
  }
1517 1518 1519 1520 1521
#else
  VLOG(0) << "FleetWrapper::ClearModel does nothing when no pslib";
#endif
}

X
xujiaqi01 已提交
1522 1523 1524 1525
void FleetWrapper::ClearOneTable(const uint64_t table_id) {
#ifdef PADDLE_WITH_PSLIB
  auto ret = pslib_ptr_->_worker_ptr->clear(table_id);
  ret.wait();
1526 1527 1528 1529
  int32_t err_code = ret.get();
  if (err_code == -1) {
    LOG(ERROR) << "Clear One Table failed table_id: " << table_id;
  }
X
xujiaqi01 已提交
1530 1531 1532 1533 1534
#else
  VLOG(0) << "FleetWrapper::ClearOneTable does nothing when no pslib";
#endif
}

1535 1536
void FleetWrapper::ShrinkDenseTable(int table_id, Scope* scope,
                                    std::vector<std::string> var_list,
1537
                                    float decay, int emb_dim) {
1538 1539 1540 1541 1542 1543
#ifdef PADDLE_WITH_PSLIB
  std::vector<paddle::ps::Region> regions;
  for (std::string& name : var_list) {
    if (name.find("batch_sum") != std::string::npos) {
      Variable* var = scope->FindVar(name);
      CHECK(var != nullptr) << "var[" << name << "] not found";
1544
      VLOG(0) << "prepare shrink dense batch_sum";
1545 1546
      LoDTensor* tensor = var->GetMutable<LoDTensor>();
      float* g = tensor->data<float>();
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559

      // show_batch_sum += N * log(decay)
      std::string size_name = name;
      size_name.replace(size_name.find("batch_sum"), size_name.length(),
                        "batch_size");
      Variable* var_size = scope->FindVar(size_name);
      CHECK(var_size != nullptr) << "var[" << size_name << "] not found";
      VLOG(3) << "shrink dense batch_sum: " << name << ", " << size_name;
      float* g_size = var_size->GetMutable<LoDTensor>()->data<float>();

      for (int k = 0; k < tensor->numel(); k += emb_dim) {
        g[k] = g[k] + g_size[k] * log(decay);
      }
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
      paddle::ps::Region reg(g, tensor->numel());
      regions.emplace_back(std::move(reg));
    } else {
      Variable* var = scope->FindVar(name);
      CHECK(var != nullptr) << "var[" << name << "] not found";
      LoDTensor* tensor = var->GetMutable<LoDTensor>();
      float* g = tensor->data<float>();
      paddle::ps::Region reg(g, tensor->numel());
      regions.emplace_back(std::move(reg));
    }
  }
  auto push_status = pslib_ptr_->_worker_ptr->push_dense_param(
      regions.data(), regions.size(), table_id);
  push_status.wait();
  auto status = push_status.get();
  if (status != 0) {
T
Thunderbrook 已提交
1576 1577
    // PADDLE_THORW(platform::errors::Fatal(
    //    "push shrink dense param failed, status is [%d].", status));
1578
    sleep(sleep_seconds_before_fail_exit_);
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
    exit(-1);
  }
#else
  VLOG(0) << "FleetWrapper::ShrinkSparseTable does nothing when no pslib";
#endif
}

void FleetWrapper::ClientFlush() {
#ifdef PADDLE_WITH_PSLIB
  auto ret = pslib_ptr_->_worker_ptr->flush();
  ret.wait();
1590 1591 1592 1593
  int32_t err_code = ret.get();
  if (err_code == -1) {
    LOG(ERROR) << "Client Flush failed";
  }
1594 1595 1596 1597 1598
#else
  VLOG(0) << "FleetWrapper::ServerFlush does nothing when no pslib";
#endif
}

1599 1600
int FleetWrapper::RegisterClientToClientMsgHandler(int msg_type,
                                                   MsgHandlerFunc handler) {
1601
#ifdef PADDLE_WITH_PSLIB
X
xujiaqi01 已提交
1602 1603 1604
  VLOG(3) << "calling FleetWrapper::RegisterClientToClientMsgHandler";
  VLOG(3) << "pslib_ptr_=" << pslib_ptr_;
  VLOG(3) << "_worker_ptr=" << pslib_ptr_->_worker_ptr;
1605 1606
  return pslib_ptr_->_worker_ptr->registe_client2client_msg_handler(msg_type,
                                                                    handler);
1607 1608 1609 1610
#else
  VLOG(0) << "FleetWrapper::RegisterClientToClientMsgHandler"
          << " does nothing when no pslib";
#endif
X
xujiaqi01 已提交
1611
  return 0;
1612 1613
}

1614 1615
std::future<int32_t> FleetWrapper::SendClientToClientMsg(
    int msg_type, int to_client_id, const std::string& msg) {
1616
#ifdef PADDLE_WITH_PSLIB
1617 1618
  return pslib_ptr_->_worker_ptr->send_client2client_msg(msg_type, to_client_id,
                                                         msg);
1619 1620 1621 1622
#else
  VLOG(0) << "FleetWrapper::SendClientToClientMsg"
          << " does nothing when no pslib";
#endif
1623
  return std::future<int32_t>();
X
xujiaqi01 已提交
1624 1625
}

1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
std::default_random_engine& FleetWrapper::LocalRandomEngine() {
  struct engine_wrapper_t {
    std::default_random_engine engine;
#ifdef PADDLE_WITH_PSLIB
    engine_wrapper_t() {
      struct timespec tp;
      clock_gettime(CLOCK_REALTIME, &tp);
      double cur_time = tp.tv_sec + tp.tv_nsec * 1e-9;
      static std::atomic<uint64_t> x(0);
      std::seed_seq sseq = {x++, x++, x++, (uint64_t)(cur_time * 1000)};
      engine.seed(sseq);
    }
#endif
  };
  thread_local engine_wrapper_t r;
  return r.engine;
}

X
xujiaqi01 已提交
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661
int32_t FleetWrapper::CopyTable(const uint64_t src_table_id,
                                const uint64_t dest_table_id) {
#ifdef PADDLE_WITH_PSLIB
  auto ret = pslib_ptr_->_worker_ptr->copy_table(src_table_id, dest_table_id);
  ret.wait();
  int32_t feasign_cnt = ret.get();
  if (feasign_cnt == -1) {
    LOG(ERROR) << "copy table failed";
    sleep(sleep_seconds_before_fail_exit_);
    exit(-1);
  }
  return feasign_cnt;
#else
  VLOG(0) << "FleetWrapper::CopyTable does nothing when no pslib";
  return 0;
#endif
}

1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
void FleetWrapper::Confirm() {
#ifdef PADDLE_WITH_PSLIB
  // FIXME(xujiaqi01): will later support confirm
  // auto ret = pslib_ptr_->_worker_ptr->confirm();
  // ret.wait();
  VLOG(0) << "disable FleetWrapper::Confirm temporarily";
#else
  VLOG(0) << "FleetWrapper::Confirm does nothing when no pslib";
#endif
}

void FleetWrapper::Revert() {
#ifdef PADDLE_WITH_PSLIB
  // FIXME(xujiaqi01): will later support revert
  // auto ret = pslib_ptr_->_worker_ptr->revert();
  // ret.wait();
  VLOG(0) << "disable FleetWrapper::Revert temporarily";
#else
  VLOG(0) << "FleetWrapper::Revert does nothing when no pslib";
#endif
}

X
xujiaqi01 已提交
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
int32_t FleetWrapper::CopyTableByFeasign(
    const uint64_t src_table_id, const uint64_t dest_table_id,
    const std::vector<uint64_t>& feasign_list) {
#ifdef PADDLE_WITH_PSLIB
  auto ret = pslib_ptr_->_worker_ptr->copy_table_by_feasign(
      src_table_id, dest_table_id, feasign_list.data(), feasign_list.size());
  ret.wait();
  int32_t feasign_cnt = ret.get();
  if (feasign_cnt == -1) {
    LOG(ERROR) << "copy table by feasign failed";
    sleep(sleep_seconds_before_fail_exit_);
    exit(-1);
  }
  return feasign_cnt;
#else
  VLOG(0) << "FleetWrapper::CopyTableByFeasign does nothing when no pslib";
  return 0;
#endif
}
1703

1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717
size_t FleetWrapper::GetAbsoluteSum(size_t start, size_t end, size_t level,
                                    const framework::LoD& lod) {
  if (level >= lod.size() - 1) {
    return end - start;
  }
  size_t ret = 0;
  for (size_t i = start; i < end - 1; ++i) {
    size_t pos1 = lod[level][i];
    size_t pos2 = lod[level][i + 1];
    ret += GetAbsoluteSum(pos1, pos2, level + 1, lod);
  }
  return ret;
}

1718 1719
}  // end namespace framework
}  // end namespace paddle