ps_gpu_wrapper.cc 78.5 KB
Newer Older
T
Thunderbrook 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
// 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.

/* 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. */
T
Thunderbrook 已提交
28
#ifdef PADDLE_WITH_HETERPS
Y
yaoxuefeng 已提交
29

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

T
Thunderbrook 已提交
32
#include <algorithm>
Y
yaoxuefeng 已提交
33
#include <deque>
L
lxsbupt 已提交
34
#include <unordered_set>
Y
yaoxuefeng 已提交
35

D
danleifeng 已提交
36
#include "paddle/fluid/framework/data_set.h"
D
danleifeng 已提交
37
#include "paddle/fluid/framework/fleet/heter_ps/gpu_graph_utils.h"
L
lxsbupt 已提交
38
#include "paddle/fluid/framework/fleet/heter_ps/graph_gpu_wrapper.h"
T
Thunderbrook 已提交
39
#include "paddle/fluid/platform/timer.h"
40 41 42
#if defined(PADDLE_WITH_PSCORE)
#include "paddle/fluid/distributed/ps/table/depends/feature_value.h"
#endif
T
Thunderbrook 已提交
43

D
danleifeng 已提交
44
DECLARE_int32(gpugraph_dedup_pull_push_mode);
L
lxsbupt 已提交
45
DECLARE_int32(gpugraph_storage_mode);
D
danleifeng 已提交
46

