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

15
#include "paddle/fluid/distributed/ps/table/common_graph_table.h"
16

S
seemingwang 已提交
17
#include <time.h>
18

S
seemingwang 已提交
19
#include <algorithm>
20
#include <chrono>
S
seemingwang 已提交
21 22
#include <set>
#include <sstream>
23

S
seemingwang 已提交
24
#include "paddle/fluid/distributed/common/utils.h"
25
#include "paddle/fluid/distributed/ps/table/graph/graph_node.h"
26
#include "paddle/fluid/framework/generator.h"
S
seemingwang 已提交
27 28
#include "paddle/fluid/string/printf.h"
#include "paddle/fluid/string/string_helper.h"
29

S
seemingwang 已提交
30 31 32
namespace paddle {
namespace distributed {

33
#ifdef PADDLE_WITH_HETERPS
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
int32_t GraphTable::Load_to_ssd(const std::string &path,
                                const std::string &param) {
  bool load_edge = (param[0] == 'e');
  bool load_node = (param[0] == 'n');
  if (load_edge) {
    bool reverse_edge = (param[1] == '<');
    std::string edge_type = param.substr(2);
    return this->load_edges_to_ssd(path, reverse_edge, edge_type);
  }
  if (load_node) {
    std::string node_type = param.substr(1);
    return this->load_nodes(path, node_type);
  }
  return 0;
}

50
paddle::framework::GpuPsCommGraph GraphTable::make_gpu_ps_graph(
51
    int idx, std::vector<int64_t> ids) {
52 53 54 55 56 57 58 59
  std::vector<std::vector<int64_t>> bags(task_pool_size_);
  for (auto x : ids) {
    int location = x % shard_num % task_pool_size_;
    bags[location].push_back(x);
  }
  std::vector<std::future<int>> tasks;
  std::vector<int64_t> edge_array[task_pool_size_];
  std::vector<paddle::framework::GpuPsGraphNode> node_array[task_pool_size_];
60
  for (size_t i = 0; i < bags.size(); i++) {
61 62 63
    if (bags[i].size() > 0) {
      tasks.push_back(_shards_task_pool[i]->enqueue([&, i, this]() -> int {
        paddle::framework::GpuPsGraphNode x;
64
        for (size_t j = 0; j < bags[i].size(); j++) {
65
          Node *v = find_node(0, idx, bags[i][j]);
66 67 68 69 70 71 72 73 74
          x.node_id = bags[i][j];
          if (v == NULL) {
            x.neighbor_size = 0;
            x.neighbor_offset = 0;
            node_array[i].push_back(x);
          } else {
            x.neighbor_size = v->get_neighbor_size();
            x.neighbor_offset = edge_array[i].size();
            node_array[i].push_back(x);
75
            for (size_t k = 0; k < x.neighbor_size; k++) {
76 77 78 79 80 81 82 83 84 85
              edge_array[i].push_back(v->get_neighbor_id(k));
            }
          }
        }
        return 0;
      }));
    }
  }
  for (int i = 0; i < (int)tasks.size(); i++) tasks[i].get();
  paddle::framework::GpuPsCommGraph res;
S
seemingwang 已提交
86
  int64_t tot_len = 0;
87
  for (int i = 0; i < task_pool_size_; i++) {
88 89 90 91 92 93
    tot_len += edge_array[i].size();
  }
  // res.neighbor_size = tot_len;
  // res.node_size = ids.size();
  // res.neighbor_list = new int64_t[tot_len];
  // res.node_list = new paddle::framework::GpuPsGraphNode[ids.size()];
S
seemingwang 已提交
94 95
  res.init_on_cpu(tot_len, ids.size());
  int64_t offset = 0, ind = 0;
96 97 98 99 100
  for (int i = 0; i < task_pool_size_; i++) {
    for (int j = 0; j < (int)node_array[i].size(); j++) {
      res.node_list[ind] = node_array[i][j];
      res.node_list[ind++].neighbor_offset += offset;
    }
101
    for (size_t j = 0; j < edge_array[i].size(); j++) {
102 103 104 105 106 107
      res.neighbor_list[offset + j] = edge_array[i][j];
    }
    offset += edge_array[i].size();
  }
  return res;
}
108

109 110 111 112 113 114 115
int32_t GraphTable::add_node_to_ssd(int type_id, int idx, int64_t src_id,
                                    char *data, int len) {
  if (_db != NULL) {
    char ch[sizeof(int) * 2 + sizeof(int64_t)];
    memcpy(ch, &type_id, sizeof(int));
    memcpy(ch + sizeof(int), &idx, sizeof(int));
    memcpy(ch + sizeof(int) * 2, &src_id, sizeof(int64_t));
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    std::string str;
    if (_db->get(src_id % shard_num % task_pool_size_, ch,
                 sizeof(int) * 2 + sizeof(int64_t), str) == 0) {
      int64_t *stored_data = ((int64_t *)str.c_str());
      int n = str.size() / sizeof(int64_t);
      char *new_data = new char[n * sizeof(int64_t) + len];
      memcpy(new_data, stored_data, n * sizeof(int64_t));
      memcpy(new_data + n * sizeof(int64_t), data, len);
      _db->put(src_id % shard_num % task_pool_size_, ch,
               sizeof(int) * 2 + sizeof(int64_t), (char *)new_data,
               n * sizeof(int64_t) + len);
      delete[] new_data;
    } else {
      _db->put(src_id % shard_num % task_pool_size_, ch,
               sizeof(int) * 2 + sizeof(int64_t), (char *)data, len);
    }
S
seemingwang 已提交
132 133
    // _db->flush(src_id % shard_num % task_pool_size_);
    // std::string x;
134 135 136 137 138 139 140
    // if (_db->get(src_id % shard_num % task_pool_size_, ch, sizeof(int64_t) +
    // 2 * sizeof(int), x) ==0){
    // VLOG(0)<<"put result";
    // for(int i = 0;i < x.size();i+=8){
    //   VLOG(0)<<"get an id "<<*((int64_t *)(x.c_str() + i));
    // }
    //}
S
seemingwang 已提交
141 142 143 144 145 146 147 148 149 150 151 152
    // if(src_id == 429){
    //   str = "";
    //   _db->get(src_id % shard_num % task_pool_size_, ch,
    //            sizeof(int) * 2 + sizeof(int64_t), str);
    //   int64_t *stored_data = ((int64_t *)str.c_str());
    //   int n = str.size() / sizeof(int64_t);
    //   VLOG(0)<<"429 has "<<n<<"neighbors";
    //   for(int i =0;i< n;i++){
    //     VLOG(0)<<"get an id "<<*((int64_t *)(str.c_str() +
    //     i*sizeof(int64_t)));
    //   }
    // }
153
  }
154 155 156
  return 0;
}
char *GraphTable::random_sample_neighbor_from_ssd(
157 158
    int idx, int64_t id, int sample_size,
    const std::shared_ptr<std::mt19937_64> rng, int &actual_size) {
159 160 161 162 163
  if (_db == NULL) {
    actual_size = 0;
    return NULL;
  }
  std::string str;
S
seemingwang 已提交
164
  VLOG(2) << "sample ssd for key " << id;
165 166 167 168
  char ch[sizeof(int) * 2 + sizeof(int64_t)];
  memset(ch, 0, sizeof(int));
  memcpy(ch + sizeof(int), &idx, sizeof(int));
  memcpy(ch + sizeof(int) * 2, &id, sizeof(int64_t));
169 170
  if (_db->get(id % shard_num % task_pool_size_, ch,
               sizeof(int) * 2 + sizeof(int64_t), str) == 0) {
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    int64_t *data = ((int64_t *)str.c_str());
    int n = str.size() / sizeof(int64_t);
    std::unordered_map<int, int> m;
    // std::vector<int64_t> res;
    int sm_size = std::min(n, sample_size);
    actual_size = sm_size * Node::id_size;
    char *buff = new char[actual_size];
    for (int i = 0; i < sm_size; i++) {
      std::uniform_int_distribution<int> distrib(0, n - i - 1);
      int t = distrib(*rng);
      // int t = rand() % (n-i);
      int pos = 0;
      auto iter = m.find(t);
      if (iter != m.end()) {
        pos = iter->second;
      } else {
        pos = t;
      }
      auto iter2 = m.find(n - i - 1);
190

191 192 193 194 195 196
      int key2 = iter2 == m.end() ? n - i - 1 : iter2->second;
      m[t] = key2;
      m.erase(n - i - 1);
      memcpy(buff + i * Node::id_size, &data[pos], Node::id_size);
      // res.push_back(data[pos]);
    }
S
seemingwang 已提交
197 198 199
    for (int i = 0; i < actual_size; i += 8) {
      VLOG(2) << "sampled an neighbor " << *(int64_t *)&buff[i];
    }
200 201 202 203 204
    return buff;
  }
  actual_size = 0;
  return NULL;
}
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250

int64_t GraphTable::load_graph_to_memory_from_ssd(int idx,
                                                  std::vector<int64_t> &ids) {
  std::vector<std::vector<int64_t>> bags(task_pool_size_);
  for (auto x : ids) {
    int location = x % shard_num % task_pool_size_;
    bags[location].push_back(x);
  }
  std::vector<std::future<int>> tasks;
  std::vector<int64_t> count(task_pool_size_, 0);
  for (size_t i = 0; i < bags.size(); i++) {
    if (bags[i].size() > 0) {
      tasks.push_back(_shards_task_pool[i]->enqueue([&, i, idx, this]() -> int {
        char ch[sizeof(int) * 2 + sizeof(int64_t)];
        memset(ch, 0, sizeof(int));
        memcpy(ch + sizeof(int), &idx, sizeof(int));
        for (size_t k = 0; k < bags[i].size(); k++) {
          auto v = bags[i][k];
          memcpy(ch + sizeof(int) * 2, &v, sizeof(int64_t));
          std::string str;
          if (_db->get(i, ch, sizeof(int) * 2 + sizeof(int64_t), str) == 0) {
            count[i] += (int64_t)str.size();
            for (int j = 0; j < str.size(); j += sizeof(int64_t)) {
              int64_t id = *(int64_t *)(str.c_str() + j);
              add_comm_edge(idx, v, id);
            }
          }
        }
        return 0;
      }));
    }
  }

  for (int i = 0; i < (int)tasks.size(); i++) tasks[i].get();
  int64_t tot = 0;
  for (auto x : count) tot += x;
  return tot;
}

void GraphTable::make_partitions(int idx, int64_t byte_size, int device_len) {
  VLOG(2) << "start to make graph partitions , byte_size = " << byte_size
          << " total memory cost = " << total_memory_cost;
  if (total_memory_cost == 0) {
    VLOG(0) << "no edges are detected,make partitions exits";
    return;
  }
251 252
  auto &weight_map = node_weight[0][idx];
  const double a = 2.0, y = 1.25, weight_param = 1.0;
253 254 255 256 257 258 259 260 261
  int64_t gb_size_by_discount = byte_size * 0.8 * device_len;
  if (gb_size_by_discount <= 0) gb_size_by_discount = 1;
  int part_len = total_memory_cost / gb_size_by_discount;
  if (part_len == 0) part_len = 1;

  VLOG(2) << "part_len = " << part_len
          << " byte size = " << gb_size_by_discount;
  partitions[idx].clear();
  partitions[idx].resize(part_len);
262
  std::vector<double> weight_cost(part_len, 0);
263
  std::vector<int64_t> memory_remaining(part_len, gb_size_by_discount);
264
  std::vector<double> score(part_len, 0);
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
  std::unordered_map<int64_t, int> id_map;
  std::vector<rocksdb::Iterator *> iters;
  for (int i = 0; i < task_pool_size_; i++) {
    iters.push_back(_db->get_iterator(i));
    iters[i]->SeekToFirst();
  }
  int next = 0;
  while (iters.size()) {
    if (next >= iters.size()) {
      next = 0;
    }
    if (!iters[next]->Valid()) {
      iters.erase(iters.begin() + next);
      continue;
    }
    std::string key = iters[next]->key().ToString();
281
    int type_idx = *(int *)key.c_str();
282
    int temp_idx = *(int *)(key.c_str() + sizeof(int));
283
    if (type_idx != 0 || temp_idx != idx) {
284 285 286 287 288
      iters[next]->Next();
      next++;
      continue;
    }
    std::string value = iters[next]->value().ToString();
289
    std::int64_t i_key = *(int64_t *)(key.c_str() + sizeof(int) * 2);
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
    for (int i = 0; i < part_len; i++) {
      if (memory_remaining[i] < (int64_t)value.size()) {
        score[i] = -100000.0;
      } else {
        score[i] = 0;
      }
    }
    for (int j = 0; j < value.size(); j += sizeof(int64_t)) {
      int64_t v = *((int64_t *)(value.c_str() + j));
      int index = -1;
      if (id_map.find(v) != id_map.end()) {
        index = id_map[v];
        score[index]++;
      }
    }
305 306 307 308 309 310 311
    double base, weight_base = 0;
    double w = 0;
    bool has_weight = false;
    if (weight_map.find(i_key) != weight_map.end()) {
      w = weight_map[i_key];
      has_weight = true;
    }
312 313
    int index = 0;
    for (int i = 0; i < part_len; i++) {
314 315 316 317 318 319 320
      base = gb_size_by_discount - memory_remaining[i] + value.size();
      if (has_weight)
        weight_base = weight_cost[i] + w * weight_param;
      else {
        weight_base = 0;
      }
      score[i] -= a * y * std::pow(1.0 * base, y - 1) + weight_base;
321 322 323 324 325 326 327
      if (score[i] > score[index]) index = i;
      VLOG(2) << "score" << i << " = " << score[i] << " memory left "
              << memory_remaining[i];
    }
    id_map[i_key] = index;
    partitions[idx][index].push_back(i_key);
    memory_remaining[index] -= (int64_t)value.size();
328
    if (has_weight) weight_cost[index] += w;
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
    iters[next]->Next();
    next++;
  }
  for (int i = 0; i < part_len; i++) {
    if (partitions[idx][i].size() == 0) {
      partitions[idx].erase(partitions[idx].begin() + i);
      i--;
      part_len--;
      continue;
    }
    VLOG(2) << " partition " << i << " size = " << partitions[idx][i].size();
    for (auto x : partitions[idx][i]) {
      VLOG(2) << "find a id " << x;
    }
  }
  next_partition = 0;
}

347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
void GraphTable::export_partition_files(int idx, std::string file_path) {
  int part_len = partitions[idx].size();
  if (part_len == 0) return;
  if (file_path == "") file_path = ".";
  if (file_path[(int)file_path.size() - 1] != '/') {
    file_path += "/";
  }
  std::vector<std::future<int>> tasks;
  for (int i = 0; i < part_len; i++) {
    tasks.push_back(_shards_task_pool[i % task_pool_size_]->enqueue(
        [&, i, idx, this]() -> int {
          std::string output_path =
              file_path + "partition_" + std::to_string(i);

          std::ofstream ofs(output_path);
          if (ofs.fail()) {
            VLOG(0) << "creating " << output_path << " failed";
            return 0;
          }
          for (auto x : partitions[idx][i]) {
            auto str = std::to_string(x);
            ofs.write(str.c_str(), str.size());
            ofs.write("\n", 1);
          }
          ofs.close();
          return 0;
        }));
  }

  for (int i = 0; i < (int)tasks.size(); i++) tasks[i].get();
}
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
void GraphTable::clear_graph(int idx) {
  for (auto p : edge_shards[idx]) {
    delete p;
  }

  edge_shards[idx].clear();
  for (size_t i = 0; i < shard_num_per_server; i++) {
    edge_shards[idx].push_back(new GraphShard());
  }
}
int32_t GraphTable::load_next_partition(int idx) {
  if (next_partition >= partitions[idx].size()) {
    VLOG(0) << "partition iteration is done";
    return -1;
  }
  clear_graph(idx);
  load_graph_to_memory_from_ssd(idx, partitions[idx][next_partition]);
  next_partition++;
  return 0;
}
int32_t GraphTable::load_edges_to_ssd(const std::string &path,
                                      bool reverse_edge,
                                      const std::string &edge_type) {
  int idx = 0;
  if (edge_type == "") {
    VLOG(0) << "edge_type not specified, loading edges to " << id_to_edge[0]
            << " part";
  } else {
    if (edge_to_id.find(edge_type) == edge_to_id.end()) {
      VLOG(0) << "edge_type " << edge_type
              << " is not defined, nothing will be loaded";
      return 0;
    }
    idx = edge_to_id[edge_type];
  }
  total_memory_cost = 0;
  auto paths = paddle::string::split_string<std::string>(path, ";");
  int64_t count = 0;
  std::string sample_type = "random";
  bool is_weighted = false;
  int valid_count = 0;
  for (auto path : paths) {
    std::ifstream file(path);
    std::string line;
    while (std::getline(file, line)) {
      VLOG(0) << "get a line from file " << line;
      auto values = paddle::string::split_string<std::string>(line, "\t");
      count++;
      if (values.size() < 2) continue;
      auto src_id = std::stoll(values[0]);
      auto dist_ids = paddle::string::split_string<std::string>(values[1], ";");
      std::vector<int64_t> dist_data;
      for (auto x : dist_ids) {
        dist_data.push_back(std::stoll(x));
        total_memory_cost += sizeof(int64_t);
      }
      add_node_to_ssd(0, idx, src_id, (char *)dist_data.data(),
                      (int)(dist_data.size() * sizeof(int64_t)));
    }
  }
  VLOG(0) << "total memory cost = " << total_memory_cost << " bytes";
  return 0;
}

int32_t GraphTable::dump_edges_to_ssd(int idx) {
S
seemingwang 已提交
443
  VLOG(2) << "calling dump edges to ssd";
444 445 446 447 448 449 450 451 452 453 454 455
  const int64_t fixed_size = 10000;
  // std::vector<int64_t> edge_array[task_pool_size_];
  std::vector<std::unordered_map<int64_t, int>> count(task_pool_size_);
  std::vector<std::future<int64_t>> tasks;
  auto &shards = edge_shards[idx];
  for (size_t i = 0; i < shards.size(); ++i) {
    tasks.push_back(_shards_task_pool[i % task_pool_size_]->enqueue(
        [&, i, this]() -> int64_t {
          int64_t cost = 0;
          std::vector<Node *> &v = shards[i]->get_bucket();
          size_t ind = i % this->task_pool_size_;
          for (size_t j = 0; j < v.size(); j++) {
S
seemingwang 已提交
456
            std::vector<int64_t> s;
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
            for (int k = 0; k < v[j]->get_neighbor_size(); k++) {
              s.push_back(v[j]->get_neighbor_id(k));
            }
            cost += v[j]->get_neighbor_size() * sizeof(int64_t);
            add_node_to_ssd(0, idx, v[j]->get_id(), (char *)s.data(),
                            s.size() * sizeof(int64_t));
          }
          return cost;
        }));
  }
  for (size_t i = 0; i < tasks.size(); i++) total_memory_cost += tasks[i].get();
  return 0;
}
int32_t GraphTable::make_complementary_graph(int idx, int64_t byte_size) {
  VLOG(0) << "make_complementary_graph";
S
seemingwang 已提交
472
  const int64_t fixed_size = byte_size / 8;
473 474 475 476 477 478 479 480 481 482
  // std::vector<int64_t> edge_array[task_pool_size_];
  std::vector<std::unordered_map<int64_t, int>> count(task_pool_size_);
  std::vector<std::future<int>> tasks;
  auto &shards = edge_shards[idx];
  for (size_t i = 0; i < shards.size(); ++i) {
    tasks.push_back(
        _shards_task_pool[i % task_pool_size_]->enqueue([&, i, this]() -> int {
          std::vector<Node *> &v = shards[i]->get_bucket();
          size_t ind = i % this->task_pool_size_;
          for (size_t j = 0; j < v.size(); j++) {
S
seemingwang 已提交
483
            // size_t location = v[j]->get_id();
484 485 486 487 488 489 490
            for (int k = 0; k < v[j]->get_neighbor_size(); k++) {
              count[ind][v[j]->get_neighbor_id(k)]++;
            }
          }
          return 0;
        }));
  }
S
seemingwang 已提交
491
  for (size_t i = 0; i < tasks.size(); i++) tasks[i].get();
492 493 494
  std::unordered_map<int64_t, int> final_count;
  std::map<int, std::vector<int64_t>> count_to_id;
  std::vector<int64_t> buffer;
S
seemingwang 已提交
495
  clear_graph(idx);
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512

  for (int i = 0; i < task_pool_size_; i++) {
    for (auto &p : count[i]) {
      final_count[p.first] = final_count[p.first] + p.second;
    }
    count[i].clear();
  }
  for (auto &p : final_count) {
    count_to_id[p.second].push_back(p.first);
    VLOG(2) << p.first << " appear " << p.second << " times";
  }
  auto iter = count_to_id.rbegin();
  while (iter != count_to_id.rend() && byte_size > 0) {
    for (auto x : iter->second) {
      buffer.push_back(x);
      if (buffer.size() >= fixed_size) {
        int64_t res = load_graph_to_memory_from_ssd(idx, buffer);
S
seemingwang 已提交
513
        buffer.clear();
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
        byte_size -= res;
      }
      if (byte_size <= 0) break;
    }
    iter++;
  }
  if (byte_size > 0 && buffer.size() > 0) {
    int64_t res = load_graph_to_memory_from_ssd(idx, buffer);
    byte_size -= res;
  }
  std::string sample_type = "random";
  for (auto &shard : edge_shards[idx]) {
    auto bucket = shard->get_bucket();
    for (size_t i = 0; i < bucket.size(); i++) {
      bucket[i]->build_sampler(sample_type);
    }
  }
  return 0;
}
533
#endif
534

535
/*
536 537 538 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
int CompleteGraphSampler::run_graph_sampling() {
  pthread_rwlock_t *rw_lock = graph_table->rw_lock.get();
  pthread_rwlock_rdlock(rw_lock);
  std::cout << "in graph sampling" << std::endl;
  sample_nodes.clear();
  sample_neighbors.clear();
  sample_res.clear();
  sample_nodes.resize(gpu_num);
  sample_neighbors.resize(gpu_num);
  sample_res.resize(gpu_num);
  std::vector<std::vector<std::vector<paddle::framework::GpuPsGraphNode>>>
      sample_nodes_ex(graph_table->task_pool_size_);
  std::vector<std::vector<std::vector<int64_t>>> sample_neighbors_ex(
      graph_table->task_pool_size_);
  for (int i = 0; i < graph_table->task_pool_size_; i++) {
    sample_nodes_ex[i].resize(gpu_num);
    sample_neighbors_ex[i].resize(gpu_num);
  }
  std::vector<std::future<int>> tasks;
  for (size_t i = 0; i < graph_table->shards.size(); ++i) {
    tasks.push_back(
        graph_table->_shards_task_pool[i % graph_table->task_pool_size_]
            ->enqueue([&, i, this]() -> int {
              if (this->status == GraphSamplerStatus::terminating) return 0;
              paddle::framework::GpuPsGraphNode node;
              std::vector<Node *> &v =
                  this->graph_table->shards[i]->get_bucket();
              size_t ind = i % this->graph_table->task_pool_size_;
              for (size_t j = 0; j < v.size(); j++) {
                size_t location = v[j]->get_id() % this->gpu_num;
                node.node_id = v[j]->get_id();
                node.neighbor_size = v[j]->get_neighbor_size();
                node.neighbor_offset =
                    (int)sample_neighbors_ex[ind][location].size();
                sample_nodes_ex[ind][location].emplace_back(node);
                for (int k = 0; k < node.neighbor_size; k++)
                  sample_neighbors_ex[ind][location].push_back(
                      v[j]->get_neighbor_id(k));
              }
              return 0;
            }));
  }
  for (size_t i = 0; i < tasks.size(); i++) tasks[i].get();
  tasks.clear();
580
  for (int i = 0; i < gpu_num; i++) {
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
    tasks.push_back(
        graph_table->_shards_task_pool[i % graph_table->task_pool_size_]
            ->enqueue([&, i, this]() -> int {
              if (this->status == GraphSamplerStatus::terminating) return 0;
              int total_offset = 0;
              size_t ind = i % this->graph_table->task_pool_size_;
              for (int j = 0; j < this->graph_table->task_pool_size_; j++) {
                for (size_t k = 0; k < sample_nodes_ex[j][ind].size(); k++) {
                  sample_nodes[ind].push_back(sample_nodes_ex[j][ind][k]);
                  sample_nodes[ind].back().neighbor_offset += total_offset;
                }
                size_t neighbor_size = sample_neighbors_ex[j][ind].size();
                total_offset += neighbor_size;
                for (size_t k = 0; k < neighbor_size; k++) {
                  sample_neighbors[ind].push_back(
                      sample_neighbors_ex[j][ind][k]);
                }
              }
              return 0;
            }));
  }
  for (size_t i = 0; i < tasks.size(); i++) tasks[i].get();

  if (this->status == GraphSamplerStatus::terminating) {
    pthread_rwlock_unlock(rw_lock);
    return 0;
  }
608
  for (int i = 0; i < gpu_num; i++) {
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
    sample_res[i].node_list = sample_nodes[i].data();
    sample_res[i].neighbor_list = sample_neighbors[i].data();
    sample_res[i].node_size = sample_nodes[i].size();
    sample_res[i].neighbor_size = sample_neighbors[i].size();
  }
  pthread_rwlock_unlock(rw_lock);
  if (this->status == GraphSamplerStatus::terminating) {
    return 0;
  }
  callback(sample_res);
  return 0;
}
void CompleteGraphSampler::init(size_t gpu_num, GraphTable *graph_table,
                                std::vector<std::string> args) {
  this->gpu_num = gpu_num;
  this->graph_table = graph_table;
}

int BasicBfsGraphSampler::run_graph_sampling() {
  pthread_rwlock_t *rw_lock = graph_table->rw_lock.get();
  pthread_rwlock_rdlock(rw_lock);
  while (rounds > 0 && status == GraphSamplerStatus::running) {
    for (size_t i = 0; i < sample_neighbors_map.size(); i++) {
      sample_neighbors_map[i].clear();
    }
    sample_neighbors_map.clear();
    std::vector<int> nodes_left(graph_table->shards.size(),
                                node_num_for_each_shard);
    std::promise<int> prom;
    std::future<int> fut = prom.get_future();
    sample_neighbors_map.resize(graph_table->task_pool_size_);
    int task_size = 0;
    std::vector<std::future<int>> tasks;
    int init_size = 0;
643 644
    //__sync_fetch_and_add
    std::function<int(int, int64_t)> bfs = [&, this](int i, int id) -> int {
645 646 647 648 649 650 651 652 653 654 655 656 657
      if (this->status == GraphSamplerStatus::terminating) {
        int task_left = __sync_sub_and_fetch(&task_size, 1);
        if (task_left == 0) {
          prom.set_value(0);
        }
        return 0;
      }
      size_t ind = i % this->graph_table->task_pool_size_;
      if (nodes_left[i] > 0) {
        auto iter = sample_neighbors_map[ind].find(id);
        if (iter == sample_neighbors_map[ind].end()) {
          Node *node = graph_table->shards[i]->find_node(id);
          if (node != NULL) {
658 659 660
            nodes_left[i]--;
            sample_neighbors_map[ind][id] = std::vector<int64_t>();
            iter = sample_neighbors_map[ind].find(id);
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
            size_t edge_fetch_size =
                std::min((size_t) this->edge_num_for_each_node,
                         node->get_neighbor_size());
            for (size_t k = 0; k < edge_fetch_size; k++) {
              int64_t neighbor_id = node->get_neighbor_id(k);
              int node_location = neighbor_id % this->graph_table->shard_num %
                                  this->graph_table->task_pool_size_;
              __sync_add_and_fetch(&task_size, 1);
              graph_table->_shards_task_pool[node_location]->enqueue(
                  bfs, neighbor_id % this->graph_table->shard_num, neighbor_id);
              iter->second.push_back(neighbor_id);
            }
          }
        }
      }
      int task_left = __sync_sub_and_fetch(&task_size, 1);
      if (task_left == 0) {
        prom.set_value(0);
      }
      return 0;
    };
    for (size_t i = 0; i < graph_table->shards.size(); ++i) {
      std::vector<Node *> &v = graph_table->shards[i]->get_bucket();
      if (v.size() > 0) {
685 686 687 688 689 690 691 692
        int search_size = std::min(init_search_size, (int)v.size());
        for (int k = 0; k < search_size; k++) {
          init_size++;
          __sync_add_and_fetch(&task_size, 1);
          int64_t id = v[k]->get_id();
          graph_table->_shards_task_pool[i % graph_table->task_pool_size_]
              ->enqueue(bfs, i, id);
        }
693 694 695 696 697 698 699 700 701 702
      }  // if
    }
    if (init_size == 0) {
      prom.set_value(0);
    }
    fut.get();
    if (this->status == GraphSamplerStatus::terminating) {
      pthread_rwlock_unlock(rw_lock);
      return 0;
    }
703
    VLOG(0) << "BasicBfsGraphSampler finishes the graph searching task";
704 705 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 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
    sample_nodes.clear();
    sample_neighbors.clear();
    sample_res.clear();
    sample_nodes.resize(gpu_num);
    sample_neighbors.resize(gpu_num);
    sample_res.resize(gpu_num);
    std::vector<std::vector<std::vector<paddle::framework::GpuPsGraphNode>>>
        sample_nodes_ex(graph_table->task_pool_size_);
    std::vector<std::vector<std::vector<int64_t>>> sample_neighbors_ex(
        graph_table->task_pool_size_);
    for (int i = 0; i < graph_table->task_pool_size_; i++) {
      sample_nodes_ex[i].resize(gpu_num);
      sample_neighbors_ex[i].resize(gpu_num);
    }
    tasks.clear();
    for (size_t i = 0; i < (size_t)graph_table->task_pool_size_; ++i) {
      tasks.push_back(
          graph_table->_shards_task_pool[i]->enqueue([&, i, this]() -> int {
            if (this->status == GraphSamplerStatus::terminating) {
              return 0;
            }
            paddle::framework::GpuPsGraphNode node;
            auto iter = sample_neighbors_map[i].begin();
            size_t ind = i;
            for (; iter != sample_neighbors_map[i].end(); iter++) {
              size_t location = iter->first % this->gpu_num;
              node.node_id = iter->first;
              node.neighbor_size = iter->second.size();
              node.neighbor_offset =
                  (int)sample_neighbors_ex[ind][location].size();
              sample_nodes_ex[ind][location].emplace_back(node);
              for (auto k : iter->second)
                sample_neighbors_ex[ind][location].push_back(k);
            }
            return 0;
          }));
    }

    for (size_t i = 0; i < tasks.size(); i++) {
      tasks[i].get();
      sample_neighbors_map[i].clear();
    }
    tasks.clear();
    if (this->status == GraphSamplerStatus::terminating) {
      pthread_rwlock_unlock(rw_lock);
      return 0;
    }
751
    for (size_t i = 0; i < (size_t)gpu_num; i++) {
752 753 754 755 756 757 758 759 760
      tasks.push_back(
          graph_table->_shards_task_pool[i % graph_table->task_pool_size_]
              ->enqueue([&, i, this]() -> int {
                if (this->status == GraphSamplerStatus::terminating) {
                  pthread_rwlock_unlock(rw_lock);
                  return 0;
                }
                int total_offset = 0;
                for (int j = 0; j < this->graph_table->task_pool_size_; j++) {
761 762
                  for (size_t k = 0; k < sample_nodes_ex[j][i].size(); k++) {
                    sample_nodes[i].push_back(sample_nodes_ex[j][i][k]);
763 764
                    sample_nodes[i].back().neighbor_offset += total_offset;
                  }
765
                  size_t neighbor_size = sample_neighbors_ex[j][i].size();
766 767
                  total_offset += neighbor_size;
                  for (size_t k = 0; k < neighbor_size; k++) {
768
                    sample_neighbors[i].push_back(sample_neighbors_ex[j][i][k]);
769 770 771 772 773 774 775 776 777 778
                  }
                }
                return 0;
              }));
    }
    for (size_t i = 0; i < tasks.size(); i++) tasks[i].get();
    if (this->status == GraphSamplerStatus::terminating) {
      pthread_rwlock_unlock(rw_lock);
      return 0;
    }
779
    for (int i = 0; i < gpu_num; i++) {
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
      sample_res[i].node_list = sample_nodes[i].data();
      sample_res[i].neighbor_list = sample_neighbors[i].data();
      sample_res[i].node_size = sample_nodes[i].size();
      sample_res[i].neighbor_size = sample_neighbors[i].size();
    }
    pthread_rwlock_unlock(rw_lock);
    if (this->status == GraphSamplerStatus::terminating) {
      return 0;
    }
    callback(sample_res);
    rounds--;
    if (rounds > 0) {
      for (int i = 0;
           i < interval && this->status == GraphSamplerStatus::running; i++) {
        std::this_thread::sleep_for(std::chrono::seconds(1));
      }
    }
797
    VLOG(0)<<"bfs returning";
798 799 800 801 802 803 804
  }
  return 0;
}
void BasicBfsGraphSampler::init(size_t gpu_num, GraphTable *graph_table,
                                std::vector<std::string> args) {
  this->gpu_num = gpu_num;
  this->graph_table = graph_table;
805 806 807 808 809
  init_search_size = args.size() > 0 ? std::stoi(args[0]) : 10;
  node_num_for_each_shard = args.size() > 1 ? std::stoi(args[1]) : 10;
  edge_num_for_each_node = args.size() > 2 ? std::stoi(args[2]) : 10;
  rounds = args.size() > 3 ? std::stoi(args[3]) : 1;
  interval = args.size() > 4 ? std::stoi(args[4]) : 60;
810 811 812
}

#endif
813
*/
S
seemingwang 已提交
814 815 816 817 818 819 820 821 822 823 824
std::vector<Node *> GraphShard::get_batch(int start, int end, int step) {
  if (start < 0) start = 0;
  std::vector<Node *> res;
  for (int pos = start; pos < std::min(end, (int)bucket.size()); pos += step) {
    res.push_back(bucket[pos]);
  }
  return res;
}

size_t GraphShard::get_size() { return bucket.size(); }

825
int32_t GraphTable::add_comm_edge(int idx, int64_t src_id, int64_t dst_id) {
826 827 828 829 830 831
  size_t src_shard_id = src_id % shard_num;

  if (src_shard_id >= shard_end || src_shard_id < shard_start) {
    return -1;
  }
  size_t index = src_shard_id - shard_start;
832 833
  edge_shards[idx][index]->add_graph_node(src_id)->build_edges(false);
  edge_shards[idx][index]->add_neighbor(src_id, dst_id, 1.0);
834 835
  return 0;
}
836
int32_t GraphTable::add_graph_node(int idx, std::vector<int64_t> &id_list,
837
                                   std::vector<bool> &is_weight_list) {
838
  auto &shards = edge_shards[idx];
839
  size_t node_size = id_list.size();
840
  std::vector<std::vector<std::pair<int64_t, bool>>> batch(task_pool_size_);
841 842 843 844 845 846 847 848 849 850 851
  for (size_t i = 0; i < node_size; i++) {
    size_t shard_id = id_list[i] % shard_num;
    if (shard_id >= shard_end || shard_id < shard_start) {
      continue;
    }
    batch[get_thread_pool_index(id_list[i])].push_back(
        {id_list[i], i < is_weight_list.size() ? is_weight_list[i] : false});
  }
  std::vector<std::future<int>> tasks;
  for (size_t i = 0; i < batch.size(); ++i) {
    if (!batch[i].size()) continue;
852 853 854 855 856 857 858 859
    tasks.push_back(
        _shards_task_pool[i]->enqueue([&shards, &batch, i, this]() -> int {
          for (auto &p : batch[i]) {
            size_t index = p.first % this->shard_num - this->shard_start;
            shards[index]->add_graph_node(p.first)->build_edges(p.second);
          }
          return 0;
        }));
860 861 862 863 864
  }
  for (size_t i = 0; i < tasks.size(); i++) tasks[i].get();
  return 0;
}

865
int32_t GraphTable::remove_graph_node(int idx, std::vector<int64_t> &id_list) {
866
  size_t node_size = id_list.size();
867
  std::vector<std::vector<int64_t>> batch(task_pool_size_);
868 869 870 871 872
  for (size_t i = 0; i < node_size; i++) {
    size_t shard_id = id_list[i] % shard_num;
    if (shard_id >= shard_end || shard_id < shard_start) continue;
    batch[get_thread_pool_index(id_list[i])].push_back(id_list[i]);
  }
873
  auto &shards = edge_shards[idx];
874 875 876
  std::vector<std::future<int>> tasks;
  for (size_t i = 0; i < batch.size(); ++i) {
    if (!batch[i].size()) continue;
877 878 879 880 881 882 883 884
    tasks.push_back(
        _shards_task_pool[i]->enqueue([&shards, &batch, i, this]() -> int {
          for (auto &p : batch[i]) {
            size_t index = p % this->shard_num - this->shard_start;
            shards[index]->delete_node(p);
          }
          return 0;
        }));
885 886 887 888 889 890 891 892 893 894 895 896 897 898
  }
  for (size_t i = 0; i < tasks.size(); i++) tasks[i].get();
  return 0;
}

void GraphShard::clear() {
  for (size_t i = 0; i < bucket.size(); i++) {
    delete bucket[i];
  }
  bucket.clear();
  node_location.clear();
}

GraphShard::~GraphShard() { clear(); }
899

900
void GraphShard::delete_node(int64_t id) {
901 902 903 904 905 906 907 908 909 910 911
  auto iter = node_location.find(id);
  if (iter == node_location.end()) return;
  int pos = iter->second;
  delete bucket[pos];
  if (pos != (int)bucket.size() - 1) {
    bucket[pos] = bucket.back();
    node_location[bucket.back()->get_id()] = pos;
  }
  node_location.erase(id);
  bucket.pop_back();
}
912
GraphNode *GraphShard::add_graph_node(int64_t id) {
S
seemingwang 已提交
913 914 915 916 917 918 919
  if (node_location.find(id) == node_location.end()) {
    node_location[id] = bucket.size();
    bucket.push_back(new GraphNode(id));
  }
  return (GraphNode *)bucket[node_location[id]];
}

920 921 922 923 924 925 926 927
GraphNode *GraphShard::add_graph_node(Node *node) {
  auto id = node->get_id();
  if (node_location.find(id) == node_location.end()) {
    node_location[id] = bucket.size();
    bucket.push_back(node);
  }
  return (GraphNode *)bucket[node_location[id]];
}
928
FeatureNode *GraphShard::add_feature_node(int64_t id) {
S
seemingwang 已提交
929 930 931 932 933 934 935
  if (node_location.find(id) == node_location.end()) {
    node_location[id] = bucket.size();
    bucket.push_back(new FeatureNode(id));
  }
  return (FeatureNode *)bucket[node_location[id]];
}

936
void GraphShard::add_neighbor(int64_t id, int64_t dst_id, float weight) {
S
seemingwang 已提交
937 938 939
  find_node(id)->add_edge(dst_id, weight);
}

940
Node *GraphShard::find_node(int64_t id) {
S
seemingwang 已提交
941 942 943 944
  auto iter = node_location.find(id);
  return iter == node_location.end() ? nullptr : bucket[iter->second];
}

945
GraphTable::~GraphTable() {
946 947 948 949 950
  for (int i = 0; i < (int)edge_shards.size(); i++) {
    for (auto p : edge_shards[i]) {
      delete p;
    }
    edge_shards[i].clear();
951 952
  }

953 954 955 956 957 958
  for (int i = 0; i < (int)feature_shards.size(); i++) {
    for (auto p : feature_shards[i]) {
      delete p;
    }
    feature_shards[i].clear();
  }
959 960
}

Z
zhaocaibei123 已提交
961
int32_t GraphTable::Load(const std::string &path, const std::string &param) {
S
seemingwang 已提交
962 963 964 965
  bool load_edge = (param[0] == 'e');
  bool load_node = (param[0] == 'n');
  if (load_edge) {
    bool reverse_edge = (param[1] == '<');
966 967
    std::string edge_type = param.substr(2);
    return this->load_edges(path, reverse_edge, edge_type);
S
seemingwang 已提交
968 969 970 971 972 973 974 975 976
  }
  if (load_node) {
    std::string node_type = param.substr(1);
    return this->load_nodes(path, node_type);
  }
  return 0;
}

int32_t GraphTable::get_nodes_ids_by_ranges(
977 978
    int type_id, int idx, std::vector<std::pair<int, int>> ranges,
    std::vector<int64_t> &res) {
S
seemingwang 已提交
979 980
  int start = 0, end, index = 0, total_size = 0;
  res.clear();
981
  auto &shards = type_id == 0 ? edge_shards[idx] : feature_shards[idx];
982
  std::vector<std::future<std::vector<int64_t>>> tasks;
983
  for (size_t i = 0; i < shards.size() && index < (int)ranges.size(); i++) {
984
    end = total_size + shards[i]->get_size();
S
seemingwang 已提交
985
    start = total_size;
986
    while (start < end && index < (int)ranges.size()) {
S
seemingwang 已提交
987 988 989 990 991 992 993 994 995 996 997
      if (ranges[index].second <= start)
        index++;
      else if (ranges[index].first >= end) {
        break;
      } else {
        int first = std::max(ranges[index].first, start);
        int second = std::min(ranges[index].second, end);
        start = second;
        first -= total_size;
        second -= total_size;
        tasks.push_back(_shards_task_pool[i % task_pool_size_]->enqueue(
998
            [&shards, this, first, second, i]() -> std::vector<int64_t> {
999
              return shards[i]->get_ids_by_range(first, second);
S
seemingwang 已提交
1000 1001 1002
            }));
      }
    }
1003
    total_size += shards[i]->get_size();
S
seemingwang 已提交
1004
  }
1005
  for (size_t i = 0; i < tasks.size(); i++) {
S
seemingwang 已提交
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
    auto vec = tasks[i].get();
    for (auto &id : vec) {
      res.push_back(id);
      std::swap(res[rand() % res.size()], res[(int)res.size() - 1]);
    }
  }
  return 0;
}

int32_t GraphTable::load_nodes(const std::string &path, std::string node_type) {
  auto paths = paddle::string::split_string<std::string>(path, ";");
  int64_t count = 0;
  int64_t valid_count = 0;
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
  int idx = 0;
  if (node_type == "") {
    VLOG(0) << "node_type not specified, loading edges to " << id_to_feature[0]
            << " part";
  } else {
    if (feature_to_id.find(node_type) == feature_to_id.end()) {
      VLOG(0) << "node_type " << node_type
              << " is not defined, nothing will be loaded";
      return 0;
    }
    idx = feature_to_id[node_type];
  }
S
seemingwang 已提交
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
  for (auto path : paths) {
    std::ifstream file(path);
    std::string line;
    while (std::getline(file, line)) {
      auto values = paddle::string::split_string<std::string>(line, "\t");
      if (values.size() < 2) continue;
      auto id = std::stoull(values[1]);

      size_t shard_id = id % shard_num;
      if (shard_id >= shard_end || shard_id < shard_start) {
        VLOG(4) << "will not load " << id << " from " << path
                << ", please check id distribution";
        continue;
      }

      if (count % 1000000 == 0) {
        VLOG(0) << count << " nodes are loaded from filepath";
1048
        VLOG(0) << line;
S
seemingwang 已提交
1049
      }
1050
      count++;
S
seemingwang 已提交
1051 1052 1053 1054 1055 1056 1057 1058

      std::string nt = values[0];
      if (nt != node_type) {
        continue;
      }

      size_t index = shard_id - shard_start;

1059 1060 1061
      // auto node = shards[index]->add_feature_node(id);
      auto node = feature_shards[idx][index]->add_feature_node(id);
      node->set_feature_size(feat_name[idx].size());
S
seemingwang 已提交
1062 1063

      for (size_t slice = 2; slice < values.size(); slice++) {
1064
        auto feat = this->parse_feature(idx, values[slice]);
S
seemingwang 已提交
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
        if (feat.first >= 0) {
          node->set_feature(feat.first, feat.second);
        } else {
          VLOG(4) << "Node feature:  " << values[slice]
                  << " not in feature_map.";
        }
      }
      valid_count++;
    }
  }

  VLOG(0) << valid_count << "/" << count << " nodes in type " << node_type
          << " are loaded successfully in " << path;
  return 0;
}

1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
int32_t GraphTable::build_sampler(int idx, std::string sample_type) {
  for (auto &shard : edge_shards[idx]) {
    auto bucket = shard->get_bucket();
    for (size_t i = 0; i < bucket.size(); i++) {
      bucket[i]->build_sampler(sample_type);
    }
  }
  return 0;
}
int32_t GraphTable::load_edges(const std::string &path, bool reverse_edge,
                               const std::string &edge_type) {
1092 1093 1094 1095 1096
#ifdef PADDLE_WITH_HETERPS
  // if (gpups_mode) pthread_rwlock_rdlock(rw_lock.get());
  if (search_level == 2) total_memory_cost = 0;
  const int64_t fixed_load_edges = 1000000;
#endif
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
  int idx = 0;
  if (edge_type == "") {
    VLOG(0) << "edge_type not specified, loading edges to " << id_to_edge[0]
            << " part";
  } else {
    if (edge_to_id.find(edge_type) == edge_to_id.end()) {
      VLOG(0) << "edge_type " << edge_type
              << " is not defined, nothing will be loaded";
      return 0;
    }
    idx = edge_to_id[edge_type];
  }
1109

S
seemingwang 已提交
1110
  auto paths = paddle::string::split_string<std::string>(path, ";");
S
seemingwang 已提交
1111
  int64_t count = 0;
S
seemingwang 已提交
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
  std::string sample_type = "random";
  bool is_weighted = false;
  int valid_count = 0;
  for (auto path : paths) {
    std::ifstream file(path);
    std::string line;
    while (std::getline(file, line)) {
      auto values = paddle::string::split_string<std::string>(line, "\t");
      count++;
      if (values.size() < 2) continue;
      auto src_id = std::stoull(values[0]);
      auto dst_id = std::stoull(values[1]);
      if (reverse_edge) {
        std::swap(src_id, dst_id);
      }
      float weight = 1;
      if (values.size() == 3) {
        weight = std::stof(values[2]);
        sample_type = "weighted";
        is_weighted = true;
      }

      size_t src_shard_id = src_id % shard_num;

      if (src_shard_id >= shard_end || src_shard_id < shard_start) {
1137 1138
        VLOG(4) << "will not load " << src_id << " from " << path
                << ", please check id distribution";
S
seemingwang 已提交
1139 1140
        continue;
      }
1141

S
seemingwang 已提交
1142 1143
      if (count % 1000000 == 0) {
        VLOG(0) << count << " edges are loaded from filepath";
1144
        VLOG(0) << line;
S
seemingwang 已提交
1145 1146 1147
      }

      size_t index = src_shard_id - shard_start;
1148 1149
      edge_shards[idx][index]->add_graph_node(src_id)->build_edges(is_weighted);
      edge_shards[idx][index]->add_neighbor(src_id, dst_id, weight);
S
seemingwang 已提交
1150
      valid_count++;
1151 1152 1153 1154 1155 1156 1157 1158 1159
#ifdef PADDLE_WITH_HETERPS
      // if (gpups_mode) pthread_rwlock_rdlock(rw_lock.get());
      if (count > fixed_load_edges && search_level == 2) {
        dump_edges_to_ssd(idx);
        VLOG(0) << "dumping edges to ssd, edge count is reset to 0";
        clear_graph(idx);
        count = 0;
      }
#endif
S
seemingwang 已提交
1160 1161 1162 1163 1164
    }
  }
  VLOG(0) << valid_count << "/" << count << " edges are loaded successfully in "
          << path;

1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
// Build Sampler j
#ifdef PADDLE_WITH_HETERPS
  // if (gpups_mode) pthread_rwlock_rdlock(rw_lock.get());
  if (search_level == 2) {
    if (count > 0) {
      dump_edges_to_ssd(idx);
      VLOG(0) << "dumping edges to ssd, edge count is reset to 0";
      clear_graph(idx);
      count = 0;
    }
    return 0;
  }
#endif
1178
  for (auto &shard : edge_shards[idx]) {
1179 1180 1181 1182 1183 1184
    auto bucket = shard->get_bucket();
    for (size_t i = 0; i < bucket.size(); i++) {
      bucket[i]->build_sampler(sample_type);
    }
  }

S
seemingwang 已提交
1185 1186 1187
  return 0;
}

1188
Node *GraphTable::find_node(int type_id, int idx, int64_t id) {
S
seemingwang 已提交
1189 1190
  size_t shard_id = id % shard_num;
  if (shard_id >= shard_end || shard_id < shard_start) {
1191
    return nullptr;
S
seemingwang 已提交
1192 1193
  }
  size_t index = shard_id - shard_start;
1194 1195
  auto &search_shards = type_id == 0 ? edge_shards[idx] : feature_shards[idx];
  Node *node = search_shards[index]->find_node(id);
S
seemingwang 已提交
1196 1197
  return node;
}
1198
uint32_t GraphTable::get_thread_pool_index(int64_t node_id) {
1199
  return node_id % shard_num % shard_num_per_server % task_pool_size_;
S
seemingwang 已提交
1200
}
1201

1202
uint32_t GraphTable::get_thread_pool_index_by_shard_index(int64_t shard_index) {
S
seemingwang 已提交
1203
  return shard_index % shard_num_per_server % task_pool_size_;
1204 1205
}

1206 1207
int32_t GraphTable::clear_nodes(int type_id, int idx) {
  auto &search_shards = type_id == 0 ? edge_shards[idx] : feature_shards[idx];
Z
zhangchunle 已提交
1208
  for (size_t i = 0; i < search_shards.size(); i++) {
1209
    search_shards[i]->clear();
1210 1211 1212 1213
  }
  return 0;
}

1214
int32_t GraphTable::random_sample_nodes(int type_id, int idx, int sample_size,
S
seemingwang 已提交
1215 1216 1217
                                        std::unique_ptr<char[]> &buffer,
                                        int &actual_size) {
  int total_size = 0;
1218
  auto &shards = type_id == 0 ? edge_shards[idx] : feature_shards[idx];
1219
  for (int i = 0; i < (int)shards.size(); i++) {
1220
    total_size += shards[i]->get_size();
S
seemingwang 已提交
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
  }
  if (sample_size > total_size) sample_size = total_size;
  int range_num = random_sample_nodes_ranges;
  if (range_num > sample_size) range_num = sample_size;
  if (sample_size == 0 || range_num == 0) return 0;
  std::vector<int> ranges_len, ranges_pos;
  int remain = sample_size, last_pos = -1, num;
  std::set<int> separator_set;
  for (int i = 0; i < range_num - 1; i++) {
    while (separator_set.find(num = rand() % (sample_size - 1)) !=
           separator_set.end())
      ;
    separator_set.insert(num);
  }
  for (auto p : separator_set) {
    ranges_len.push_back(p - last_pos);
    last_pos = p;
  }
  ranges_len.push_back(sample_size - 1 - last_pos);
  remain = total_size - sample_size + range_num;
  separator_set.clear();
  for (int i = 0; i < range_num; i++) {
    while (separator_set.find(num = rand() % remain) != separator_set.end())
      ;
    separator_set.insert(num);
  }
  int used = 0, index = 0;
  last_pos = -1;
  for (auto p : separator_set) {
    used += p - last_pos - 1;
    last_pos = p;
    ranges_pos.push_back(used);
    used += ranges_len[index++];
  }
  std::vector<std::pair<int, int>> first_half, second_half;
  int start_index = rand() % total_size;
1257
  for (size_t i = 0; i < ranges_len.size() && i < ranges_pos.size(); i++) {
S
seemingwang 已提交
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
    if (ranges_pos[i] + ranges_len[i] - 1 + start_index < total_size)
      first_half.push_back({ranges_pos[i] + start_index,
                            ranges_pos[i] + ranges_len[i] + start_index});
    else if (ranges_pos[i] + start_index >= total_size) {
      second_half.push_back(
          {ranges_pos[i] + start_index - total_size,
           ranges_pos[i] + ranges_len[i] + start_index - total_size});
    } else {
      first_half.push_back({ranges_pos[i] + start_index, total_size});
      second_half.push_back(
          {0, ranges_pos[i] + ranges_len[i] + start_index - total_size});
    }
  }
  for (auto &pair : first_half) second_half.push_back(pair);
1272
  std::vector<int64_t> res;
1273
  get_nodes_ids_by_ranges(type_id, idx, second_half, res);
1274
  actual_size = res.size() * sizeof(int64_t);
S
seemingwang 已提交
1275 1276 1277 1278 1279
  buffer.reset(new char[actual_size]);
  char *pointer = buffer.get();
  memcpy(pointer, res.data(), actual_size);
  return 0;
}
1280
int32_t GraphTable::random_sample_neighbors(
1281
    int idx, int64_t *node_ids, int sample_size,
1282 1283
    std::vector<std::shared_ptr<char>> &buffers, std::vector<int> &actual_sizes,
    bool need_weight) {
S
seemingwang 已提交
1284
  size_t node_num = buffers.size();
1285
  std::function<void(char *)> char_del = [](char *c) { delete[] c; };
S
seemingwang 已提交
1286
  std::vector<std::future<int>> tasks;
1287 1288
  std::vector<std::vector<uint32_t>> seq_id(task_pool_size_);
  std::vector<std::vector<SampleKey>> id_list(task_pool_size_);
S
seemingwang 已提交
1289
  size_t index;
1290 1291 1292 1293
  for (size_t idy = 0; idy < node_num; ++idy) {
    index = get_thread_pool_index(node_ids[idy]);
    seq_id[index].emplace_back(idy);
    id_list[index].emplace_back(idx, node_ids[idy], sample_size, need_weight);
S
seemingwang 已提交
1294
  }
1295

1296
  for (int i = 0; i < (int)seq_id.size(); i++) {
S
seemingwang 已提交
1297 1298
    if (seq_id[i].size() == 0) continue;
    tasks.push_back(_shards_task_pool[i]->enqueue([&, i, this]() -> int {
1299
      int64_t node_id;
S
seemingwang 已提交
1300 1301 1302 1303
      std::vector<std::pair<SampleKey, SampleResult>> r;
      LRUResponse response = LRUResponse::blocked;
      if (use_cache) {
        response =
1304
            scaled_lru->query(i, id_list[i].data(), id_list[i].size(), r);
S
seemingwang 已提交
1305 1306 1307 1308 1309 1310
      }
      int index = 0;
      std::vector<SampleResult> sample_res;
      std::vector<SampleKey> sample_keys;
      auto &rng = _shards_task_rng_pool[i];
      for (size_t k = 0; k < id_list[i].size(); k++) {
1311
        if (index < (int)r.size() &&
S
seemingwang 已提交
1312
            r[index].first.node_key == id_list[i][k].node_key) {
1313 1314 1315
          int idy = seq_id[i][k];
          actual_sizes[idy] = r[index].second.actual_size;
          buffers[idy] = r[index].second.buffer;
S
seemingwang 已提交
1316 1317 1318
          index++;
        } else {
          node_id = id_list[i][k].node_key;
1319 1320 1321
          Node *node = find_node(0, idx, node_id);
          int idy = seq_id[i][k];
          int &actual_size = actual_sizes[idy];
S
seemingwang 已提交
1322
          if (node == nullptr) {
1323 1324
#ifdef PADDLE_WITH_HETERPS
            if (search_level == 2) {
S
seemingwang 已提交
1325
              VLOG(2) << "enter sample from ssd for node_id " << node_id;
1326
              char *buffer_addr = random_sample_neighbor_from_ssd(
1327
                  idx, node_id, sample_size, rng, actual_size);
1328
              if (actual_size != 0) {
S
seemingwang 已提交
1329
                std::shared_ptr<char> &buffer = buffers[idy];
1330 1331
                buffer.reset(buffer_addr, char_del);
              }
S
seemingwang 已提交
1332
              VLOG(2) << "actual sampled size from ssd = " << actual_sizes[idy];
1333 1334 1335
              continue;
            }
#endif
S
seemingwang 已提交
1336 1337 1338
            actual_size = 0;
            continue;
          }
1339
          std::shared_ptr<char> &buffer = buffers[idy];
S
seemingwang 已提交
1340
          std::vector<int> res = node->sample_k(sample_size, rng);
1341 1342 1343
          actual_size =
              res.size() * (need_weight ? (Node::id_size + Node::weight_size)
                                        : Node::id_size);
S
seemingwang 已提交
1344
          int offset = 0;
1345
          int64_t id;
S
seemingwang 已提交
1346 1347 1348
          float weight;
          char *buffer_addr = new char[actual_size];
          if (response == LRUResponse::ok) {
1349
            sample_keys.emplace_back(idx, node_id, sample_size, need_weight);
S
seemingwang 已提交
1350 1351
            sample_res.emplace_back(actual_size, buffer_addr);
            buffer = sample_res.back().buffer;
1352
          } else {
S
seemingwang 已提交
1353 1354 1355 1356 1357 1358
            buffer.reset(buffer_addr, char_del);
          }
          for (int &x : res) {
            id = node->get_neighbor_id(x);
            memcpy(buffer_addr + offset, &id, Node::id_size);
            offset += Node::id_size;
1359 1360 1361 1362 1363
            if (need_weight) {
              weight = node->get_neighbor_weight(x);
              memcpy(buffer_addr + offset, &weight, Node::weight_size);
              offset += Node::weight_size;
            }
1364 1365
          }
        }
1366
      }
S
seemingwang 已提交
1367 1368 1369
      if (sample_res.size()) {
        scaled_lru->insert(i, sample_keys.data(), sample_res.data(),
                           sample_keys.size());
1370 1371 1372
      }
      return 0;
    }));
S
seemingwang 已提交
1373
  }
S
seemingwang 已提交
1374 1375
  for (auto &t : tasks) {
    t.get();
S
seemingwang 已提交
1376 1377 1378 1379
  }
  return 0;
}

1380
int32_t GraphTable::get_node_feat(int idx, const std::vector<int64_t> &node_ids,
S
seemingwang 已提交
1381 1382 1383 1384
                                  const std::vector<std::string> &feature_names,
                                  std::vector<std::vector<std::string>> &res) {
  size_t node_num = node_ids.size();
  std::vector<std::future<int>> tasks;
1385 1386
  for (size_t idy = 0; idy < node_num; ++idy) {
    int64_t node_id = node_ids[idy];
S
seemingwang 已提交
1387
    tasks.push_back(_shards_task_pool[get_thread_pool_index(node_id)]->enqueue(
1388 1389
        [&, idx, idy, node_id]() -> int {
          Node *node = find_node(1, idx, node_id);
S
seemingwang 已提交
1390 1391 1392 1393

          if (node == nullptr) {
            return 0;
          }
1394 1395
          for (int feat_idx = 0; feat_idx < (int)feature_names.size();
               ++feat_idx) {
S
seemingwang 已提交
1396
            const std::string &feature_name = feature_names[feat_idx];
1397
            if (feat_id_map[idx].find(feature_name) != feat_id_map[idx].end()) {
S
seemingwang 已提交
1398 1399
              // res[feat_idx][idx] =
              // node->get_feature(feat_id_map[feature_name]);
1400 1401
              auto feat = node->get_feature(feat_id_map[idx][feature_name]);
              res[feat_idx][idy] = feat;
S
seemingwang 已提交
1402 1403 1404 1405
            }
          }
          return 0;
        }));
S
seemingwang 已提交
1406
  }
1407 1408
  for (size_t idy = 0; idy < node_num; ++idy) {
    tasks[idy].get();
S
seemingwang 已提交
1409 1410 1411 1412 1413
  }
  return 0;
}

int32_t GraphTable::set_node_feat(
1414
    int idx, const std::vector<int64_t> &node_ids,
S
seemingwang 已提交
1415 1416 1417 1418
    const std::vector<std::string> &feature_names,
    const std::vector<std::vector<std::string>> &res) {
  size_t node_num = node_ids.size();
  std::vector<std::future<int>> tasks;
1419 1420
  for (size_t idy = 0; idy < node_num; ++idy) {
    int64_t node_id = node_ids[idy];
S
seemingwang 已提交
1421
    tasks.push_back(_shards_task_pool[get_thread_pool_index(node_id)]->enqueue(
1422
        [&, idx, idy, node_id]() -> int {
S
seemingwang 已提交
1423
          size_t index = node_id % this->shard_num - this->shard_start;
1424 1425
          auto node = feature_shards[idx][index]->add_feature_node(node_id);
          node->set_feature_size(this->feat_name[idx].size());
1426 1427
          for (int feat_idx = 0; feat_idx < (int)feature_names.size();
               ++feat_idx) {
S
seemingwang 已提交
1428
            const std::string &feature_name = feature_names[feat_idx];
1429 1430 1431
            if (feat_id_map[idx].find(feature_name) != feat_id_map[idx].end()) {
              node->set_feature(feat_id_map[idx][feature_name],
                                res[feat_idx][idy]);
S
seemingwang 已提交
1432 1433 1434 1435
            }
          }
          return 0;
        }));
S
seemingwang 已提交
1436
  }
1437 1438
  for (size_t idy = 0; idy < node_num; ++idy) {
    tasks[idy].get();
S
seemingwang 已提交
1439 1440 1441 1442 1443
  }
  return 0;
}

std::pair<int32_t, std::string> GraphTable::parse_feature(
1444
    int idx, std::string feat_str) {
S
seemingwang 已提交
1445 1446 1447
  // Return (feat_id, btyes) if name are in this->feat_name, else return (-1,
  // "")
  auto fields = paddle::string::split_string<std::string>(feat_str, " ");
1448 1449 1450 1451
  if (feat_id_map[idx].count(fields[0])) {
    // if (this->feat_id_map.count(fields[0])) {
    int32_t id = this->feat_id_map[idx][fields[0]];
    std::string dtype = this->feat_dtype[idx][id];
S
seemingwang 已提交
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
    std::vector<std::string> values(fields.begin() + 1, fields.end());
    if (dtype == "feasign") {
      return std::make_pair<int32_t, std::string>(
          int32_t(id), paddle::string::join_strings(values, ' '));
    } else if (dtype == "string") {
      return std::make_pair<int32_t, std::string>(
          int32_t(id), paddle::string::join_strings(values, ' '));
    } else if (dtype == "float32") {
      return std::make_pair<int32_t, std::string>(
          int32_t(id), FeatureNode::parse_value_to_bytes<float>(values));
    } else if (dtype == "float64") {
      return std::make_pair<int32_t, std::string>(
          int32_t(id), FeatureNode::parse_value_to_bytes<double>(values));
    } else if (dtype == "int32") {
      return std::make_pair<int32_t, std::string>(
          int32_t(id), FeatureNode::parse_value_to_bytes<int32_t>(values));
    } else if (dtype == "int64") {
      return std::make_pair<int32_t, std::string>(
          int32_t(id), FeatureNode::parse_value_to_bytes<int64_t>(values));
    }
  }
  return std::make_pair<int32_t, std::string>(-1, "");
}

1476 1477 1478 1479 1480
std::vector<std::vector<int64_t>> GraphTable::get_all_id(int type_id, int idx,
                                                         int slice_num) {
  std::vector<std::vector<int64_t>> res(slice_num);
  auto &search_shards = type_id == 0 ? edge_shards[idx] : feature_shards[idx];
  std::vector<std::future<std::vector<int64_t>>> tasks;
Z
zhangchunle 已提交
1481
  for (size_t i = 0; i < search_shards.size(); i++) {
1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
    tasks.push_back(_shards_task_pool[i % task_pool_size_]->enqueue(
        [&search_shards, i]() -> std::vector<int64_t> {
          return search_shards[i]->get_all_id();
        }));
  }
  for (size_t i = 0; i < tasks.size(); ++i) {
    tasks[i].wait();
  }
  for (size_t i = 0; i < tasks.size(); i++) {
    auto ids = tasks[i].get();
T
Thunderbrook 已提交
1492
    for (auto &id : ids) res[(uint64_t)(id) % slice_num].push_back(id);
1493 1494 1495
  }
  return res;
}
1496 1497
int32_t GraphTable::pull_graph_list(int type_id, int idx, int start,
                                    int total_size,
S
seemingwang 已提交
1498 1499 1500 1501 1502
                                    std::unique_ptr<char[]> &buffer,
                                    int &actual_size, bool need_feature,
                                    int step) {
  if (start < 0) start = 0;
  int size = 0, cur_size;
1503
  auto &search_shards = type_id == 0 ? edge_shards[idx] : feature_shards[idx];
S
seemingwang 已提交
1504
  std::vector<std::future<std::vector<Node *>>> tasks;
1505 1506
  for (size_t i = 0; i < search_shards.size() && total_size > 0; i++) {
    cur_size = search_shards[i]->get_size();
S
seemingwang 已提交
1507 1508 1509 1510 1511 1512 1513
    if (size + cur_size <= start) {
      size += cur_size;
      continue;
    }
    int count = std::min(1 + (size + cur_size - start - 1) / step, total_size);
    int end = start + (count - 1) * step + 1;
    tasks.push_back(_shards_task_pool[i % task_pool_size_]->enqueue(
1514 1515 1516
        [&search_shards, this, i, start, end, step,
         size]() -> std::vector<Node *> {
          return search_shards[i]->get_batch(start - size, end - size, step);
S
seemingwang 已提交
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
        }));
    start += count * step;
    total_size -= count;
    size += cur_size;
  }
  for (size_t i = 0; i < tasks.size(); ++i) {
    tasks[i].wait();
  }
  size = 0;
  std::vector<std::vector<Node *>> res;
  for (size_t i = 0; i < tasks.size(); i++) {
    res.push_back(tasks[i].get());
    for (size_t j = 0; j < res.back().size(); j++) {
      size += res.back()[j]->get_size(need_feature);
    }
  }
  char *buffer_addr = new char[size];
  buffer.reset(buffer_addr);
  int index = 0;
  for (size_t i = 0; i < res.size(); i++) {
    for (size_t j = 0; j < res[i].size(); j++) {
      res[i][j]->to_buffer(buffer_addr + index, need_feature);
      index += res[i][j]->get_size(need_feature);
    }
  }
  actual_size = size;
  return 0;
}
S
seemingwang 已提交
1545

1546
int32_t GraphTable::get_server_index_by_id(int64_t id) {
S
seemingwang 已提交
1547 1548
  return id % shard_num / shard_num_per_server;
}
Z
zhaocaibei123 已提交
1549
int32_t GraphTable::Initialize(const TableParameter &config,
1550 1551 1552
                               const FsClientParameter &fs_config) {
  LOG(INFO) << "in graphTable initialize";
  _config = config;
Z
zhaocaibei123 已提交
1553
  if (InitializeAccessor() != 0) {
1554 1555 1556
    LOG(WARNING) << "Table accessor initialize failed";
    return -1;
  }
S
seemingwang 已提交
1557

1558 1559 1560 1561 1562 1563 1564
  if (_afs_client.initialize(fs_config) != 0) {
    LOG(WARNING) << "Table fs_client initialize failed";
    // return -1;
  }
  auto graph = config.graph_parameter();
  shard_num = _config.shard_num();
  LOG(INFO) << "in graphTable initialize over";
Z
zhaocaibei123 已提交
1565
  return Initialize(graph);
1566
}
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584

void GraphTable::load_node_weight(int type_id, int idx, std::string path) {
  auto paths = paddle::string::split_string<std::string>(path, ";");
  int64_t count = 0;
  auto &weight_map = node_weight[type_id][idx];
  for (auto path : paths) {
    std::ifstream file(path);
    std::string line;
    while (std::getline(file, line)) {
      auto values = paddle::string::split_string<std::string>(line, "\t");
      count++;
      if (values.size() < 2) continue;
      auto src_id = std::stoull(values[0]);
      double weight = std::stod(values[1]);
      weight_map[src_id] = weight;
    }
  }
}
Z
zhaocaibei123 已提交
1585
int32_t GraphTable::Initialize(const GraphParameter &graph) {
1586
  task_pool_size_ = graph.task_pool_size();
1587

1588
#ifdef PADDLE_WITH_HETERPS
1589 1590 1591 1592 1593
  _db = NULL;
  search_level = graph.search_level();
  if (search_level >= 2) {
    _db = paddle::distributed::RocksDBHandler::GetInstance();
    _db->initialize("./temp_gpups_db", task_pool_size_);
1594
  }
1595 1596 1597 1598 1599 1600 1601 1602 1603
// gpups_mode = true;
// auto *sampler =
//     CREATE_PSCORE_CLASS(GraphSampler, graph.gpups_graph_sample_class());
// auto slices =
//     string::split_string<std::string>(graph.gpups_graph_sample_args(), ",");
// std::cout << "slices" << std::endl;
// for (auto x : slices) std::cout << x << std::endl;
// sampler->init(graph.gpu_num(), this, slices);
// graph_sampler.reset(sampler);
1604
#endif
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
  if (shard_num == 0) {
    server_num = 1;
    _shard_idx = 0;
    shard_num = graph.shard_num();
  }
  use_cache = graph.use_cache();
  if (use_cache) {
    cache_size_limit = graph.cache_size_limit();
    cache_ttl = graph.cache_ttl();
    make_neighbor_sample_cache((size_t)cache_size_limit, (size_t)cache_ttl);
  }
S
seemingwang 已提交
1616 1617 1618
  _shards_task_pool.resize(task_pool_size_);
  for (size_t i = 0; i < _shards_task_pool.size(); ++i) {
    _shards_task_pool[i].reset(new ::ThreadPool(1));
1619
    _shards_task_rng_pool.push_back(paddle::framework::GetCPURandomEngine(0));
S
seemingwang 已提交
1620
  }
1621
  auto graph_feature = graph.graph_feature();
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
  auto node_types = graph.node_types();
  auto edge_types = graph.edge_types();
  VLOG(0) << "got " << edge_types.size() << "edge types in total";
  feat_id_map.resize(node_types.size());
  for (int k = 0; k < edge_types.size(); k++) {
    VLOG(0) << "in initialize: get a edge_type " << edge_types[k];
    edge_to_id[edge_types[k]] = k;
    id_to_edge.push_back(edge_types[k]);
  }
  feat_name.resize(node_types.size());
  feat_shape.resize(node_types.size());
  feat_dtype.resize(node_types.size());
  VLOG(0) << "got " << node_types.size() << "node types in total";
  for (int k = 0; k < node_types.size(); k++) {
    feature_to_id[node_types[k]] = k;
    auto node_type = node_types[k];
    auto feature = graph_feature[k];
    id_to_feature.push_back(node_type);
    int feat_conf_size = static_cast<int>(feature.name().size());

    for (int i = 0; i < feat_conf_size; i++) {
      // auto &f_name = common.attributes()[i];
      // auto &f_shape = common.dims()[i];
      // auto &f_dtype = common.params()[i];
      auto &f_name = feature.name()[i];
      auto &f_shape = feature.shape()[i];
      auto &f_dtype = feature.dtype()[i];
      feat_name[k].push_back(f_name);
      feat_shape[k].push_back(f_shape);
      feat_dtype[k].push_back(f_dtype);
      feat_id_map[k][f_name] = i;
      VLOG(0) << "init graph table feat conf name:" << f_name
              << " shape:" << f_shape << " dtype:" << f_dtype;
    }
  }
1657 1658 1659 1660
  // this->table_name = common.table_name();
  // this->table_type = common.name();
  this->table_name = graph.table_name();
  this->table_type = graph.table_type();
S
seemingwang 已提交
1661 1662
  VLOG(0) << " init graph table type " << this->table_type << " table name "
          << this->table_name;
1663
  // int feat_conf_size = static_cast<int>(common.attributes().size());
1664
  // int feat_conf_size = static_cast<int>(graph_feature.name().size());
S
seemingwang 已提交
1665 1666
  VLOG(0) << "in init graph table shard num = " << shard_num << " shard_idx"
          << _shard_idx;
S
seemingwang 已提交
1667 1668 1669
  shard_num_per_server = sparse_local_shard_num(shard_num, server_num);
  shard_start = _shard_idx * shard_num_per_server;
  shard_end = shard_start + shard_num_per_server;
S
seemingwang 已提交
1670 1671
  VLOG(0) << "in init graph table shard idx = " << _shard_idx << " shard_start "
          << shard_start << " shard_end " << shard_end;
1672
  edge_shards.resize(id_to_edge.size());
1673 1674
  node_weight.resize(2);
  node_weight[0].resize(id_to_edge.size());
1675 1676 1677
#ifdef PADDLE_WITH_HETERPS
  partitions.resize(id_to_edge.size());
#endif
1678 1679 1680 1681
  for (int k = 0; k < (int)edge_shards.size(); k++) {
    for (size_t i = 0; i < shard_num_per_server; i++) {
      edge_shards[k].push_back(new GraphShard());
    }
1682
  }
1683
  node_weight[1].resize(id_to_feature.size());
1684 1685 1686 1687 1688
  feature_shards.resize(id_to_feature.size());
  for (int k = 0; k < (int)feature_shards.size(); k++) {
    for (size_t i = 0; i < shard_num_per_server; i++) {
      feature_shards[k].push_back(new GraphShard());
    }
1689 1690
  }

S
seemingwang 已提交
1691 1692
  return 0;
}
1693

1694 1695
}  // namespace distributed
};  // namespace paddle