randomwalk.cc 7.93 KB
Newer Older
1
2
3
4
5
6
7
8
/*!
 *  Copyright (c) 2018 by Contributors
 * \file graph/sampler.cc
 * \brief DGL sampler implementation
 */

#include <dmlc/omp.h>
#include <dgl/immutable_graph.h>
9
#include <dgl/packed_func_ext.h>
10
#include <dgl/random.h>
11
12
13
14
15
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <numeric>
#include <functional>
16
17
18
#include <vector>
#include "randomwalk.h"
#include "../../c_api_common.h"
19

20
using namespace dgl::runtime;
21
22
23

namespace dgl {

24
25
namespace sampling {

26
using Walker = std::function<dgl_id_t(const GraphInterface *, dgl_id_t)>;
27
28
29
30
31
32
33
34
35
36
37
38
39
40

namespace {

/*!
 * \brief Randomly select a single direct successor given the current vertex
 * \return Whether such a successor could be found
 */
dgl_id_t WalkOneHop(
    const GraphInterface *gptr,
    dgl_id_t cur) {
  const auto succ = gptr->SuccVec(cur);
  const size_t size = succ.size();
  if (size == 0)
    return DGL_INVALID_ID;
41
  return succ[RandomEngine::ThreadLocal()->RandInt(size)];
42
43
44
45
46
47
48
49
50
51
52
53
}

/*!
 * \brief Randomly select a single direct successor after \c hops hops given the current vertex
 * \return Whether such a successor could be found
 */
template<int hops>
dgl_id_t WalkMultipleHops(
    const GraphInterface *gptr,
    dgl_id_t cur) {
  dgl_id_t next;
  for (int i = 0; i < hops; ++i) {
54
    if ((next = WalkOneHop(gptr, cur)) == DGL_INVALID_ID)
55
56
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
87
      return DGL_INVALID_ID;
    cur = next;
  }
  return cur;
}

IdArray GenericRandomWalk(
    const GraphInterface *gptr,
    IdArray seeds,
    int num_traces,
    int num_hops,
    Walker walker) {
  const int64_t num_nodes = seeds->shape[0];
  const dgl_id_t *seed_ids = static_cast<dgl_id_t *>(seeds->data);
  IdArray traces = IdArray::Empty(
      {num_nodes, num_traces, num_hops + 1},
      DLDataType{kDLInt, 64, 1},
      DLContext{kDLCPU, 0});
  dgl_id_t *trace_data = static_cast<dgl_id_t *>(traces->data);

  // FIXME: does OpenMP work with exceptions?  Especially without throwing SIGABRT?
  dgl_id_t next;

  for (int64_t i = 0; i < num_nodes; ++i) {
    const dgl_id_t seed_id = seed_ids[i];

    for (int j = 0; j < num_traces; ++j) {
      dgl_id_t cur = seed_id;
      const int kmax = num_hops + 1;

      for (int k = 0; k < kmax; ++k) {
        const int64_t offset = (i * num_traces + j) * kmax + k;
        trace_data[offset] = cur;
88
        if ((next = walker(gptr, cur)) == DGL_INVALID_ID)
89
90
91
92
93
94
95
96
97
          LOG(FATAL) << "no successors from vertex " << cur;
        cur = next;
      }
    }
  }

  return traces;
}

98
RandomWalkTracesPtr GenericRandomWalkWithRestart(
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
    const GraphInterface *gptr,
    IdArray seeds,
    double restart_prob,
    uint64_t visit_threshold_per_seed,
    uint64_t max_visit_counts,
    uint64_t max_frequent_visited_nodes,
    Walker walker) {
  std::vector<dgl_id_t> vertices;
  std::vector<size_t> trace_lengths, trace_counts, visit_counts;
  const dgl_id_t *seed_ids = static_cast<dgl_id_t *>(seeds->data);
  const uint64_t num_nodes = seeds->shape[0];

  visit_counts.resize(gptr->NumVertices());

  for (uint64_t i = 0; i < num_nodes; ++i) {
    int stop = 0;
    size_t total_trace_length = 0;
    size_t num_traces = 0;
    uint64_t num_frequent_visited_nodes = 0;
    std::fill(visit_counts.begin(), visit_counts.end(), 0);

    while (1) {
      dgl_id_t cur = seed_ids[i], next;
      size_t trace_length = 0;

      for (; ; ++trace_length) {
        if ((trace_length > 0) &&
            (++visit_counts[cur] == max_visit_counts) &&
            (++num_frequent_visited_nodes == max_frequent_visited_nodes))
          stop = 1;

130
131
        if ((trace_length > 0) &&
            (RandomEngine::ThreadLocal()->Uniform<double>() < restart_prob))
132
133
          break;

134
        if ((next = walker(gptr, cur)) == DGL_INVALID_ID)
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
          LOG(FATAL) << "no successors from vertex " << cur;
        cur = next;
        vertices.push_back(cur);
      }

      total_trace_length += trace_length;
      ++num_traces;
      trace_lengths.push_back(trace_length);
      if ((total_trace_length >= visit_threshold_per_seed) || stop)
        break;
    }

    trace_counts.push_back(num_traces);
  }

150
151
  RandomWalkTraces *traces = new RandomWalkTraces;
  traces->trace_counts = IdArray::Empty(
152
153
154
      {static_cast<int64_t>(trace_counts.size())},
      DLDataType{kDLInt, 64, 1},
      DLContext{kDLCPU, 0});
155
  traces->trace_lengths = IdArray::Empty(
156
157
158
      {static_cast<int64_t>(trace_lengths.size())},
      DLDataType{kDLInt, 64, 1},
      DLContext{kDLCPU, 0});
159
  traces->vertices = IdArray::Empty(
160
161
162
163
      {static_cast<int64_t>(vertices.size())},
      DLDataType{kDLInt, 64, 1},
      DLContext{kDLCPU, 0});

164
165
166
  dgl_id_t *trace_counts_data = static_cast<dgl_id_t *>(traces->trace_counts->data);
  dgl_id_t *trace_lengths_data = static_cast<dgl_id_t *>(traces->trace_lengths->data);
  dgl_id_t *vertices_data = static_cast<dgl_id_t *>(traces->vertices->data);
167
168
169
170
171

  std::copy(trace_counts.begin(), trace_counts.end(), trace_counts_data);
  std::copy(trace_lengths.begin(), trace_lengths.end(), trace_lengths_data);
  std::copy(vertices.begin(), vertices.end(), vertices_data);

172
  return RandomWalkTracesPtr(traces);
173
174
175
176
177
178
179
180
181
182
183
184
}

};  // namespace

IdArray RandomWalk(
    const GraphInterface *gptr,
    IdArray seeds,
    int num_traces,
    int num_hops) {
  return GenericRandomWalk(gptr, seeds, num_traces, num_hops, WalkMultipleHops<1>);
}

185
RandomWalkTracesPtr RandomWalkWithRestart(
186
187
188
189
190
191
192
193
194
195
196
    const GraphInterface *gptr,
    IdArray seeds,
    double restart_prob,
    uint64_t visit_threshold_per_seed,
    uint64_t max_visit_counts,
    uint64_t max_frequent_visited_nodes) {
  return GenericRandomWalkWithRestart(
      gptr, seeds, restart_prob, visit_threshold_per_seed, max_visit_counts,
      max_frequent_visited_nodes, WalkMultipleHops<1>);
}

197
RandomWalkTracesPtr BipartiteSingleSidedRandomWalkWithRestart(
198
199
200
201
202
203
204
205
206
207
208
    const GraphInterface *gptr,
    IdArray seeds,
    double restart_prob,
    uint64_t visit_threshold_per_seed,
    uint64_t max_visit_counts,
    uint64_t max_frequent_visited_nodes) {
  return GenericRandomWalkWithRestart(
      gptr, seeds, restart_prob, visit_threshold_per_seed, max_visit_counts,
      max_frequent_visited_nodes, WalkMultipleHops<2>);
}

209
DGL_REGISTER_GLOBAL("sampler.randomwalk._CAPI_DGLRandomWalk")
210
.set_body([] (DGLArgs args, DGLRetValue* rv) {
211
    GraphRef g = args[0];
212
    const IdArray seeds = args[1];
213
214
215
    const int num_traces = args[2];
    const int num_hops = args[3];

216
217
218
219
    CHECK(aten::IsValidIdArray(seeds));
    CHECK_EQ(seeds->ctx.device_type, kDLCPU)
      << "RandomWalk only support CPU sampling";

220
    *rv = RandomWalk(g.sptr().get(), seeds, num_traces, num_hops);
221
222
  });

223
DGL_REGISTER_GLOBAL("sampler.randomwalk._CAPI_DGLRandomWalkWithRestart")
224
.set_body([] (DGLArgs args, DGLRetValue* rv) {
225
    GraphRef g = args[0];
226
    const IdArray seeds = args[1];
227
228
229
230
231
    const double restart_prob = args[2];
    const uint64_t visit_threshold_per_seed = args[3];
    const uint64_t max_visit_counts = args[4];
    const uint64_t max_frequent_visited_nodes = args[5];

232
233
234
235
    CHECK(aten::IsValidIdArray(seeds));
    CHECK_EQ(seeds->ctx.device_type, kDLCPU)
      << "RandomWalkWithRestart only support CPU sampling";

236
    *rv = RandomWalkTracesRef(
237
        RandomWalkWithRestart(g.sptr().get(), seeds, restart_prob, visit_threshold_per_seed,
238
239
240
          max_visit_counts, max_frequent_visited_nodes));
  });

241
DGL_REGISTER_GLOBAL("sampler.randomwalk._CAPI_DGLBipartiteSingleSidedRandomWalkWithRestart")
242
.set_body([] (DGLArgs args, DGLRetValue* rv) {
243
    GraphRef g = args[0];
244
    const IdArray seeds = args[1];
245
246
247
248
249
    const double restart_prob = args[2];
    const uint64_t visit_threshold_per_seed = args[3];
    const uint64_t max_visit_counts = args[4];
    const uint64_t max_frequent_visited_nodes = args[5];

250
251
252
253
    CHECK(aten::IsValidIdArray(seeds));
    CHECK_EQ(seeds->ctx.device_type, kDLCPU)
      << "BipartiteSingleSidedRandomWalkWithRestart only support CPU sampling";

254
    *rv = RandomWalkTracesRef(
255
        BipartiteSingleSidedRandomWalkWithRestart(
256
          g.sptr().get(), seeds, restart_prob, visit_threshold_per_seed,
257
258
259
          max_visit_counts, max_frequent_visited_nodes));
  });

260
261
};  // namespace sampling

262
};  // namespace dgl