T
Thunderbrook 已提交
47 48 49
namespace paddle {
namespace framework {

T
Thunderbrook 已提交
50
#ifdef PADDLE_WITH_PSLIB
51 52 53 54 55 56
void AfsWrapper::init(const std::string& fs_name,
                      const std::string& fs_user,
                      const std::string& pass_wd,
                      const std::string& conf) {
  int ret = afs_handler_.init(
      fs_name.c_str(), fs_user.c_str(), pass_wd.c_str(), conf.c_str());
T
Thunderbrook 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
  if (ret != 0) {
    LOG(ERROR) << "AFS Init Error";
  }
}

int AfsWrapper::remove(const std::string& path) {
  return afs_handler_.remove(path);
}

int AfsWrapper::mkdir(const std::string& path) {
  return afs_handler_.mkdir(path);
}

std::vector<std::string> AfsWrapper::list(const std::string& path) {
  return afs_handler_.list(path);
}

int AfsWrapper::exist(const std::string& path) {
  return afs_handler_.exist(path);
}

int AfsWrapper::upload(const std::string& local_file,
                       const std::string& afs_file) {
  return afs_handler_.upload_file(local_file, afs_file);
}

int AfsWrapper::download(const std::string& local_file,
                         const std::string& afs_file) {
  return afs_handler_.download_file(local_file, afs_file);
}
87 88 89 90 91 92 93 94 95 96 97 98

int AfsWrapper::touchz(const std::string& path) {
  return afs_handler_.touchz(path);
}

std::string AfsWrapper::cat(const std::string& path) {
  return afs_handler_.cat(path);
}

int AfsWrapper::mv(const std::string& old_path, const std::string& dest_path) {
  return afs_handler_.mv(old_path, dest_path);
}
T
Thunderbrook 已提交
99 100
#endif

T
Thunderbrook 已提交
101 102
std::shared_ptr<PSGPUWrapper> PSGPUWrapper::s_instance_ = NULL;
bool PSGPUWrapper::is_initialized_ = false;
103
std::mutex PSGPUWrapper::ins_mutex;
T
Thunderbrook 已提交
104 105 106 107 108
#ifdef PADDLE_WITH_PSLIB
void PSGPUWrapper::InitAfsApi(const std::string& fs_name,
                              const std::string& fs_user,
                              const std::string& pass_wd,
                              const std::string& conf) {
109 110
  int ret = afs_handler_.init(
      fs_name.c_str(), fs_user.c_str(), pass_wd.c_str(), conf.c_str());
T
Thunderbrook 已提交
111
  if (ret != 0) {
112
    VLOG(0) << "AFS Init Error";
T
Thunderbrook 已提交
113 114 115 116
  }
  use_afs_api_ = 1;
}
#endif
L
lxsbupt 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146

void PSGPUWrapper::add_key_to_local(const std::vector<uint64_t>& vec_data) {
  size_t total_len = vec_data.size();
  size_t len_per_thread = total_len / thread_keys_thread_num_;
  size_t begin = 0;
  std::vector<std::thread> threads;

  int remain = total_len % thread_keys_thread_num_;
  auto gen_graph_data_func = [this](const std::vector<uint64_t>& total_data,
                                    int begin_index,
                                    int end_index,
                                    int i) {
    for (auto iter = total_data.begin() + begin_index;
         iter != total_data.begin() + end_index;
         iter++) {
      uint64_t cur_key = *iter;
      int shard_id = cur_key % thread_keys_shard_num_;
      this->thread_keys_[i][shard_id].insert(cur_key);
    }
  };
  auto gen_graph_dynamic_mf_func = [this](
                                       const std::vector<uint64_t>& total_data,
                                       int begin_index,
                                       int end_index,
                                       int i) {
    for (auto iter = total_data.begin() + begin_index;
         iter != total_data.begin() + end_index;
         iter++) {
      uint64_t cur_key = *iter;
      int shard_id = cur_key % thread_keys_shard_num_;
147
      // TODO(lxsbupt): feasign <-> slot <-> multi_dim
L
lxsbupt 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
      this->thread_dim_keys_[i][shard_id][0].insert(cur_key);
    }
  };
  for (int i = 0; i < thread_keys_thread_num_; i++) {
    if (!multi_mf_dim_) {
      threads.push_back(
          std::thread(gen_graph_data_func,
                      std::ref(vec_data),
                      begin,
                      begin + len_per_thread + (i < remain ? 1 : 0),
                      i));
    } else {
      threads.push_back(
          std::thread(gen_graph_dynamic_mf_func,
                      std::ref(vec_data),
                      begin,
                      begin + len_per_thread + (i < remain ? 1 : 0),
                      i));
    }
    begin += len_per_thread + (i < remain ? 1 : 0);
  }
  for (std::thread& t : threads) {
    t.join();
  }
}

void PSGPUWrapper::add_key_to_gputask(std::shared_ptr<HeterContext> gpu_task) {
  std::vector<std::thread> threads;
  platform::Timer timeline;
  timeline.Start();
  // merge thread_keys to shard_keys
  auto merge_ins_dynamic_mf_func = [this, gpu_task](int shard_num, int dim_id) {
    for (int i = 0; i < thread_keys_thread_num_; ++i) {
      gpu_task->batch_add_keys(
          shard_num, dim_id, thread_dim_keys_[i][shard_num][dim_id]);
      thread_dim_keys_[i][shard_num][dim_id].clear();
    }
  };
  for (int i = 0; i < thread_keys_shard_num_; ++i) {
    for (int j = 0; j < multi_mf_dim_; j++) {
      threads.push_back(std::thread(merge_ins_dynamic_mf_func, i, j));
    }
  }
  for (auto& t : threads) {
    t.join();
  }
  timeline.Pause();

196
  VLOG(1) << "GpuPs task add keys cost " << timeline.ElapsedSec()
L
lxsbupt 已提交
197 198
          << " seconds.";
  timeline.Start();
199
  size_t slot_num = (size_t)slot_num_for_pull_feature_;
L
lxsbupt 已提交
200 201 202 203 204 205
  // no slot_fea mode and whole_hbm mode, only keep one unique_sort action
  if (slot_num > 0 && FLAGS_gpugraph_storage_mode !=
                          paddle::framework::GpuGraphStorageMode::WHOLE_HBM) {
    gpu_task->UniqueKeys();
  }
  timeline.Pause();
206
  VLOG(1) << "GpuPs task unique cost " << timeline.ElapsedSec() << " seconds.";
L
lxsbupt 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219 220
}

void PSGPUWrapper::resize_gputask(std::shared_ptr<HeterContext> gpu_task) {
  for (int i = 0; i < thread_keys_shard_num_; i++) {
    for (int j = 0; j < multi_mf_dim_; j++) {
      if (i == 0 && j == multi_mf_dim_ - 1) {
        gpu_task->feature_dim_keys_[i][j].push_back(0);
      }
      gpu_task->value_dim_ptr_[i][j].resize(
          gpu_task->feature_dim_keys_[i][j].size());
    }
  }
}

221 222
void PSGPUWrapper::PreBuildTask(std::shared_ptr<HeterContext> gpu_task,
                                Dataset* dataset_for_pull) {
Y
yaoxuefeng 已提交
223
  VLOG(3) << "PSGPUWrapper::BuildGPUPSTask begin";
T
Thunderbrook 已提交
224 225
  platform::Timer timeline;
  timeline.Start();
226
  int device_num = heter_devices_.size();
Y
yaoxuefeng 已提交
227
  gpu_task->init(thread_keys_shard_num_, device_num, multi_mf_dim_);
228

Y
yaoxuefeng 已提交
229
  std::vector<std::thread> threads;
Y
yaoxuefeng 已提交
230 231 232 233 234 235 236
  // data should be in input channel

  thread_dim_keys_.resize(thread_keys_thread_num_);
  for (int i = 0; i < thread_keys_thread_num_; i++) {
    thread_dim_keys_[i].resize(thread_keys_shard_num_);
    for (int j = 0; j < thread_keys_shard_num_; j++) {
      thread_dim_keys_[i][j].resize(multi_mf_dim_);
237
    }
Y
yaoxuefeng 已提交
238
  }
Y
yaoxuefeng 已提交
239 240 241 242

  size_t total_len = 0;
  size_t len_per_thread = 0;
  int remain = 0;
Y
yaoxuefeng 已提交
243
  size_t begin = 0;
Y
yaoxuefeng 已提交
244 245 246

  std::string data_set_name = std::string(typeid(*dataset_).name());

L
lxsbupt 已提交
247
  VLOG(1) << "gpu_graph_mode_:" << gpu_graph_mode_;
D
danleifeng 已提交
248 249 250
  if (!gpu_graph_mode_) {
    if (data_set_name.find("SlotRecordDataset") != std::string::npos) {
      VLOG(0) << "ps_gpu_wrapper use SlotRecordDataset";
251
      SlotRecordDataset* dataset = (SlotRecordDataset*)(dataset_);  // NOLINT
D
danleifeng 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
      auto input_channel = dataset->GetInputChannel();
      VLOG(0) << "psgpu wrapperinputslotchannle size: "
              << input_channel->Size();
      const std::deque<SlotRecord>& vec_data = input_channel->GetData();
      total_len = vec_data.size();
      len_per_thread = total_len / thread_keys_thread_num_;
      remain = total_len % thread_keys_thread_num_;
      VLOG(0) << "total len: " << total_len;
      auto gen_dynamic_mf_func = [this](
                                     const std::deque<SlotRecord>& total_data,
                                     int begin_index,
                                     int end_index,
                                     int i) {
        for (auto iter = total_data.begin() + begin_index;
             iter != total_data.begin() + end_index;
             iter++) {
          const auto& ins = *iter;
          const auto& feasign_v = ins->slot_uint64_feasigns_.slot_values;
          const auto& slot_offset = ins->slot_uint64_feasigns_.slot_offsets;
          for (size_t slot_idx = 0; slot_idx < slot_offset_vector_.size();
               slot_idx++) {
            for (size_t j = slot_offset[slot_offset_vector_[slot_idx]];
                 j < slot_offset[slot_offset_vector_[slot_idx] + 1];
                 j++) {
              int shard_id = feasign_v[j] % thread_keys_shard_num_;
              int dim_id = slot_index_vec_[slot_idx];
              if (feasign_v[j] != 0) {
                this->thread_dim_keys_[i][shard_id][dim_id].insert(
                    feasign_v[j]);
              }
Y
yaoxuefeng 已提交
282
            }
283 284
          }
        }
D
danleifeng 已提交
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
      };
      for (int i = 0; i < thread_keys_thread_num_; i++) {
        threads.push_back(
            std::thread(gen_dynamic_mf_func,
                        std::ref(vec_data),
                        begin,
                        begin + len_per_thread + (i < remain ? 1 : 0),
                        i));

        begin += len_per_thread + (i < remain ? 1 : 0);
      }
      for (std::thread& t : threads) {
        t.join();
      }
      timeline.Pause();
      VLOG(0) << "GpuPs build task cost " << timeline.ElapsedSec()
              << " seconds.";
    } else {
      CHECK(data_set_name.find("MultiSlotDataset") != std::string::npos);
      VLOG(0) << "ps_gpu_wrapper use MultiSlotDataset";
305
      MultiSlotDataset* dataset = (MultiSlotDataset*)(dataset_);  // NOLINT
D
danleifeng 已提交
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
      auto input_channel = dataset->GetInputChannel();

      const std::deque<Record>& vec_data = input_channel->GetData();
      total_len = vec_data.size();
      len_per_thread = total_len / thread_keys_thread_num_;
      remain = total_len % thread_keys_thread_num_;
      auto gen_func = [this](const std::deque<Record>& total_data,
                             int begin_index,
                             int end_index,
                             int i) {
        for (auto iter = total_data.begin() + begin_index;
             iter != total_data.begin() + end_index;
             iter++) {
          const auto& ins = *iter;
          const auto& feasign_v = ins.uint64_feasigns_;
          for (const auto feasign : feasign_v) {
            uint64_t cur_key = feasign.sign().uint64_feasign_;
            int shard_id = cur_key % thread_keys_shard_num_;
            this->thread_keys_[i][shard_id].insert(cur_key);
          }
        }
      };
      for (int i = 0; i < thread_keys_thread_num_; i++) {
        threads.push_back(
            std::thread(gen_func,
                        std::ref(vec_data),
                        begin,
                        begin + len_per_thread + (i < remain ? 1 : 0),
                        i));
        begin += len_per_thread + (i < remain ? 1 : 0);
336
      }
D
danleifeng 已提交
337 338 339 340 341 342
      for (std::thread& t : threads) {
        t.join();
      }
      timeline.Pause();
      VLOG(0) << "GpuPs build task cost " << timeline.ElapsedSec()
              << " seconds.";
Y
yaoxuefeng 已提交
343 344
    }
  } else {
345 346
    SlotRecordDataset* dataset =
        reinterpret_cast<SlotRecordDataset*>(dataset_for_pull);
D
danleifeng 已提交
347
    const std::vector<uint64_t>& vec_data = dataset->GetGpuGraphTotalKeys();
L
lxsbupt 已提交
348 349 350
    timeline.Start();
    add_key_to_local(vec_data);
    timeline.Pause();
351
    VLOG(1) << "GpuGraphTotalKeys: " << vec_data.size()
L
lxsbupt 已提交
352 353 354
            << ", add_key_to_local cost " << timeline.ElapsedSec()
            << " seconds.";
  }
Y
yaoxuefeng 已提交
355

L
lxsbupt 已提交
356 357 358 359 360 361 362 363 364 365
  add_key_to_gputask(gpu_task);
}

void PSGPUWrapper::add_slot_feature(std::shared_ptr<HeterContext> gpu_task) {
  platform::Timer timeline;
  platform::Timer time_stage;
  timeline.Start();
  // 8卡数据分片
  size_t device_num = heter_devices_.size();
  std::vector<std::thread> threads;
366 367
  size_t slot_num =
      (size_t)slot_num_for_pull_feature_;  // node slot 9008 in slot_vector
L
lxsbupt 已提交
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
  auto& local_dim_keys = gpu_task->feature_dim_keys_;  // [shard_num, 0, keys]]
  double divide_nodeid_cost = 0;
  double get_feature_id_cost = 0;
  double add_feature_to_set_cost = 0;
  double add_feature_to_key_cost = 0;

  std::vector<std::vector<uint64_t>> node_ids(device_num);
  size_t node_num = 0;
  for (int i = 0; i < thread_keys_shard_num_; i++) {
    for (int j = 0; j < multi_mf_dim_; j++) {
      node_num += local_dim_keys[i][j].size();
    }
  }
  for (auto& node_id_vector : node_ids) {
    node_id_vector.reserve(node_num * 1.2 / device_num);
  }

  auto& device_dim_mutex = gpu_task->dim_mutex_;

  auto divide_nodeid_to_device =
      [this, device_num, &local_dim_keys, &node_ids, &device_dim_mutex](int i,
                                                                        int j) {
        std::vector<std::vector<uint64_t>> task_keys(device_num);
        size_t batch = 10000;
        for (size_t k = 0; k < device_num; k++) {
          task_keys[k].reserve(batch * 1.2 / device_num);
        }
        std::vector<int> shuffle_device = shuffle_int_vector(device_num);
        size_t start = 0;
        while (start < local_dim_keys[i][j].size()) {
          if (batch + start > local_dim_keys[i][j].size()) {
            batch = local_dim_keys[i][j].size() - start;
D
danleifeng 已提交
400
          }
L
lxsbupt 已提交
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
          for (size_t k = start; k < (start + batch); k++) {
            int shard = local_dim_keys[i][j][k] % device_num;
            task_keys[shard].push_back(local_dim_keys[i][j][k]);
          }
          // allocate local keys to devices
          for (auto dev : shuffle_device) {
            device_dim_mutex[dev][0]->lock();
            int len = task_keys[dev].size();
            for (int k = 0; k < len; ++k) {
              node_ids[dev].push_back(task_keys[dev][k]);
            }
            device_dim_mutex[dev][0]->unlock();
            task_keys[dev].clear();
          }
          start += batch;
        }
      };
  threads.resize(thread_keys_shard_num_ * multi_mf_dim_);
  time_stage.Start();

  for (int i = 0; i < thread_keys_shard_num_; i++) {
    for (int j = 0; j < multi_mf_dim_; j++) {
      threads[i * multi_mf_dim_ + j] =
          std::thread(divide_nodeid_to_device, i, j);
    }
  }
  for (std::thread& t : threads) {
    t.join();
  }
  threads.clear();
  time_stage.Pause();
  divide_nodeid_cost = time_stage.ElapsedSec();
  gpu_task->sub_graph_feas = new std::vector<GpuPsCommGraphFea>;
  std::vector<GpuPsCommGraphFea>& sub_graph_feas =
      *((std::vector<GpuPsCommGraphFea>*)gpu_task->sub_graph_feas);
  std::vector<std::vector<uint64_t>> feature_ids(device_num);
  std::vector<uint64_t*> feature_list(device_num);
  std::vector<size_t> feature_list_size(device_num);
  size_t batch = 40000;

  time_stage.Start();
  if (FLAGS_gpugraph_storage_mode ==
      paddle::framework::GpuGraphStorageMode::MEM_EMB_AND_GPU_GRAPH) {
    auto gpu_graph_ptr = GraphGpuWrapper::GetInstance();
    auto h_slot_feature_num_map = gpu_graph_ptr->slot_feature_num_map();
    int fea_num_per_node = 0;
    for (size_t i = 0; i < slot_num; ++i) {
      fea_num_per_node += h_slot_feature_num_map[i];
    }

    auto get_feature_id = [this,
                           slot_num,
                           batch,
                           fea_num_per_node,
                           &h_slot_feature_num_map,
                           &node_ids,
                           &feature_ids](int i) {
      platform::CUDADeviceGuard guard(resource_->dev_id(i));
      int* d_slot_feature_num_map;
      uint64_t* d_node_list_ptr;
      uint64_t* d_feature_list_ptr;
      CUDA_CHECK(cudaMalloc(&d_slot_feature_num_map, slot_num * sizeof(int)));
      CUDA_CHECK(cudaMemcpy(d_slot_feature_num_map,
                            h_slot_feature_num_map.data(),
                            sizeof(int) * slot_num,
                            cudaMemcpyHostToDevice));
      CUDA_CHECK(cudaMalloc(&d_node_list_ptr, batch * sizeof(uint64_t)));
      CUDA_CHECK(cudaMalloc(&d_feature_list_ptr,
                            batch * fea_num_per_node * sizeof(uint64_t)));
      auto gpu_graph_ptr = GraphGpuWrapper::GetInstance();
      uint64_t pos = 0;
      size_t real_batch = 0;
      feature_ids[i].resize(node_ids[i].size() * fea_num_per_node);
      while (pos < node_ids[i].size()) {
        real_batch = (pos + batch) <= node_ids[i].size()
                         ? batch
                         : node_ids[i].size() - pos;
        CUDA_CHECK(cudaMemcpy(d_node_list_ptr,
                              node_ids[i].data() + pos,
                              real_batch * sizeof(uint64_t),
                              cudaMemcpyHostToDevice));
        int ret = gpu_graph_ptr->get_feature_of_nodes(i,
                                                      d_node_list_ptr,
                                                      d_feature_list_ptr,
                                                      real_batch,
                                                      slot_num,
                                                      d_slot_feature_num_map,
                                                      fea_num_per_node);
        PADDLE_ENFORCE_EQ(
            ret,
            0,
            platform::errors::PreconditionNotMet("get_feature_of_nodes error"));

        CUDA_CHECK(cudaMemcpy(feature_ids[i].data() + pos * fea_num_per_node,
                              d_feature_list_ptr,
                              real_batch * fea_num_per_node * sizeof(uint64_t),
                              cudaMemcpyDeviceToHost));
        pos += real_batch;
D
danleifeng 已提交
499
      }
L
lxsbupt 已提交
500 501 502 503 504 505 506 507
      cudaFree(d_slot_feature_num_map);
      cudaFree(d_node_list_ptr);
      cudaFree(d_feature_list_ptr);
    };

    threads.resize(device_num);
    for (size_t i = 0; i < device_num; i++) {
      threads[i] = std::thread(get_feature_id, i);
Y
yaoxuefeng 已提交
508 509 510 511
    }
    for (std::thread& t : threads) {
      t.join();
    }
L
lxsbupt 已提交
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
    threads.clear();
    for (size_t i = 0; i < device_num; i++) {
      feature_list[i] = feature_ids[i].data();
      feature_list_size[i] = feature_ids[i].size();
    }
  } else if (FLAGS_gpugraph_storage_mode ==
                 paddle::framework::GpuGraphStorageMode::
                     MEM_EMB_FEATURE_AND_GPU_GRAPH ||
             FLAGS_gpugraph_storage_mode ==
                 paddle::framework::GpuGraphStorageMode::
                     SSD_EMB_AND_MEM_FEATURE_GPU_GRAPH) {
    auto gpu_graph_ptr = GraphGpuWrapper::GetInstance();
    sub_graph_feas = gpu_graph_ptr->get_sub_graph_fea(node_ids, slot_num);
    for (size_t i = 0; i < device_num; i++) {
      feature_list[i] = sub_graph_feas[i].feature_list;
      feature_list_size[i] = sub_graph_feas[i].feature_size;
    }
  } else {
    VLOG(0) << "FLAGS_gpugraph_storage_mode is not adaptived";
  }
  time_stage.Pause();
  get_feature_id_cost = time_stage.ElapsedSec();
  size_t feature_num = 0;
  for (size_t i = 0; i < device_num; i++) {
    feature_num += feature_list_size[i];
  }
538
  VLOG(1) << "feature_num is " << feature_num << " node_num is " << node_num;
L
lxsbupt 已提交
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 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 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607

  size_t set_num = thread_keys_shard_num_;
  std::vector<std::unordered_set<uint64_t>> feature_id_set(set_num);
  std::vector<std::mutex> set_mutex(set_num);

  auto add_feature_to_set =
      [this, set_num, &feature_list, &feature_id_set, &set_mutex](
          int dev, size_t start, size_t end) {
        size_t batch = 10000 * set_num;
        std::vector<std::vector<uint64_t>> feature_list_tmp(set_num);
        for (size_t i = 0; i < set_num; i++) {
          feature_list_tmp[i].reserve((batch * 1.2) / set_num);
        }
        std::vector<int> shuffle_set_index = shuffle_int_vector(set_num);
        size_t pos = start;
        size_t real_batch = 0;
        while (pos < end) {
          real_batch = (pos + batch <= end) ? batch : end - pos;
          for (size_t i = pos; i < pos + real_batch; i++) {
            if (feature_list[dev][i] == 0) {
              continue;
            }
            int shard_num = feature_list[dev][i] % set_num;
            feature_list_tmp[shard_num].push_back(feature_list[dev][i]);
          }
          // uniq in local
          for (size_t i = 0; i < set_num; i++) {
            std::sort(feature_list_tmp[i].begin(), feature_list_tmp[i].end());
            size_t idx = 0;
            size_t total = feature_list_tmp[i].size();
            for (size_t j = 0; j < total; j++) {
              auto& k = feature_list_tmp[i][j];
              if (idx > 0 && feature_list_tmp[i][idx - 1] == k) {
                continue;
              }
              feature_list_tmp[i][idx] = k;
              ++idx;
            }
            feature_list_tmp[i].resize(idx);
          }
          // uniq in global
          for (auto set_index : shuffle_set_index) {
            set_mutex[set_index].lock();
            for (auto feature_id : feature_list_tmp[set_index]) {
              feature_id_set[set_index].insert(feature_id);
            }
            set_mutex[set_index].unlock();
            feature_list_tmp[set_index].clear();
          }
          pos += real_batch;
        }
      };
  size_t device_thread_num = 8;
  threads.resize(device_num * device_thread_num);
  time_stage.Start();
  for (size_t i = 0; i < device_num; i++) {
    size_t start = 0;
    for (size_t j = 0; j < device_thread_num; j++) {
      size_t batch = feature_list_size[i] / device_thread_num;
      if (j < feature_list_size[i] % device_thread_num) {
        batch += 1;
      }
      threads[i * device_thread_num + j] =
          std::thread(add_feature_to_set, i, start, start + batch);
      start += batch;
    }
  }
  for (std::thread& t : threads) {
    t.join();
Y
yaoxuefeng 已提交
608
  }
609
  threads.clear();
L
lxsbupt 已提交
610 611 612 613 614 615 616 617 618 619 620 621 622
  time_stage.Pause();
  add_feature_to_set_cost = time_stage.ElapsedSec();
  auto add_feature_to_key = [this,
                             device_num,
                             &feature_id_set,
                             &local_dim_keys,
                             set_num](int shard_num, int j) {
    local_dim_keys[shard_num][j].reserve(local_dim_keys[shard_num][j].size() +
                                         feature_id_set[shard_num].size());
    for (auto it = feature_id_set[shard_num].begin();
         it != feature_id_set[shard_num].end();
         it++) {
      local_dim_keys[shard_num][j].push_back(*it);
623
    }
L
lxsbupt 已提交
624
    feature_id_set[shard_num].clear();
625
  };
L
lxsbupt 已提交
626 627 628
  time_stage.Start();
  threads.resize(thread_keys_shard_num_ * multi_mf_dim_);
  for (int i = 0; i < thread_keys_shard_num_; i++) {
Y
yaoxuefeng 已提交
629
    for (int j = 0; j < multi_mf_dim_; j++) {
L
lxsbupt 已提交
630
      threads[i * multi_mf_dim_ + j] = std::thread(add_feature_to_key, i, j);
631
    }
632
  }
L
lxsbupt 已提交
633
  for (std::thread& t : threads) {
634
    t.join();
Y
yaoxuefeng 已提交
635
  }
L
lxsbupt 已提交
636 637 638
  time_stage.Pause();
  add_feature_to_key_cost = time_stage.ElapsedSec();
  threads.clear();
Y
yaoxuefeng 已提交
639
  timeline.Pause();
640
  VLOG(1) << " add_slot_feature costs: " << timeline.ElapsedSec() << " s."
L
lxsbupt 已提交
641 642 643 644
          << " divide_nodeid_cost " << divide_nodeid_cost
          << " get_feature_id_cost " << get_feature_id_cost
          << " add_feature_to_set_cost " << add_feature_to_set_cost
          << " add_feature_to_key_cost " << add_feature_to_key_cost;
645 646 647 648
}

void PSGPUWrapper::BuildPull(std::shared_ptr<HeterContext> gpu_task) {
  platform::Timer timeline;
649 650 651
  if (slot_num_for_pull_feature_ > 0 &&
      FLAGS_gpugraph_storage_mode !=
          paddle::framework::GpuGraphStorageMode::WHOLE_HBM) {
L
lxsbupt 已提交
652 653 654 655 656 657 658 659 660
    add_slot_feature(gpu_task);
  }

  resize_gputask(gpu_task);

  platform::Timer time_stage;
  time_stage.Start();
  gpu_task->UniqueKeys();
  time_stage.Pause();
661
  VLOG(1) << "BuildPull slot feature uniq and sort cost time: "
L
lxsbupt 已提交
662
          << time_stage.ElapsedSec();
663

664 665 666 667 668
  auto& local_dim_keys = gpu_task->feature_dim_keys_;
  auto& local_dim_ptr = gpu_task->value_dim_ptr_;

  auto& device_dim_keys = gpu_task->device_dim_keys_;
  auto& device_dim_ptr = gpu_task->device_dim_ptr_;
Y
yaoxuefeng 已提交
669 670 671 672

  for (size_t dev = 0; dev < device_dim_keys.size(); dev++) {
    device_dim_keys[dev].resize(multi_mf_dim_);
    device_dim_ptr[dev].resize(multi_mf_dim_);
673
  }
Y
yaoxuefeng 已提交
674

T
Thunderbrook 已提交
675
  // auto& device_mutex = gpu_task->mutex_;
676 677 678 679 680 681

  std::vector<std::thread> threads(thread_keys_shard_num_);
#ifdef PADDLE_WITH_PSLIB
  auto fleet_ptr = FleetWrapper::GetInstance();
#endif
#ifdef PADDLE_WITH_PSCORE
682
  auto fleet_ptr = paddle::distributed::FleetWrapper::GetInstance();
683
#endif
684

685
#if (defined PADDLE_WITH_PSLIB) && (defined PADDLE_WITH_HETERPS)
686 687 688 689 690 691 692 693 694 695 696
  // get day_id: day nums from 1970
  struct std::tm b;
  b.tm_year = year_ - 1900;
  b.tm_mon = month_ - 1;
  b.tm_mday = day_;
  b.tm_min = b.tm_hour = b.tm_sec = 0;
  std::time_t seconds_from_1970 = std::mktime(&b);
  int day_id = seconds_from_1970 / 86400;
  fleet_ptr->pslib_ptr_->_worker_ptr->set_day_id(table_id_, day_id);
#endif

697
  timeline.Start();
698

699
  auto ptl_dynamic_mf_func =
L
lxsbupt 已提交
700 701
      [this, &local_dim_keys, &local_dim_ptr, &fleet_ptr, &gpu_task](int i,
                                                                     int j) {
702 703 704
        size_t key_size = local_dim_keys[i][j].size();
        int32_t status = -1;
        int32_t cnt = 0;
705
#ifdef PADDLE_WITH_PSLIB
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
        while (true) {
          auto tt = fleet_ptr->pslib_ptr_->_worker_ptr->pull_sparse_ptr(
              i,
              reinterpret_cast<char**>(local_dim_ptr[i][j].data()),
              this->table_id_,
              local_dim_keys[i][j].data(),
              key_size);
          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 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);
          }
733

734 735 736 737
          if (flag) {
            break;
          }
        }
738 739
#endif
#ifdef PADDLE_WITH_PSCORE
740 741
        while (true) {
          auto tt = fleet_ptr->worker_ptr_->PullSparsePtr(
L
lxsbupt 已提交
742
              i,
743 744 745
              reinterpret_cast<char**>(local_dim_ptr[i][j].data()),
              this->table_id_,
              local_dim_keys[i][j].data(),
L
lxsbupt 已提交
746 747
              key_size,
              gpu_task->pass_id_);
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
          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 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);
          }
768

769 770 771 772
          if (flag) {
            break;
          }
        }
773
#endif
774 775 776 777 778
        if (status != 0) {
          LOG(ERROR) << "fleet pull sparse failed, status[" << status << "]";
          sleep(300);
          exit(-1);
        } else {
L
lxsbupt 已提交
779
          VLOG(1) << "FleetWrapper Pull sparse to local done with table size: "
780 781 782
                  << local_dim_keys[i][j].size();
        }
      };
Y
yaoxuefeng 已提交
783 784

  threads.resize(thread_keys_shard_num_ * multi_mf_dim_);
L
lxsbupt 已提交
785 786 787

  uint64_t total_key = 0;
  std::vector<std::future<void>> task_futures;
Y
yaoxuefeng 已提交
788 789 790 791
  for (int i = 0; i < thread_keys_shard_num_; i++) {
    for (int j = 0; j < multi_mf_dim_; j++) {
      task_futures.emplace_back(
          pull_thread_pool_[i]->enqueue(ptl_dynamic_mf_func, i, j));
L
lxsbupt 已提交
792
      total_key += local_dim_keys[i][j].size();
793
    }
794
  }
Y
yaoxuefeng 已提交
795 796
  for (auto& f : task_futures) {
    f.wait();
797
  }
Y
yaoxuefeng 已提交
798
  task_futures.clear();
799
  timeline.Pause();
800
  VLOG(1) << "pull sparse from CpuPS into GpuPS total keys " << total_key
L
lxsbupt 已提交
801
          << ", cost " << timeline.ElapsedSec() << " seconds.";
Y
yaoxuefeng 已提交
802 803 804 805 806 807 808 809
  if (multi_node_) {
    auto gloo_wrapper = paddle::framework::GlooWrapper::GetInstance();
    if (!gloo_wrapper->IsInitialized()) {
      VLOG(0) << "GLOO is not inited";
      gloo_wrapper->Init();
    }
    gloo_wrapper->Barrier();
  }
L
lxsbupt 已提交
810
}
811

L
lxsbupt 已提交
812 813 814 815 816 817 818
void PSGPUWrapper::divide_to_device(std::shared_ptr<HeterContext> gpu_task) {
  platform::Timer timeline;
  int device_num = heter_devices_.size();
  std::vector<std::thread> threads;
  std::vector<std::future<void>> task_futures;
  auto& local_dim_keys = gpu_task->feature_dim_keys_;
  auto& local_dim_ptr = gpu_task->value_dim_ptr_;
Y
yaoxuefeng 已提交
819

L
lxsbupt 已提交
820 821 822 823 824 825 826 827 828 829 830 831 832
  auto& device_dim_keys = gpu_task->device_dim_keys_;
  auto& device_dim_ptr = gpu_task->device_dim_ptr_;
  auto& device_dim_mutex = gpu_task->dim_mutex_;
  // auto& device_mutex = gpu_task->mutex_;

  if (multi_mf_dim_) {
    for (size_t dev = 0; dev < device_dim_keys.size(); dev++) {
      device_dim_keys[dev].resize(multi_mf_dim_);
      device_dim_ptr[dev].resize(multi_mf_dim_);
    }
  }

  timeline.Start();
833 834 835 836 837
  auto build_pull_dynamic_mf_func = [this,
                                     device_num,
                                     &local_dim_keys,
                                     &local_dim_ptr,
                                     &device_dim_keys,
Y
yaoxuefeng 已提交
838 839
                                     &device_dim_ptr,
                                     &device_dim_mutex](int i, int j) {
840
    std::vector<std::vector<FeatureKey>> task_keys(device_num);
841
#ifdef PADDLE_WITH_PSLIB
842 843
    std::vector<std::vector<paddle::ps::DownpourFixedFeatureValue*>> task_ptrs(
        device_num);
844 845 846 847 848 849
#endif

#ifdef PADDLE_WITH_PSCORE
    std::vector<std::vector<paddle::distributed::FixedFeatureValue*>> task_ptrs(
        device_num);
#endif
850 851 852 853 854
    for (size_t k = 0; k < local_dim_keys[i][j].size(); k++) {
      int shard = local_dim_keys[i][j][k] % device_num;
      task_keys[shard].push_back(local_dim_keys[i][j][k]);
      task_ptrs[shard].push_back(local_dim_ptr[i][j][k]);
    }
Y
yaoxuefeng 已提交
855
    // allocate local keys to devices
L
lxsbupt 已提交
856 857
    std::vector<int> shuffle_device = shuffle_int_vector(device_num);
    for (auto dev : shuffle_device) {
Y
yaoxuefeng 已提交
858 859 860 861 862 863 864 865
      device_dim_mutex[dev][j]->lock();
      int len = task_keys[dev].size();
      int cur = device_dim_keys[dev][j].size();
      device_dim_keys[dev][j].resize(device_dim_keys[dev][j].size() + len);
      device_dim_ptr[dev][j].resize(device_dim_ptr[dev][j].size() + len);
      for (int k = 0; k < len; ++k) {
        device_dim_keys[dev][j][cur + k] = task_keys[dev][k];
        device_dim_ptr[dev][j][cur + k] = task_ptrs[dev][k];
866
      }
Y
yaoxuefeng 已提交
867
      device_dim_mutex[dev][j]->unlock();
868 869
    }
  };
L
lxsbupt 已提交
870 871 872 873 874 875 876 877 878 879 880 881 882 883

  if (multi_mf_dim_) {
    threads.resize(thread_keys_shard_num_ * multi_mf_dim_);
    for (int i = 0; i < thread_keys_shard_num_; i++) {
      for (int j = 0; j < multi_mf_dim_; j++) {
        threads[i * multi_mf_dim_ + j] =
            std::thread(build_pull_dynamic_mf_func, i, j);
      }
    }
    for (std::thread& t : threads) {
      t.join();
    }
  }
  timeline.Pause();
884
  VLOG(1) << "GpuPs prepare for build hbm cost " << timeline.ElapsedSec()
L
lxsbupt 已提交
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
          << " seconds.";
}

void PSGPUWrapper::PrepareGPUTask(std::shared_ptr<HeterContext> gpu_task) {
  platform::Timer timeline;
  int device_num = heter_devices_.size();
  std::vector<std::thread> threads;
  std::vector<std::future<void>> task_futures;
  auto& local_keys = gpu_task->feature_keys_;
  auto& local_ptr = gpu_task->value_ptr_;

  auto& device_keys = gpu_task->device_keys_;
  auto& device_vals = gpu_task->device_values_;
  // auto& device_mutex = gpu_task->mutex_;

  timeline.Start();
  std::vector<std::vector<std::pair<uint64_t, char*>>> pass_values;

  bool record_status = false;
  auto& device_task_keys = gpu_task->device_task_keys_;
  auto& device_task_ptrs = gpu_task->device_task_ptr_;

907 908 909 910 911 912 913
  auto build_func = [device_num,
                     record_status,
                     &pass_values,
                     &local_keys,
                     &local_ptr,
                     &device_task_keys,
                     &device_task_ptrs](int i) {
T
Thunderbrook 已提交
914
    auto& task_keys = device_task_keys[i];
T
Thunderbrook 已提交
915
#ifdef PADDLE_WITH_PSLIB
T
Thunderbrook 已提交
916
    auto& task_ptrs = device_task_ptrs[i];
T
Thunderbrook 已提交
917 918 919
#endif

#ifdef PADDLE_WITH_PSCORE
T
Thunderbrook 已提交
920
    auto& task_ptrs = device_task_ptrs[i];
T
Thunderbrook 已提交
921
#endif
922 923 924 925 926 927

    for (size_t j = 0; j < local_keys[i].size(); j++) {
      int shard = local_keys[i][j] % device_num;
      task_keys[shard].push_back(local_keys[i][j]);
      task_ptrs[shard].push_back(local_ptr[i][j]);
    }
928
#ifdef PADDLE_WITH_PSLIB
Y
yaoxuefeng 已提交
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
    if (record_status) {
      size_t local_keys_size = local_keys.size();
      size_t pass_values_size = pass_values.size();
      for (size_t j = 0; j < pass_values_size; j += local_keys_size) {
        auto& shard_values = pass_values[j];
        for (size_t pair_idx = 0; pair_idx < pass_values[j].size();
             pair_idx++) {
          auto& cur_pair = shard_values[pair_idx];
          int shard = cur_pair.first % device_num;
          task_keys[shard].push_back(cur_pair.first);
          task_ptrs[shard].push_back(
              (paddle::ps::DownpourFixedFeatureValue*)cur_pair.second);
        }
      }
    }
944
#endif
T
Thunderbrook 已提交
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
  };
  if (!multi_mf_dim_) {
    for (int i = 0; i < thread_keys_shard_num_; i++) {
      task_futures.emplace_back(hbm_thread_pool_[i]->enqueue(build_func, i));
    }
    for (auto& f : task_futures) {
      f.wait();
    }
    task_futures.clear();
    VLOG(0) << "GpuPs build hbmps done";
  }
  std::vector<std::vector<int>> prefix_sum;
  prefix_sum.resize(device_num);
  for (int i = 0; i < device_num; i++) {
    prefix_sum[i].resize(thread_keys_shard_num_ + 1);
    prefix_sum[i][0] = 0;
  }
962 963 964 965
  auto calc_prefix_func = [this,
                           &prefix_sum,
                           &device_keys,
                           &device_vals,
T
Thunderbrook 已提交
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
                           &device_task_keys](int device_num) {
    for (int j = 0; j < thread_keys_shard_num_; j++) {
      prefix_sum[device_num][j + 1] =
          prefix_sum[device_num][j] + device_task_keys[j][device_num].size();
    }
    device_keys[device_num].resize(
        prefix_sum[device_num][thread_keys_shard_num_]);
    device_vals[device_num].resize(
        prefix_sum[device_num][thread_keys_shard_num_]);
  };
  if (!multi_mf_dim_) {
    for (int i = 0; i < device_num; i++) {
      task_futures.emplace_back(
          hbm_thread_pool_[i]->enqueue(calc_prefix_func, i));
    }
    for (auto& f : task_futures) {
      f.wait();
    }
    task_futures.clear();
  }
  VLOG(0) << "prefix done";
987 988 989 990 991
  auto prepare_dev_value_func = [device_num,
                                 &prefix_sum,
                                 &device_keys,
                                 &device_vals,
                                 &device_task_keys,
T
Thunderbrook 已提交
992 993 994
                                 &device_task_ptrs](int dev, int shard_id) {
#ifdef PADDLE_WITH_PSLIB
    auto& task_ptrs = device_task_ptrs[shard_id];
995

T
Thunderbrook 已提交
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
    for (int j = 0; j < len; ++j) {
      device_keys[dev][cur + j] = task_keys[dev][j];
      float* ptr_val = task_ptrs[dev][j]->data();
      FeatureValue& val = device_vals[dev][cur + j];
      size_t dim = task_ptrs[dev][j]->size();

      val.delta_score = ptr_val[1];
      val.show = ptr_val[2];
      val.clk = ptr_val[3];
      val.slot = ptr_val[6];
      val.lr = ptr_val[4];
      val.lr_g2sum = ptr_val[5];
      val.cpu_ptr = (uint64_t)(task_ptrs[dev][j]);

      if (dim > 7) {
        val.mf_size = MF_DIM + 1;
        for (int x = 0; x < val.mf_size; x++) {
          val.mf[x] = ptr_val[x + 7];
        }
      } else {
        val.mf_size = 0;
        for (int x = 0; x < MF_DIM + 1; x++) {
          val.mf[x] = 0;
Y
yaoxuefeng 已提交
1019 1020
        }
      }
T
Thunderbrook 已提交
1021
    }
T
Thunderbrook 已提交
1022
#endif
T
Thunderbrook 已提交
1023
    VLOG(3) << "GpuPs build hbmps done";
Y
yaoxuefeng 已提交
1024
  };
L
lxsbupt 已提交
1025
  if (!multi_mf_dim_) {
T
Thunderbrook 已提交
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
    for (int i = 0; i < thread_keys_shard_num_; i++) {
      for (int j = 0; j < device_num; j++) {
        task_futures.emplace_back(
            hbm_thread_pool_[i]->enqueue(prepare_dev_value_func, j, i));
      }
    }
    for (auto& f : task_futures) {
      f.wait();
    }
    task_futures.clear();
Y
yaoxuefeng 已提交
1036 1037
  }
  timeline.Pause();
T
Thunderbrook 已提交
1038
  VLOG(0) << "GpuPs prepare for build hbm cost " << timeline.ElapsedSec()
1039
          << " seconds.";
Y
yaoxuefeng 已提交
1040 1041
}

1042
void PSGPUWrapper::BuildGPUTask(std::shared_ptr<HeterContext> gpu_task) {
1043
  int device_num = heter_devices_.size();
L
lxsbupt 已提交
1044 1045
  platform::Timer stagetime;
  stagetime.Start();
T
Thunderbrook 已提交
1046

1047
  std::vector<size_t> feature_keys_count(device_num);
T
Thunderbrook 已提交
1048
  size_t size_max = 0;
Y
yaoxuefeng 已提交
1049 1050 1051 1052 1053 1054 1055

  for (int i = 0; i < device_num; i++) {
    for (int j = 0; j < multi_mf_dim_; j++) {
      feature_keys_count[i] += gpu_task->device_dim_ptr_[i][j].size();
      VLOG(1) << i << " card with dynamic mf dim: " << index_dim_vec_[j]
              << " dim index: " << j << " contains feasign nums: "
              << gpu_task->device_dim_ptr_[i][j].size();
1056
    }
1057
    VLOG(1) << i << " card with dynamic mf contains feasign nums total: "
Y
yaoxuefeng 已提交
1058 1059
            << feature_keys_count[i];
    size_max = std::max(size_max, feature_keys_count[i]);
T
Thunderbrook 已提交
1060
  }
1061
  if (size_max <= 0) {
1062
    VLOG(0) << "Skip build gpu ps cause feasign nums = " << size_max;
1063 1064
    return;
  }
1065
  std::vector<std::thread> threads(device_num);
D
danleifeng 已提交
1066
  auto accessor_wrapper_ptr =
D
danleifeng 已提交
1067
      GlobalAccessorFactory::GetInstance().GetAccessorWrapper();
L
lxsbupt 已提交
1068 1069 1070
  if (HeterPs_ == NULL) {
    HeterPs_ = HeterPsBase::get_instance(
        size_max, resource_, fleet_config_, accessor_class_, optimizer_type_);
F
Fan Zhang 已提交
1071
#ifdef PADDLE_WITH_CUDA
L
lxsbupt 已提交
1072 1073 1074 1075
    HeterPs_->set_nccl_comm_and_size(
        inner_comms_, inter_comms_, node_size_, rank_id_);
    HeterPs_->set_sparse_sgd(optimizer_config_);
    HeterPs_->set_embedx_sgd(optimizer_config_);
F
Fan Zhang 已提交
1076
#endif
L
lxsbupt 已提交
1077 1078
  }
  stagetime.Pause();
1079
  VLOG(1) << "card: "
L
lxsbupt 已提交
1080 1081 1082
          << " BuildGPUTask create HeterPs_ costs: " << stagetime.ElapsedSec()
          << " s.";
  stagetime.Start();
Z
zmxdream 已提交
1083

L
lxsbupt 已提交
1084 1085 1086
  auto build_dynamic_mf_func = [this, &gpu_task, &accessor_wrapper_ptr](
                                   int i, int j, size_t start, size_t end) {
    // this->HeterPs_->set_multi_mf_dim(multi_mf_dim_, max_mf_dim_);
Y
yaoxuefeng 已提交
1087
    auto& device_dim_ptrs = gpu_task->device_dim_ptr_[i][j];
Z
zmxdream 已提交
1088 1089
    int mf_dim = this->index_dim_vec_[j];
    size_t feature_value_size =
D
danleifeng 已提交
1090
        accessor_wrapper_ptr->GetFeatureValueSize(mf_dim);
L
lxsbupt 已提交
1091 1092 1093 1094 1095
    size_t real_len = end - start;
    std::shared_ptr<char> build_values(new char[feature_value_size * real_len],
                                       [](char* p) { delete[] p; });
    char* test_build_values = build_values.get();
    for (size_t k = start; k < end; k++) {
D
danleifeng 已提交
1096
#ifdef PADDLE_WITH_PSLIB
L
lxsbupt 已提交
1097 1098
      float* val = reinterpret_cast<float*>(test_build_values +
                                            (k - start) * feature_value_size);
Y
yaoxuefeng 已提交
1099 1100 1101 1102 1103 1104 1105 1106 1107
      float* ptr_val = device_dim_ptrs[k]->data();
      size_t dim = device_dim_ptrs[k]->size();
      val->delta_score =
          ptr_val[paddle::ps::DownpourCtrDymfAccessor::
                      DownpourCtrDymfFeatureValue::delta_score_index()];
      val->show = ptr_val[paddle::ps::DownpourCtrDymfAccessor::
                              DownpourCtrDymfFeatureValue::show_index()];
      val->clk = ptr_val[paddle::ps::DownpourCtrDymfAccessor::
                             DownpourCtrDymfFeatureValue::click_index()];
1108 1109
      val->slot = int(ptr_val[paddle::ps::DownpourCtrDymfAccessor::  // NOLINT
                              DownpourCtrDymfFeatureValue::slot_index()]);
Y
yaoxuefeng 已提交
1110 1111 1112 1113 1114
      val->lr = ptr_val[paddle::ps::DownpourCtrDymfAccessor::
                            DownpourCtrDymfFeatureValue::embed_w_index()];
      val->lr_g2sum =
          ptr_val[paddle::ps::DownpourCtrDymfAccessor::
                      DownpourCtrDymfFeatureValue::embed_g2sum_index()];
Y
yaoxuefeng 已提交
1115
      // TODO(xuefeng) set mf_dim while using DownpourCtrDymfAccessor
Y
yaoxuefeng 已提交
1116
      ptr_val[paddle::ps::DownpourCtrDymfAccessor::DownpourCtrDymfFeatureValue::
1117
                  mf_dim_index()] = float(mf_dim);  // NOLINT
Y
yaoxuefeng 已提交
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
      val->mf_dim = mf_dim;
      if (dim > 8) {  // CpuPS alreay expand as mf_dim
        val->mf_size = mf_dim + 1;
        for (int x = 0; x < val->mf_dim + 1; x++) {
          val->mf[x] = ptr_val[x + 8];
        }
      } else {
        val->mf_size = 0;
        for (int x = 0; x < val->mf_dim + 1; x++) {
          val->mf[x] = 0;
        }
      }
L
lxsbupt 已提交
1130 1131 1132 1133
      VLOG(5) << "build " << k << " : "
              << feature_value_accessor_.ParseToString(
                     val,
                     feature_value_accessor_.common_feature_value.Dim(mf_dim));
D
danleifeng 已提交
1134 1135
#endif
#ifdef PADDLE_WITH_PSCORE
L
lxsbupt 已提交
1136 1137
      void* val = reinterpret_cast<float*>(test_build_values +
                                           (k - start) * feature_value_size);
D
danleifeng 已提交
1138 1139 1140
      accessor_wrapper_ptr->BuildFill(
          val, device_dim_ptrs[k], cpu_table_accessor_, mf_dim);
#endif
Y
yaoxuefeng 已提交
1141
    }
L
lxsbupt 已提交
1142 1143 1144 1145 1146 1147 1148 1149
    task_info task;
    task.build_values = build_values;
    task.offset = start;
    task.device_id = i;
    task.multi_mf_dim = j;
    task.start = 0;
    task.end = real_len;
    cpu_reday_channels_[i]->Put(task);
Z
zmxdream 已提交
1150
  };
Y
yaoxuefeng 已提交
1151

L
lxsbupt 已提交
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
  auto build_dymf_hbm_pool = [this,
                              &gpu_task,
                              &accessor_wrapper_ptr,
                              &feature_keys_count](int i) {
    platform::CUDADeviceGuard guard(resource_->dev_id(i));
    // reset table
    this->HeterPs_->reset_table(i,
                                feature_keys_count[i],
                                optimizer_config_,
                                optimizer_config_,
                                infer_mode_);
    // insert hbm table
    std::vector<std::thread> threads(multi_mf_dim_);
Z
zmxdream 已提交
1165
    for (int j = 0; j < multi_mf_dim_; j++) {
L
lxsbupt 已提交
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
      auto& device_dim_keys = gpu_task->device_dim_keys_[i][j];
      size_t len = device_dim_keys.size();
      int mf_dim = this->index_dim_vec_[j];
      size_t feature_value_size =
          accessor_wrapper_ptr->GetFeatureValueSize(mf_dim);
      this->hbm_pools_[i * this->multi_mf_dim_ + j]->reset(len,
                                                           feature_value_size);

      auto build_ps_thread =
          [this, &gpu_task](
              int i, int j, size_t len, size_t feature_value_size) {
            auto& device_dim_keys = gpu_task->device_dim_keys_[i][j];
            this->HeterPs_->build_ps(
                i,
                device_dim_keys.data(),
                this->hbm_pools_[i * this->multi_mf_dim_ + j]->mem(),
                len,
                feature_value_size,
                500000,
                2);
            if (device_dim_keys.size() > 0) {
              VLOG(3) << "show table: " << i
                      << " table kv size: " << device_dim_keys.size()
                      << "dim: " << this->index_dim_vec_[j] << " len: " << len;
              HeterPs_->show_one_table(i);
            }
          };
      threads[j] = std::thread(build_ps_thread, i, j, len, feature_value_size);
    }
    // build feature table
1196
    if (slot_num_for_pull_feature_ > 0 &&
L
lxsbupt 已提交
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
        (FLAGS_gpugraph_storage_mode == paddle::framework::GpuGraphStorageMode::
                                            MEM_EMB_FEATURE_AND_GPU_GRAPH ||
         FLAGS_gpugraph_storage_mode ==
             paddle::framework::GpuGraphStorageMode::
                 SSD_EMB_AND_MEM_FEATURE_GPU_GRAPH)) {
      auto build_feature_table = [this, &gpu_task](int i) {
        auto gpu_graph_ptr = GraphGpuWrapper::GetInstance();
        std::vector<GpuPsCommGraphFea>* tmp =
            (std::vector<GpuPsCommGraphFea>*)gpu_task->sub_graph_feas;
        gpu_graph_ptr->build_gpu_graph_fea((*tmp)[i], i);
      };
      threads.push_back(std::thread(build_feature_table, i));
Z
zmxdream 已提交
1209
    }
Y
yaoxuefeng 已提交
1210

L
lxsbupt 已提交
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
    struct task_info task;
    while (cpu_reday_channels_[i]->Get(task)) {
      auto hbm = this->hbm_pools_[task.device_id * this->multi_mf_dim_ +
                                  task.multi_mf_dim]
                     ->mem();
      int mf_dim = this->index_dim_vec_[task.multi_mf_dim];
      size_t feature_value_size =
          accessor_wrapper_ptr->GetFeatureValueSize(mf_dim);
      auto hbm_start = hbm + task.offset * feature_value_size;
      CUDA_CHECK(
          cudaMemcpy(hbm_start,
                     task.build_values.get() + task.start * feature_value_size,
                     (task.end - task.start) * feature_value_size,
                     cudaMemcpyHostToDevice));
    }
    platform::Timer stagetime;
    stagetime.Start();
    for (std::thread& t : threads) {
      t.join();
    }
    stagetime.Pause();
1232
    VLOG(1) << "card: " << i
L
lxsbupt 已提交
1233 1234 1235
            << " BuildGPUTask build_ps async costs: " << stagetime.ElapsedSec()
            << " s.";
  };
Y
yaoxuefeng 已提交
1236

L
lxsbupt 已提交
1237 1238 1239 1240 1241
  std::vector<std::future<void>> cpu_task_futures;
  std::vector<std::future<void>> gpu_task_futures;

  int once_gpu_copy = 64 * 1024;
  threads.resize(device_num * multi_mf_dim_);
Z
zmxdream 已提交
1242
  for (int i = 0; i < device_num; i++) {
L
lxsbupt 已提交
1243 1244 1245
    cpu_reday_channels_[i]->Open();
    gpu_task_futures.emplace_back(
        hbm_thread_pool_[i]->enqueue(build_dymf_hbm_pool, i));
Z
zmxdream 已提交
1246
    for (int j = 0; j < multi_mf_dim_; j++) {
L
lxsbupt 已提交
1247 1248 1249 1250 1251 1252 1253 1254 1255
      auto& device_dim_keys = gpu_task->device_dim_keys_[i][j];
      size_t len = device_dim_keys.size();
      size_t start = 0;
      size_t end = 0;
      while (end < len) {
        start = end;
        end = end + once_gpu_copy < len ? (end + once_gpu_copy) : len;
        cpu_task_futures.emplace_back(cpu_work_pool_[i]->enqueue(
            build_dynamic_mf_func, i, j, start, end));
Z
zmxdream 已提交
1256
      }
Y
yaoxuefeng 已提交
1257
    }
Z
zmxdream 已提交
1258
  }
L
lxsbupt 已提交
1259 1260 1261 1262

  stagetime.Start();
  for (auto& f : cpu_task_futures) {
    f.wait();
Z
zmxdream 已提交
1263
  }
L
lxsbupt 已提交
1264 1265
  cpu_task_futures.clear();
  stagetime.Pause();
1266
  VLOG(1) << " BuildGPUTask build_dynamic_mf_func "
L
lxsbupt 已提交
1267
          << " cost " << stagetime.ElapsedSec() << " s.";
Y
yaoxuefeng 已提交
1268
  for (int i = 0; i < device_num; i++) {
L
lxsbupt 已提交
1269
    cpu_reday_channels_[i]->Close();
Y
yaoxuefeng 已提交
1270
  }
L
lxsbupt 已提交
1271 1272 1273
  stagetime.Start();
  for (auto& f : gpu_task_futures) {
    f.wait();
T
Thunderbrook 已提交
1274
  }
L
lxsbupt 已提交
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
  gpu_task_futures.clear();
  if (FLAGS_gpugraph_storage_mode == paddle::framework::GpuGraphStorageMode::
                                         MEM_EMB_FEATURE_AND_GPU_GRAPH ||
      FLAGS_gpugraph_storage_mode == paddle::framework::GpuGraphStorageMode::
                                         SSD_EMB_AND_MEM_FEATURE_GPU_GRAPH) {
    std::vector<GpuPsCommGraphFea>* tmp =
        (std::vector<GpuPsCommGraphFea>*)gpu_task->sub_graph_feas;
    delete tmp;
    gpu_task->sub_graph_feas = NULL;
  }
  stagetime.Pause();
1286
  VLOG(1) << "  build_dymf_hbm_pool "
L
lxsbupt 已提交
1287
          << " cost " << stagetime.ElapsedSec() << " s.";
1288 1289 1290 1291 1292 1293 1294 1295
}

void PSGPUWrapper::LoadIntoMemory(bool is_shuffle) {
  platform::Timer timer;
  VLOG(3) << "Begin LoadIntoMemory(), dataset[" << dataset_ << "]";
  timer.Start();
  dataset_->LoadIntoMemory();
  timer.Pause();
1296
  VLOG(1) << "LoadIntoMemory cost: " << timer.ElapsedSec() << "s";
L
lxsbupt 已提交
1297 1298 1299 1300 1301
  gpu_graph_mode_ = dataset_->GetGpuGraphMode();
  if (dataset_->GetMemoryDataSize() == 0) {
    VLOG(0) << "GetMemoryDataSize == 0";
    return;
  }
1302 1303 1304 1305
  // local shuffle
  if (is_shuffle) {
    dataset_->LocalShuffle();
  }
Y
yaoxuefeng 已提交
1306

L
lxsbupt 已提交
1307
  InitSlotInfo();
1308
#if defined(PADDLE_WITH_GPU_GRAPH) && defined(PADDLE_WITH_HETERPS)
L
lxsbupt 已提交
1309 1310 1311 1312
  if (FLAGS_gpugraph_storage_mode != GpuGraphStorageMode::WHOLE_HBM) {
    std::shared_ptr<HeterContext> gpu_task = gpu_task_pool_.Get();
    gpu_task->Reset();
    gpu_task->pass_id_ = (uint16_t)(dataset_->GetPassID());
1313
    data_ready_channel_->Put(std::make_pair(gpu_task, dataset_));
L
lxsbupt 已提交
1314 1315 1316
  } else if (hbm_sparse_table_initialized_ == false) {
    SparseTableToHbm();
  }
1317 1318 1319 1320
#else
  std::shared_ptr<HeterContext> gpu_task = gpu_task_pool_.Get();
  gpu_task->Reset();
  gpu_task->pass_id_ = (uint16_t)(dataset_->GetPassID());
1321
  data_ready_channel_->Put(std::make_pair(gpu_task, dataset_));
1322
#endif
1323 1324 1325 1326 1327
  VLOG(3) << "End LoadIntoMemory(), dataset[" << dataset_ << "]";
}

void PSGPUWrapper::start_build_thread() {
  running_ = true;
1328
  VLOG(3) << "start build CPU ps thread.";
1329
  pre_build_threads_ = std::thread([this] { pre_build_thread(); });
L
lxsbupt 已提交
1330
  buildpull_threads_ = std::thread([this] { build_pull_thread(); });
1331 1332
}

1333 1334
void PSGPUWrapper::pre_build_thread() {
  // prebuild: process load_data
1335
  while (running_) {
1336 1337
    std::pair<std::shared_ptr<HeterContext>, Dataset*> task =
        std::make_pair(nullptr, nullptr);
1338
    std::shared_ptr<HeterContext> gpu_task = nullptr;
1339
    if (!data_ready_channel_->Get(task)) {
1340 1341
      continue;
    }
1342
    gpu_task = task.first;
1343
    VLOG(3) << "thread PreBuildTask start.";
1344 1345 1346
    platform::Timer timer;
    timer.Start();
    // build cpu ps data process
1347
    PreBuildTask(gpu_task, task.second);
1348
    timer.Pause();
1349
    VLOG(1) << "thread PreBuildTask end, cost time: " << timer.ElapsedSec()
T
Thunderbrook 已提交
1350
            << " s";
1351 1352 1353 1354 1355
    buildcpu_ready_channel_->Put(gpu_task);
  }
  VLOG(3) << "build cpu thread end";
}

L
lxsbupt 已提交
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
void PSGPUWrapper::build_pull_thread() {
  while (running_) {
    std::shared_ptr<HeterContext> gpu_task = nullptr;
    if (!buildcpu_ready_channel_->Get(gpu_task)) {
      continue;
    }
    VLOG(3) << "thread build pull start.";
    platform::Timer timer;
    timer.Start();
    // build cpu ps data process
    BuildPull(gpu_task);
    if (multi_mf_dim_) {
      divide_to_device(gpu_task);
    }
    timer.Pause();
    VLOG(1) << "thread BuildPull end, cost time: " << timer.ElapsedSec() << "s";
    buildpull_ready_channel_->Put(gpu_task);
  }
  VLOG(3) << "build cpu thread end";
}

1377 1378 1379 1380 1381 1382 1383 1384
void PSGPUWrapper::build_task() {
  // build_task: build_pull + build_gputask
  std::shared_ptr<HeterContext> gpu_task = nullptr;
  // train end, gpu free
  if (!gpu_free_channel_->Get(gpu_task)) {
    return;
  }
  // ins and pre_build end
L
lxsbupt 已提交
1385
  if (!buildpull_ready_channel_->Get(gpu_task)) {
1386
    return;
1387
  }
1388

1389
  VLOG(1) << "PrepareGPUTask start.";
1390 1391
  platform::Timer timer;
  timer.Start();
L
lxsbupt 已提交
1392 1393 1394
  if (!multi_mf_dim_) {
    PrepareGPUTask(gpu_task);
  }
1395 1396
  BuildGPUTask(gpu_task);
  timer.Pause();
1397
  VLOG(1) << "PrepareGPUTask + BuildGPUTask end, cost time: "
L
lxsbupt 已提交
1398
          << timer.ElapsedSec() << "s";
1399 1400

  current_task_ = gpu_task;
1401 1402 1403 1404
}

void PSGPUWrapper::BeginPass() {
  platform::Timer timer;
W
wangzhen38 已提交
1405
#if defined(PADDLE_WITH_GPU_GRAPH) && defined(PADDLE_WITH_HETERPS)
L
lxsbupt 已提交
1406 1407 1408
  if (FLAGS_gpugraph_storage_mode == GpuGraphStorageMode::WHOLE_HBM) {
    return;
  }
W
wangzhen38 已提交
1409
#endif
1410 1411 1412 1413 1414
  timer.Start();
  if (current_task_) {
    PADDLE_THROW(
        platform::errors::Fatal("[BeginPass] current task is not ended."));
  }
1415

D
danleifeng 已提交
1416
  debug_gpu_memory_info("befor build task");
1417
  build_task();
D
danleifeng 已提交
1418
  debug_gpu_memory_info("after build task");
1419
  timer.Pause();
1420 1421 1422 1423 1424

  if (current_task_ == nullptr) {
    PADDLE_THROW(platform::errors::Fatal(
        "[BeginPass] after build_task, current task is not null."));
  }
D
danleifeng 已提交
1425
  if (FLAGS_gpugraph_dedup_pull_push_mode) {
1426
    VLOG(1) << "BeginPass end, cost time: " << timer.ElapsedSec()
D
danleifeng 已提交
1427 1428 1429
            << "s, enable pull push dedup mode="
            << FLAGS_gpugraph_dedup_pull_push_mode;
  } else {
1430
    VLOG(1) << "BeginPass end, cost time: " << timer.ElapsedSec() << "s";
D
danleifeng 已提交
1431
  }
1432 1433 1434
}

void PSGPUWrapper::EndPass() {
W
wangzhen38 已提交
1435
#if defined(PADDLE_WITH_GPU_GRAPH) && defined(PADDLE_WITH_HETERPS)
L
lxsbupt 已提交
1436 1437 1438
  if (FLAGS_gpugraph_storage_mode == GpuGraphStorageMode::WHOLE_HBM) {
    return;
  }
W
wangzhen38 已提交
1439
#endif
1440 1441 1442
  if (current_task_ == nullptr) {
    return;
  }
L
lxsbupt 已提交
1443 1444 1445 1446
  platform::Timer stagetime;
  stagetime.Start();
  HbmToSparseTable();
  stagetime.Pause();
1447
  VLOG(1) << "EndPass HbmToSparseTable cost time: " << stagetime.ElapsedSec()
L
lxsbupt 已提交
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
          << "s";

  gpu_task_pool_.Push(current_task_);
  current_task_ = nullptr;
  gpu_free_channel_->Put(current_task_);
  // fleet_ptr->pslib_ptr_->_worker_ptr->release_table_mutex(this->table_id_);
}

void PSGPUWrapper::SparseTableToHbm() {
  std::shared_ptr<HeterContext> gpu_task = gpu_task_pool_.Get();
  gpu_task->Reset();
  size_t device_num = heter_devices_.size();
  gpu_task->init(thread_keys_shard_num_, device_num, multi_mf_dim_);
  gpu_task->pass_id_ = (uint16_t)(dataset_->GetPassID());
  auto gpu_graph_ptr = GraphGpuWrapper::GetInstance();
1463
  auto node_to_id = gpu_graph_ptr->node_to_id;
L
lxsbupt 已提交
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
  auto edge_to_id = gpu_graph_ptr->edge_to_id;
  std::vector<uint64_t> vec_data = gpu_graph_ptr->get_graph_total_keys();

  thread_dim_keys_.resize(thread_keys_thread_num_);
  for (int i = 0; i < thread_keys_thread_num_; i++) {
    thread_dim_keys_[i].resize(thread_keys_shard_num_);
    for (int j = 0; j < thread_keys_shard_num_; j++) {
      thread_dim_keys_[i][j].resize(multi_mf_dim_);
    }
  }

  add_key_to_local(vec_data);
  add_key_to_gputask(gpu_task);
  BuildPull(gpu_task);
  if (!multi_mf_dim_) {
    PrepareGPUTask(gpu_task);
  } else {
    divide_to_device(gpu_task);
  }
  BuildGPUTask(gpu_task);
  current_task_ = gpu_task;
  hbm_sparse_table_initialized_ = true;
}

void PSGPUWrapper::HbmToSparseTable() {
  // hbm no update not need dump
  if (grad_push_count_ == 0) {
    return;
  }
  grad_push_count_ = 0;

1495 1496 1497 1498 1499 1500
  if (!current_task_) {
    PADDLE_THROW(
        platform::errors::Fatal("[EndPass] current task has been ended."));
  }
  size_t keysize_max = 0;
  // in case of feasign_num = 0, skip dump_to_cpu
Y
yaoxuefeng 已提交
1501

1502
  for (size_t i = 0; i < heter_devices_.size(); i++) {
Y
yaoxuefeng 已提交
1503 1504 1505 1506 1507
    for (int j = 0; j < multi_mf_dim_; j++) {
      keysize_max =
          std::max(keysize_max, current_task_->device_dim_keys_[i][j].size());
    }
  }
D
danleifeng 已提交
1508
  auto accessor_wrapper_ptr =
D
danleifeng 已提交
1509
      GlobalAccessorFactory::GetInstance().GetAccessorWrapper();
L
lxsbupt 已提交
1510 1511 1512 1513 1514 1515

  int once_cpu_num = 16 * 1024;
  int once_gpu_copy = 8 * once_cpu_num;

  auto dump_pool_to_cpu_func = [this, &accessor_wrapper_ptr, once_cpu_num](
                                   int i, int j, size_t start, size_t end) {
Y
yaoxuefeng 已提交
1516 1517
    PADDLE_ENFORCE_GPU_SUCCESS(cudaSetDevice(this->resource_->dev_id(i)));
    auto& hbm_pool = this->hbm_pools_[i * this->multi_mf_dim_ + j];
L
lxsbupt 已提交
1518
    size_t real_len = end - start;
1519
    // ============ multi-thread process feasign============
Y
yaoxuefeng 已提交
1520 1521
    int mf_dim = this->index_dim_vec_[j];
    size_t feature_value_size =
D
danleifeng 已提交
1522
        accessor_wrapper_ptr->GetFeatureValueSize(mf_dim);
L
lxsbupt 已提交
1523 1524 1525 1526 1527 1528

    std::shared_ptr<char> build_values(new char[feature_value_size * real_len],
                                       [](char* p) { delete[] p; });
    uint64_t offset = start * feature_value_size;
    char* test_build_values = build_values.get();

1529 1530 1531 1532
    cudaMemcpy(test_build_values,
               hbm_pool->mem() + offset,
               feature_value_size * real_len,
               cudaMemcpyDeviceToHost);
L
lxsbupt 已提交
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
    for (size_t k = 0; k * once_cpu_num < real_len; k++) {
      struct task_info task;
      task.build_values = build_values;
      task.offset = start;
      task.device_id = i;
      task.multi_mf_dim = j;
      task.start = k * once_cpu_num;
      task.end = (k + 1) * once_cpu_num < real_len ? ((k + 1) * once_cpu_num)
                                                   : (real_len);
      cpu_reday_channels_[i]->Put(task);
    }
  };
  auto cpu_func = [this, &accessor_wrapper_ptr](int j) {
    struct task_info task;
    while (cpu_reday_channels_[j]->Get(task)) {
      auto& device_keys =
          this->current_task_
              ->device_dim_keys_[task.device_id][task.multi_mf_dim];
      char* test_build_values = task.build_values.get();
      int mf_dim = this->index_dim_vec_[task.multi_mf_dim];
      size_t feature_value_size =
          accessor_wrapper_ptr->GetFeatureValueSize(mf_dim);
      uint64_t unuse_key = std::numeric_limits<uint64_t>::max();
      for (int i = task.start; i < task.end; ++i) {
        if (device_keys[i + task.offset] == unuse_key) {
          continue;
        }
        size_t local_offset = i * feature_value_size;
        float* gpu_val =
            reinterpret_cast<float*>(test_build_values + local_offset);
1563
#ifdef PADDLE_WITH_PSLIB
1564
        // TODO(lxsbupt): PSLIB DumpFill
D
danleifeng 已提交
1565 1566
#endif
#ifdef PADDLE_WITH_PSCORE
L
lxsbupt 已提交
1567
        accessor_wrapper_ptr->DumpFill(gpu_val, cpu_table_accessor_, mf_dim);
D
danleifeng 已提交
1568
#endif
L
lxsbupt 已提交
1569
      }
Y
yaoxuefeng 已提交
1570 1571
    }
  };
L
lxsbupt 已提交
1572 1573 1574 1575 1576 1577
  platform::Timer timer;
  timer.Start();
  std::vector<std::future<void>> cpu_task_futures;
  std::vector<std::future<void>> gpu_task_futures;
  size_t thread_num = 16;
  size_t device_num = heter_devices_.size();
Y
yaoxuefeng 已提交
1578
  if (multi_mf_dim_) {
1579
    VLOG(1) << "psgpu wrapper dump pool: multi_mf_dim_: " << multi_mf_dim_;
Y
yaoxuefeng 已提交
1580
    for (size_t i = 0; i < device_num; i++) {
L
lxsbupt 已提交
1581
      cpu_reday_channels_[i]->Open();
Y
yaoxuefeng 已提交
1582
      for (int j = 0; j < multi_mf_dim_; j++) {
L
lxsbupt 已提交
1583 1584 1585 1586 1587 1588 1589 1590 1591
        auto& device_keys = this->current_task_->device_dim_keys_[i][j];
        size_t len = device_keys.size();
        size_t start = 0;
        size_t end = 0;
        while (end < len) {
          start = end;
          end = end + once_gpu_copy < len ? (end + once_gpu_copy) : len;
          gpu_task_futures.emplace_back(hbm_thread_pool_[i]->enqueue(
              dump_pool_to_cpu_func, i, j, start, end));
1592
        }
Y
yaoxuefeng 已提交
1593
      }
L
lxsbupt 已提交
1594 1595 1596
      for (size_t j = 0; j < thread_num; j++) {
        cpu_task_futures.emplace_back(cpu_work_pool_[i]->enqueue(cpu_func, i));
      }
Y
yaoxuefeng 已提交
1597
    }
1598
  }
L
lxsbupt 已提交
1599 1600 1601 1602
  for (auto& f : gpu_task_futures) {
    f.wait();
  }
  timer.Pause();
1603
  VLOG(1) << " EndPass  dump_pool_to_cpu_func "
L
lxsbupt 已提交
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
          << " cost " << timer.ElapsedSec() << " s.";
  for (size_t i = 0; i < device_num; i++) {
    cpu_reday_channels_[i]->Close();
  }
  gpu_task_futures.clear();
  timer.Start();
  for (auto& f : cpu_task_futures) {
    f.wait();
  }
  cpu_task_futures.clear();
  timer.Pause();
1615
  VLOG(1) << " EndPass  cpu_func "
L
lxsbupt 已提交
1616
          << " cost " << timer.ElapsedSec() << " s.";
1617 1618 1619
  if (keysize_max != 0) {
    HeterPs_->end_pass();
  }
L
lxsbupt 已提交
1620
}
1621

L
lxsbupt 已提交
1622 1623 1624
void PSGPUWrapper::DumpToMem() {
  if (FLAGS_gpugraph_storage_mode == GpuGraphStorageMode::WHOLE_HBM) {
    this->HbmToSparseTable();
Y
yaoxuefeng 已提交
1625
  }
T
Thunderbrook 已提交
1626 1627 1628 1629 1630 1631 1632 1633
}

void PSGPUWrapper::PullSparse(const paddle::platform::Place& place,
                              const int table_id,
                              const std::vector<const uint64_t*>& keys,
                              const std::vector<float*>& values,
                              const std::vector<int64_t>& slot_lengths,
                              const int hidden_size) {
D
danleifeng 已提交
1634 1635
  VLOG(0) << "Warning:: recommand use pull_gpups_sparse op instead. This "
             "PullSparse is not used.";
Y
yaoxuefeng 已提交
1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
}

void PSGPUWrapper::PullSparse(const paddle::platform::Place& place,
                              const int table_id,
                              const std::vector<const uint64_t*>& keys,
                              const std::vector<float*>& values,
                              const std::vector<int64_t>& slot_lengths,
                              const std::vector<int>& slot_dim,
                              const int hidden_size) {
  VLOG(3) << "Begine Gpu Ps PullSparse";
  platform::Timer all_timer;
  platform::Timer pull_gpups_timer;
  all_timer.Start();

D
danleifeng 已提交
1650
  auto accessor_wrapper_ptr =
D
danleifeng 已提交
1651 1652 1653
      GlobalAccessorFactory::GetInstance().GetAccessorWrapper();
  size_t feature_value_size =
      accessor_wrapper_ptr->GetPullValueSize(max_mf_dim_);
D
danleifeng 已提交
1654
  VLOG(3) << "PullSparse max_dim:" << max_mf_dim_
D
danleifeng 已提交
1655
          << " pull_feature_value_size:" << pull_type_size_;
Y
yaoxuefeng 已提交
1656 1657 1658 1659 1660

  if (platform::is_cpu_place(place)) {
    PADDLE_THROW(platform::errors::Unimplemented(
        "Warning:: CPUPlace is not supported in GpuPs now."));
  } else if (platform::is_gpu_place(place)) {
D
danleifeng 已提交
1661
#ifdef PADDLE_WITH_CUDA
Y
yaoxuefeng 已提交
1662 1663
    int device_id = place.GetDeviceId();
    int devid_2_index = HeterPs_->get_index_by_devid(device_id);
D
danleifeng 已提交
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
    if (FLAGS_gpugraph_dedup_pull_push_mode > 0) {
      auto& dev = device_caches_[devid_2_index];
      int slot_num = static_cast<int>(slot_lengths.size());
      std::vector<int64_t> slot_lengths_lod;
      slot_lengths_lod.reserve(slot_num + 1);
      slot_lengths_lod.push_back(0);

      int64_t total_length = 0;
      for (int i = 0; i < slot_num; ++i) {
        total_length += slot_lengths[i];
        slot_lengths_lod.push_back(total_length);
      }
      dev.total_key_length = total_length;
      VLOG(3) << "[" << device_id << "]Begin copy keys, key_num["
              << total_length << "] dedup mode";

1680
      auto stream = dynamic_cast<phi::GPUContext*>(
D
danleifeng 已提交
1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
                        platform::DeviceContextPool::Instance().Get(place))
                        ->stream();

      uint64_t* total_keys = dev.keys_tensor.mutable_data<uint64_t>(
          (total_length * 3) * sizeof(uint64_t), place);

      int* gpu_slot_dims = dev.dims_tensor.mutable_data<int>(
          slot_dim.size() * sizeof(int), place);
      uint64_t** gpu_keys = dev.keys_ptr_tensor.mutable_data<uint64_t*>(
          keys.size() * sizeof(uint64_t*), place);

      int64_t* slot_lens = dev.slot_lens.mutable_data<int64_t>(
          (slot_num + 1) * sizeof(int64_t), place);
      cudaMemcpyAsync(gpu_keys,
                      keys.data(),
                      keys.size() * sizeof(uint64_t*),
                      cudaMemcpyHostToDevice,
                      stream);
      cudaMemcpyAsync(slot_lens,
                      slot_lengths_lod.data(),
                      slot_lengths_lod.size() * sizeof(int64_t),
                      cudaMemcpyHostToDevice,
                      stream);

      cudaMemcpyAsync(gpu_slot_dims,
                      slot_dim.data(),
                      slot_dim.size() * sizeof(int),
                      cudaMemcpyHostToDevice,
                      stream);
      float** gpu_values = dev.values_ptr_tensor.mutable_data<float*>(
          values.size() * sizeof(float*), place);
      cudaMemcpyAsync(gpu_values,
                      values.data(),
                      values.size() * sizeof(float*),
                      cudaMemcpyHostToDevice,
                      stream);

      int* key2slot = dev.keys2slot.mutable_data<int>(
          (total_length * 5) * sizeof(int), place);

      this->CopyKeys(place,
                     gpu_keys,
                     total_keys,
                     slot_lens,
                     slot_num,
                     static_cast<int>(total_length),
                     key2slot);

      uint32_t* d_restore_idx =
          reinterpret_cast<uint32_t*>(&key2slot[total_length]);
      uint32_t* d_sorted_idx =
          reinterpret_cast<uint32_t*>(&d_restore_idx[total_length]);
      uint32_t* d_offset =
          reinterpret_cast<uint32_t*>(&d_sorted_idx[total_length]);
      uint32_t* d_merged_cnts =
          reinterpret_cast<uint32_t*>(&d_offset[total_length]);
      uint64_t* d_merged_keys =
          reinterpret_cast<uint64_t*>(&total_keys[total_length]);
      uint64_t* d_sorted_keys =
          reinterpret_cast<uint64_t*>(&d_merged_keys[total_length]);

      int dedup_size = HeterPs_->dedup_keys_and_fillidx(
          devid_2_index,
          static_cast<int>(total_length),
          total_keys,     // input
          d_merged_keys,  // output
          d_sorted_keys,  // sort keys
          d_restore_idx,  // pull fill idx
          d_sorted_idx,   // sort old idx
          d_offset,       // offset
          d_merged_cnts,
          FLAGS_gpugraph_dedup_pull_push_mode & 0x02);
      //      printf("device %d, end dedup_keys_and_fillidx total %d, "
      //              "dedup_size %d, slot num: %d, value size: %d\n",
      //             device_id, int(total_length), dedup_size, slot_num,
      //             int(feature_value_size));

      PADDLE_ENFORCE_GT(dedup_size,
                        0,
                        platform::errors::PreconditionNotMet(
                            "dedup keys need more than zero failed in BoxPS."));
      dev.dedup_key_length = dedup_size;

      int64_t total_bytes = dedup_size * feature_value_size;
      float* total_values_gpu =
          dev.pull_push_tensor.mutable_data<float>(total_bytes, place);
      pull_gpups_timer.Start();
      HeterPs_->pull_sparse(
          devid_2_index, d_merged_keys, total_values_gpu, dedup_size);

      // values.size() not sure equal slot_num
      accessor_wrapper_ptr->CopyForPull(place,
                                        total_keys,
                                        gpu_values,
                                        total_values_gpu,
                                        slot_lens,
                                        key2slot,
                                        max_mf_dim_ + 3,
                                        total_length,
                                        gpu_slot_dims,
                                        d_restore_idx,
                                        feature_value_size);
    } else {
      size_t total_length =
          std::accumulate(slot_lengths.begin(), slot_lengths.end(), 0UL);
      auto buf = memory::Alloc(place, total_length * feature_value_size);
      float* total_values_gpu = reinterpret_cast<float*>(buf->ptr());
      VLOG(3) << "Begin copy keys, key_num[" << total_length << "]";
1789
      phi::DenseTensor& total_keys_tensor = keys_tensor[devid_2_index];
D
danleifeng 已提交
1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
      uint64_t* total_keys =
          reinterpret_cast<uint64_t*>(total_keys_tensor.mutable_data<int64_t>(
              {int64_t(total_length), 1}, place));
      // construct slot_level lod info
      auto slot_lengths_lod = slot_lengths;
      for (size_t i = 1; i < slot_lengths_lod.size(); i++) {
        slot_lengths_lod[i] += slot_lengths_lod[i - 1];
      }
      auto buf_key = memory::Alloc(place, keys.size() * sizeof(uint64_t*));
      auto buf_length =
          memory::Alloc(place, slot_lengths.size() * sizeof(int64_t));
      uint64_t** gpu_keys = reinterpret_cast<uint64_t**>(buf_key->ptr());
      int64_t* gpu_len = reinterpret_cast<int64_t*>(buf_length->ptr());
      cudaMemcpy(gpu_keys,
                 keys.data(),
                 keys.size() * sizeof(uint64_t*),
                 cudaMemcpyHostToDevice);
      cudaMemcpy(gpu_len,
                 slot_lengths_lod.data(),
                 slot_lengths.size() * sizeof(int64_t),
                 cudaMemcpyHostToDevice);

      auto buf_dim = memory::Alloc(place, slot_dim.size() * sizeof(int));
      int* gpu_dim = reinterpret_cast<int*>(buf_dim->ptr());
      cudaMemcpy(gpu_dim,
                 slot_dim.data(),
                 slot_dim.size() * sizeof(int),
                 cudaMemcpyHostToDevice);

      this->CopyKeys(place,
                     gpu_keys,
                     total_keys,
                     gpu_len,
                     static_cast<int>(slot_lengths.size()),
                     static_cast<int>(total_length));
      VLOG(3) << "Begin call PullSparseGPU in GPUPS, dev: " << devid_2_index
              << " len: " << total_length;

      pull_gpups_timer.Start();
      HeterPs_->pull_sparse(
          devid_2_index, total_keys, total_values_gpu, total_length);

      VLOG(3) << "Begin Copy result to tensor, total_length[" << total_length
              << "]";

      accessor_wrapper_ptr->CopyForPull(place,
                                        gpu_keys,
                                        values,
                                        total_values_gpu,
                                        gpu_len,
                                        static_cast<int>(slot_lengths.size()),
                                        hidden_size,
                                        total_length,
                                        gpu_dim,
                                        feature_value_size);
Y
yaoxuefeng 已提交
1845 1846
    }
    pull_gpups_timer.Pause();
D
danleifeng 已提交
1847
#endif
F
Fan Zhang 已提交
1848 1849
  } else if (platform::is_xpu_place(place)) {
#ifdef PADDLE_WITH_XPU_KP
D
danleifeng 已提交
1850 1851 1852 1853 1854 1855
    VLOG(3) << "Begine Xpu Ps PullSparse";
    size_t total_length =
        std::accumulate(slot_lengths.begin(), slot_lengths.end(), 0UL);
    FeatureValue* total_values_gpu = nullptr;
    xpu_malloc(reinterpret_cast<void**>(&total_values_gpu),
               total_length * feature_value_size);
F
Fan Zhang 已提交
1856 1857 1858
    VLOG(3) << "Begin copy keys, key_num[" << total_length << "]";
    int device_id = place.GetDeviceId();
    int devid_2_index = HeterPs_->get_index_by_devid(device_id);
1859
    phi::DenseTensor& total_keys_tensor = keys_tensor[devid_2_index];
D
danleifeng 已提交
1860 1861 1862
    uint64_t* total_keys =
        reinterpret_cast<uint64_t*>(total_keys_tensor.mutable_data<int64_t>(
            {int64_t(total_length), 1}, place));
F
Fan Zhang 已提交
1863 1864 1865 1866 1867 1868 1869

    // construct slot_level lod info
    auto slot_lengths_lod = slot_lengths;
    for (size_t i = 1; i < slot_lengths_lod.size(); i++) {
      slot_lengths_lod[i] += slot_lengths_lod[i - 1];
    }

F
Fan Zhang 已提交
1870 1871 1872 1873 1874
    auto buf_key = memory::Alloc(place, keys.size() * sizeof(uint64_t*));
    auto buf_length =
        memory::Alloc(place, slot_lengths.size() * sizeof(int64_t));
    uint64_t** xpu_keys = reinterpret_cast<uint64_t**>(buf_key->ptr());
    int64_t* xpu_len = reinterpret_cast<int64_t*>(buf_length->ptr());
1875 1876
    PADDLE_ENFORCE_XPU_SUCCESS(xpu_memcpy(xpu_keys,
                                          keys.data(),
F
Fan Zhang 已提交
1877 1878
                                          keys.size() * sizeof(uint64_t*),
                                          XPU_HOST_TO_DEVICE));
1879 1880
    PADDLE_ENFORCE_XPU_SUCCESS(xpu_memcpy(xpu_len,
                                          slot_lengths_lod.data(),
F
Fan Zhang 已提交
1881 1882 1883
                                          slot_lengths.size() * sizeof(int64_t),
                                          XPU_HOST_TO_DEVICE));

1884 1885 1886 1887
    this->CopyKeys(place,
                   xpu_keys,
                   total_keys,
                   xpu_len,
F
Fan Zhang 已提交
1888 1889 1890 1891 1892
                   static_cast<int>(slot_lengths.size()),
                   static_cast<int>(total_length));
    VLOG(3) << "Begin call PullSparseGPU in GPUPS, dev: " << devid_2_index
            << " len: " << total_length;
    pull_gpups_timer.Start();
1893 1894 1895
    HeterPs_->pull_sparse(devid_2_index,
                          total_keys,
                          total_values_gpu,
F
Fan Zhang 已提交
1896 1897 1898 1899 1900
                          static_cast<int>(total_length));
    pull_gpups_timer.Pause();

    VLOG(3) << "Begin Copy result to tensor, total_length[" << total_length
            << "]";
D
danleifeng 已提交
1901 1902 1903 1904 1905 1906 1907 1908
    accessor_wrapper_ptr->CopyForPull(place,
                                      xpu_keys,
                                      values,
                                      total_values_gpu,
                                      xpu_len,
                                      static_cast<int>(slot_lengths.size()),
                                      hidden_size,
                                      total_length,
D
danleifeng 已提交
1909
                                      feature_value_size);
F
Fan Zhang 已提交
1910
#endif
T
Thunderbrook 已提交
1911 1912
  } else {
    PADDLE_THROW(platform::errors::PreconditionNotMet(
F
Fan Zhang 已提交
1913
        "GpuPs/XpuPs: PullSparse Only Support CUDAPlace or XPUPlace Now."));
T
Thunderbrook 已提交
1914 1915
  }
  all_timer.Pause();
1916
  VLOG(3) << "GpuPs PullSparse total costs: " << all_timer.ElapsedSec()
T
Thunderbrook 已提交
1917 1918 1919 1920 1921 1922 1923 1924 1925 1926
          << " s, of which GPUPS costs: " << pull_gpups_timer.ElapsedSec()
          << " s";
  VLOG(3) << "End PullSparse";
}

void PSGPUWrapper::PushSparseGrad(const paddle::platform::Place& place,
                                  const int table_id,
                                  const std::vector<const uint64_t*>& keys,
                                  const std::vector<const float*>& grad_values,
                                  const std::vector<int64_t>& slot_lengths,
1927 1928
                                  const int hidden_size,
                                  const int batch_size) {
L
lxsbupt 已提交
1929
  ++grad_push_count_;
T
Thunderbrook 已提交
1930 1931 1932
  platform::Timer all_timer;
  platform::Timer push_gpups_timer;
  all_timer.Start();
D
danleifeng 已提交
1933
  auto accessor_wrapper_ptr =
D
danleifeng 已提交
1934
      GlobalAccessorFactory::GetInstance().GetAccessorWrapper();
D
danleifeng 已提交
1935
  size_t grad_value_size = accessor_wrapper_ptr->GetPushValueSize(max_mf_dim_);
D
danleifeng 已提交
1936

T
Thunderbrook 已提交
1937 1938 1939 1940
  if (platform::is_cpu_place(place)) {
    PADDLE_THROW(platform::errors::Unimplemented(
        "Warning:: CPUPlace is not supported in GPUPS now."));
  } else if (platform::is_gpu_place(place)) {
F
Fan Zhang 已提交
1941
#ifdef PADDLE_WITH_CUDA
1942
    int device_id = place.GetDeviceId();
T
Thunderbrook 已提交
1943
    int devid_2_index = HeterPs_->get_index_by_devid(device_id);
D
danleifeng 已提交
1944 1945 1946 1947 1948 1949
    if (FLAGS_gpugraph_dedup_pull_push_mode > 0) {
      auto& dev = device_caches_[devid_2_index];
      int64_t total_length = dev.total_key_length;
      VLOG(3) << "Begin push sparse, key_num[" << total_length
              << "] dedup mode, device:" << device_id << ", index"
              << devid_2_index;
1950
      auto stream = dynamic_cast<phi::GPUContext*>(
D
danleifeng 已提交
1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964
                        platform::DeviceContextPool::Instance().Get(place))
                        ->stream();
      uint64_t* total_keys = dev.keys_tensor.data<uint64_t>();
      int* slot_dims = dev.dims_tensor.data<int>();
      int slot_num = static_cast<int>(slot_lengths.size());
      if (!dev.d_slot_vector.IsInitialized()) {
        int* buf_slot_vector =
            dev.d_slot_vector.mutable_data<int>(slot_num * sizeof(int), place);
        cudaMemcpyAsync(buf_slot_vector,
                        slot_vector_.data(),
                        slot_num * sizeof(int),
                        cudaMemcpyHostToDevice,
                        stream);
      }
T
Thunderbrook 已提交
1965

D
danleifeng 已提交
1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
      const int64_t* slot_lens = dev.slot_lens.data<int64_t>();
      const int* d_slot_vector = dev.d_slot_vector.data<int>();
      const int* key2slot = dev.keys2slot.data<int>();
      float** gpu_values = dev.values_ptr_tensor.data<float*>();
      cudaMemcpyAsync(gpu_values,
                      grad_values.data(),
                      grad_values.size() * sizeof(float*),
                      cudaMemcpyHostToDevice,
                      stream);

      uint64_t* d_merged_keys = &total_keys[total_length];

      int64_t dedup_size = dev.dedup_key_length;
      int64_t total_bytes = dedup_size * grad_value_size;
      float* total_grad_values_gpu =
          dev.pull_push_tensor.mutable_data<float>(total_bytes, place);
      // dedup rate more than 3
      if (total_length > dedup_size * 3) {
        const uint32_t* d_restore_idx =
            reinterpret_cast<const uint32_t*>(&key2slot[total_length]);
        accessor_wrapper_ptr->CopyForPush(place,
                                          total_keys,
                                          gpu_values,
                                          total_grad_values_gpu,
                                          d_slot_vector,
                                          slot_lens,
                                          max_mf_dim_ + 3,
                                          total_length,
                                          dedup_size,
                                          batch_size,
                                          slot_dims,
                                          key2slot,
                                          d_restore_idx,
                                          grad_value_size);
      } else {
        const uint32_t* d_sorted_idx =
            reinterpret_cast<const uint32_t*>(&key2slot[total_length * 2]);
        const uint32_t* d_offset =
            reinterpret_cast<const uint32_t*>(&d_sorted_idx[total_length]);
        const uint32_t* d_merged_cnts =
            reinterpret_cast<const uint32_t*>(&d_offset[total_length]);
        accessor_wrapper_ptr->CopyForPush(place,
                                          d_merged_keys,
                                          gpu_values,
                                          total_grad_values_gpu,
                                          d_slot_vector,
                                          slot_lens,
                                          max_mf_dim_ + 3,
                                          total_length,
                                          dedup_size,
                                          batch_size,
                                          slot_dims,
                                          key2slot,
                                          d_sorted_idx,
                                          d_offset,
                                          d_merged_cnts,
                                          grad_value_size);
      }

      push_gpups_timer.Start();
      HeterPs_->push_sparse(devid_2_index,
                            d_merged_keys,
                            total_grad_values_gpu,
                            static_cast<int>(dedup_size));
    } else {
      int64_t total_length =
          std::accumulate(slot_lengths.begin(), slot_lengths.end(), 0UL);
      VLOG(3) << "Begin GPUPS PushSparseGrad";

      auto buf = memory::Alloc(place, total_length * grad_value_size);
      VLOG(3) << "Push Sparse Max mf dimention: " << max_mf_dim_
              << "grad_value_size:" << grad_value_size;
      float* total_grad_values_gpu = reinterpret_cast<float*>(buf->ptr());

2040
      phi::DenseTensor& total_keys_tensor = keys_tensor[devid_2_index];
D
danleifeng 已提交
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062
      uint64_t* total_keys =
          reinterpret_cast<uint64_t*>(total_keys_tensor.data<int64_t>());
      VLOG(3) << "Begin copy grad tensor to gpups struct";

      accessor_wrapper_ptr->CopyForPush(place,
                                        grad_values,
                                        total_grad_values_gpu,
                                        slot_lengths,
                                        total_length,
                                        batch_size,
                                        grad_value_size,
                                        slot_vector_,
                                        slot_mf_dim_vector_);

      VLOG(3) << "Begin call PushSparseGPU in GPUPS, dev: " << devid_2_index
              << " len: " << total_length;
      push_gpups_timer.Start();
      HeterPs_->push_sparse(devid_2_index,
                            total_keys,
                            total_grad_values_gpu,
                            static_cast<int>(total_length));
    }
T
Thunderbrook 已提交
2063
    push_gpups_timer.Pause();
F
Fan Zhang 已提交
2064
#endif
F
Fan Zhang 已提交
2065
  } else if (platform::is_xpu_place(place)) {
F
Fan Zhang 已提交
2066
#ifdef PADDLE_WITH_XPU_KP
F
Fan Zhang 已提交
2067 2068
    int device_id = place.GetDeviceId();
    int devid_2_index = HeterPs_->get_index_by_devid(device_id);
D
danleifeng 已提交
2069 2070 2071 2072 2073 2074 2075 2076
    int64_t total_length =
        std::accumulate(slot_lengths.begin(), slot_lengths.end(), 0UL);
    VLOG(3) << "Begin GPUPS PushSparseGrad";

    auto buf = memory::Alloc(place, total_length * grad_value_size);
    VLOG(3) << "Push Sparse Max mf dimention: " << max_mf_dim_
            << "grad_value_size:" << grad_value_size;
    float* total_grad_values_gpu = reinterpret_cast<float*>(buf->ptr());
2077
    phi::DenseTensor& total_keys_tensor = keys_tensor[devid_2_index];
F
Fan Zhang 已提交
2078
    uint64_t* total_keys =
D
danleifeng 已提交
2079
        reinterpret_cast<uint64_t*>(total_keys_tensor.data<int64_t>());
F
Fan Zhang 已提交
2080
    VLOG(3) << "Begin copy grad tensor to xpups struct";
D
danleifeng 已提交
2081 2082 2083 2084 2085 2086 2087 2088
    accessor_wrapper_ptr->CopyForPush(place,
                                      grad_values,
                                      total_grad_values_gpu,
                                      slot_lengths,
                                      hidden_size,
                                      total_length,
                                      batch_size,
                                      slot_vector_);
F
Fan Zhang 已提交
2089 2090 2091 2092

    VLOG(3) << "Begin call PushSparseXPU in XPUPS, dev: " << devid_2_index
            << " len: " << total_length;
    push_gpups_timer.Start();
2093 2094 2095
    HeterPs_->push_sparse(devid_2_index,
                          total_keys,
                          total_grad_values_gpu,
F
Fan Zhang 已提交
2096 2097
                          static_cast<int>(total_length));
    push_gpups_timer.Pause();
F
Fan Zhang 已提交
2098
#endif
T
Thunderbrook 已提交
2099 2100 2101 2102 2103
  } else {
    PADDLE_THROW(platform::errors::PreconditionNotMet(
        "GPUPS: PushSparseGrad Only Support CUDAPlace Now."));
  }
  all_timer.Pause();
Y
yaoxuefeng 已提交
2104 2105
  time_3 += all_timer.ElapsedSec();
  time_4 += push_gpups_timer.ElapsedSec();
2106
  VLOG(3) << "PushSparseGrad total cost: " << all_timer.ElapsedSec()
T
Thunderbrook 已提交
2107 2108 2109 2110 2111
          << " s, of which GPUPS cost: " << push_gpups_timer.ElapsedSec()
          << " s";
  VLOG(3) << "End PushSparseGrad";
}

D
danleifeng 已提交
2112
}  // namespace framework
T
Thunderbrook 已提交
2113 2114
}  // end namespace paddle
#endif