This repository has been archived by the owner on Nov 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6.8k
/
dgl_graph.cc
1648 lines (1485 loc) · 59.6 KB
/
dgl_graph.cc
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
88
89
90
91
92
93
94
95
96
97
98
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
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
196
197
198
199
200
201
202
203
204
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
251
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
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
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
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include <mxnet/io.h>
#include <mxnet/base.h>
#include <mxnet/ndarray.h>
#include <mxnet/operator.h>
#include <mxnet/operator_util.h>
#include <dmlc/logging.h>
#include <dmlc/optional.h>
#include <algorithm>
#include <random>
#include "../elemwise_op_common.h"
#include "../../imperative/imperative_utils.h"
#include "../subgraph_op_common.h"
#include "./dgl_graph-inl.h"
namespace mxnet {
namespace op {
typedef int64_t dgl_id_t;
////////////////////////////// Graph Sampling ///////////////////////////////
/*
* ArrayHeap is used to sample elements from vector
*/
class ArrayHeap {
public:
explicit ArrayHeap(const std::vector<float>& prob, unsigned int seed) {
generator_ = std::mt19937(seed);
distribution_ = std::uniform_real_distribution<float>(0.0, 1.0);
vec_size_ = prob.size();
bit_len_ = ceil(log2(vec_size_));
limit_ = 1 << bit_len_;
// allocate twice the size
heap_.resize(limit_ << 1, 0);
// allocate the leaves
for (int i = limit_; i < vec_size_+limit_; ++i) {
heap_[i] = prob[i-limit_];
}
// iterate up the tree (this is O(m))
for (int i = bit_len_-1; i >= 0; --i) {
for (int j = (1 << i); j < (1 << (i + 1)); ++j) {
heap_[j] = heap_[j << 1] + heap_[(j << 1) + 1];
}
}
}
~ArrayHeap() {}
/*
* Remove term from index (this costs O(log m) steps)
*/
void Delete(size_t index) {
size_t i = index + limit_;
float w = heap_[i];
for (int j = bit_len_; j >= 0; --j) {
heap_[i] -= w;
i = i >> 1;
}
}
/*
* Add value w to index (this costs O(log m) steps)
*/
void Add(size_t index, float w) {
size_t i = index + limit_;
for (int j = bit_len_; j >= 0; --j) {
heap_[i] += w;
i = i >> 1;
}
}
/*
* Sample from arrayHeap
*/
size_t Sample() {
float xi = heap_[1] * distribution_(generator_);
int i = 1;
while (i < limit_) {
i = i << 1;
if (xi >= heap_[i]) {
xi -= heap_[i];
i += 1;
}
}
return i - limit_;
}
/*
* Sample a vector by given the size n
*/
void SampleWithoutReplacement(size_t n, std::vector<size_t>* samples) {
// sample n elements
for (size_t i = 0; i < n; ++i) {
samples->at(i) = this->Sample();
this->Delete(samples->at(i));
}
}
private:
int vec_size_; // sample size
int bit_len_; // bit size
int limit_;
std::vector<float> heap_;
std::mt19937 generator_;
std::uniform_real_distribution<float> distribution_;
};
struct NeighborSampleParam : public dmlc::Parameter<NeighborSampleParam> {
int num_args;
dgl_id_t num_hops;
dgl_id_t num_neighbor;
dgl_id_t max_num_vertices;
DMLC_DECLARE_PARAMETER(NeighborSampleParam) {
DMLC_DECLARE_FIELD(num_args).set_lower_bound(2)
.describe("Number of input NDArray.");
DMLC_DECLARE_FIELD(num_hops)
.set_default(1)
.describe("Number of hops.");
DMLC_DECLARE_FIELD(num_neighbor)
.set_default(2)
.describe("Number of neighbor.");
DMLC_DECLARE_FIELD(max_num_vertices)
.set_default(100)
.describe("Max number of vertices.");
}
};
DMLC_REGISTER_PARAMETER(NeighborSampleParam);
/*
* Check uniform Storage Type
*/
static bool CSRNeighborUniformSampleStorageType(const nnvm::NodeAttrs& attrs,
const int dev_mask,
DispatchMode* dispatch_mode,
std::vector<int> *in_attrs,
std::vector<int> *out_attrs) {
const NeighborSampleParam& params = nnvm::get<NeighborSampleParam>(attrs.parsed);
size_t num_subgraphs = params.num_args - 1;
CHECK_EQ(out_attrs->size(), 3 * num_subgraphs);
// input[0] is csr_graph
CHECK_EQ(in_attrs->at(0), mxnet::kCSRStorage);
// the rest input ndarray is seed_vector
for (size_t i = 0; i < num_subgraphs; i++)
CHECK_EQ(in_attrs->at(1 + i), mxnet::kDefaultStorage);
bool success = true;
// sample_id
for (size_t i = 0; i < num_subgraphs; i++) {
if (!type_assign(&(*out_attrs)[i], mxnet::kDefaultStorage)) {
success = false;
}
}
// sub_graph
for (size_t i = 0; i < num_subgraphs; i++) {
if (!type_assign(&(*out_attrs)[i + num_subgraphs], mxnet::kCSRStorage)) {
success = false;
}
}
// sub_layer
for (size_t i = 0; i < num_subgraphs; i++) {
if (!type_assign(&(*out_attrs)[i + 2*num_subgraphs], mxnet::kDefaultStorage)) {
success = false;
}
}
*dispatch_mode = DispatchMode::kFComputeEx;
return success;
}
/*
* Check non-uniform Storage Type
*/
static bool CSRNeighborNonUniformSampleStorageType(const nnvm::NodeAttrs& attrs,
const int dev_mask,
DispatchMode* dispatch_mode,
std::vector<int> *in_attrs,
std::vector<int> *out_attrs) {
const NeighborSampleParam& params =
nnvm::get<NeighborSampleParam>(attrs.parsed);
size_t num_subgraphs = params.num_args - 2;
CHECK_EQ(out_attrs->size(), 4 * num_subgraphs);
// input[0] is csr_graph
CHECK_EQ(in_attrs->at(0), mxnet::kCSRStorage);
// input[1] is probability
CHECK_EQ(in_attrs->at(1), mxnet::kDefaultStorage);
// the rest input ndarray is seed_vector
for (size_t i = 0; i < num_subgraphs; i++)
CHECK_EQ(in_attrs->at(2 + i), mxnet::kDefaultStorage);
bool success = true;
// sample_id
for (size_t i = 0; i < num_subgraphs; i++) {
if (!type_assign(&(*out_attrs)[i], mxnet::kDefaultStorage)) {
success = false;
}
}
// sub_graph
for (size_t i = 0; i < num_subgraphs; i++) {
if (!type_assign(&(*out_attrs)[i + num_subgraphs], mxnet::kCSRStorage)) {
success = false;
}
}
// sub_probability
for (size_t i = 0; i < num_subgraphs; i++) {
if (!type_assign(&(*out_attrs)[i + 2*num_subgraphs], mxnet::kDefaultStorage)) {
success = false;
}
}
// sub_layer
for (size_t i = 0; i < num_subgraphs; i++) {
if (!type_assign(&(*out_attrs)[i + 3*num_subgraphs], mxnet::kDefaultStorage)) {
success = false;
}
}
*dispatch_mode = DispatchMode::kFComputeEx;
return success;
}
/*
* Check uniform Shape
*/
static bool CSRNeighborUniformSampleShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
const NeighborSampleParam& params =
nnvm::get<NeighborSampleParam>(attrs.parsed);
size_t num_subgraphs = params.num_args - 1;
CHECK_EQ(out_attrs->size(), 3 * num_subgraphs);
// input[0] is csr graph
CHECK_EQ(in_attrs->at(0).ndim(), 2U);
CHECK_EQ(in_attrs->at(0)[0], in_attrs->at(0)[1]);
// the rest input ndarray is seed vector
for (size_t i = 0; i < num_subgraphs; i++) {
CHECK_EQ(in_attrs->at(1 + i).ndim(), 1U);
}
// Output
bool success = true;
mxnet::TShape out_shape(1, -1);
// We use the last element to store the actual
// number of vertices in the subgraph.
out_shape[0] = params.max_num_vertices + 1;
for (size_t i = 0; i < num_subgraphs; i++) {
SHAPE_ASSIGN_CHECK(*out_attrs, i, out_shape);
success = success && !mxnet::op::shape_is_none(out_attrs->at(i));
}
// sub_csr
mxnet::TShape out_csr_shape(2, -1);
out_csr_shape[0] = params.max_num_vertices;
out_csr_shape[1] = in_attrs->at(0)[1];
for (size_t i = 0; i < num_subgraphs; i++) {
SHAPE_ASSIGN_CHECK(*out_attrs, i + num_subgraphs, out_csr_shape);
success = success && !mxnet::op::shape_is_none(out_attrs->at(i + num_subgraphs));
}
// sub_layer
mxnet::TShape out_layer_shape(1, -1);
out_layer_shape[0] = params.max_num_vertices;
for (size_t i = 0; i < num_subgraphs; i++) {
SHAPE_ASSIGN_CHECK(*out_attrs, i + 2*num_subgraphs, out_layer_shape);
success = success && !mxnet::op::shape_is_none(out_attrs->at(i + 2 * num_subgraphs));
}
return success;
}
/*
* Check non-uniform Shape
*/
static bool CSRNeighborNonUniformSampleShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
const NeighborSampleParam& params =
nnvm::get<NeighborSampleParam>(attrs.parsed);
size_t num_subgraphs = params.num_args - 2;
CHECK_EQ(out_attrs->size(), 4 * num_subgraphs);
// input[0] is csr graph
CHECK_EQ(in_attrs->at(0).ndim(), 2U);
CHECK_EQ(in_attrs->at(0)[0], in_attrs->at(0)[1]);
// input[1] is probability
CHECK_EQ(in_attrs->at(1).ndim(), 1U);
// the rest ndarray is seed vector
for (size_t i = 0; i < num_subgraphs; i++) {
CHECK_EQ(in_attrs->at(2 + i).ndim(), 1U);
}
// Output
bool success = true;
mxnet::TShape out_shape(1, -1);
// We use the last element to store the actual
// number of vertices in the subgraph.
out_shape[0] = params.max_num_vertices + 1;
for (size_t i = 0; i < num_subgraphs; i++) {
SHAPE_ASSIGN_CHECK(*out_attrs, i, out_shape);
success = success && !mxnet::op::shape_is_none(out_attrs->at(i));
}
// sub_csr
mxnet::TShape out_csr_shape(2, -1);
out_csr_shape[0] = params.max_num_vertices;
out_csr_shape[1] = in_attrs->at(0)[1];
for (size_t i = 0; i < num_subgraphs; i++) {
SHAPE_ASSIGN_CHECK(*out_attrs, i + num_subgraphs, out_csr_shape);
success = success && !mxnet::op::shape_is_none(out_attrs->at(i + num_subgraphs));
}
// sub_probability
mxnet::TShape out_prob_shape(1, -1);
out_prob_shape[0] = params.max_num_vertices;
for (size_t i = 0; i < num_subgraphs; i++) {
SHAPE_ASSIGN_CHECK(*out_attrs, i + 2*num_subgraphs, out_prob_shape);
success = success && !mxnet::op::shape_is_none(out_attrs->at(i + 2 * num_subgraphs));
}
// sub_layer
mxnet::TShape out_layer_shape(1, -1);
out_layer_shape[0] = params.max_num_vertices;
for (size_t i = 0; i < num_subgraphs; i++) {
SHAPE_ASSIGN_CHECK(*out_attrs, i + 3*num_subgraphs, out_prob_shape);
success = success && !mxnet::op::shape_is_none(out_attrs->at(i + 3 * num_subgraphs));
}
return success;
}
/*
* Check uniform Type
*/
static bool CSRNeighborUniformSampleType(const nnvm::NodeAttrs& attrs,
std::vector<int> *in_attrs,
std::vector<int> *out_attrs) {
const NeighborSampleParam& params =
nnvm::get<NeighborSampleParam>(attrs.parsed);
size_t num_subgraphs = params.num_args - 1;
CHECK_EQ(out_attrs->size(), 3 * num_subgraphs);
bool success = true;
for (size_t i = 0; i < num_subgraphs; i++) {
TYPE_ASSIGN_CHECK(*out_attrs, i, in_attrs->at(1));
TYPE_ASSIGN_CHECK(*out_attrs, i + num_subgraphs, in_attrs->at(0));
TYPE_ASSIGN_CHECK(*out_attrs, i + 2*num_subgraphs, in_attrs->at(1));
success = success &&
out_attrs->at(i) != -1 &&
out_attrs->at(i + num_subgraphs) != -1 &&
out_attrs->at(i + 2*num_subgraphs) != -1;
}
return success;
}
/*
* Check non-uniform Type
*/
static bool CSRNeighborNonUniformSampleType(const nnvm::NodeAttrs& attrs,
std::vector<int> *in_attrs,
std::vector<int> *out_attrs) {
const NeighborSampleParam& params =
nnvm::get<NeighborSampleParam>(attrs.parsed);
size_t num_subgraphs = params.num_args - 2;
CHECK_EQ(out_attrs->size(), 4 * num_subgraphs);
bool success = true;
for (size_t i = 0; i < num_subgraphs; i++) {
TYPE_ASSIGN_CHECK(*out_attrs, i, in_attrs->at(2));
TYPE_ASSIGN_CHECK(*out_attrs, i + num_subgraphs, in_attrs->at(0));
TYPE_ASSIGN_CHECK(*out_attrs, i + 2*num_subgraphs, in_attrs->at(1));
TYPE_ASSIGN_CHECK(*out_attrs, i + 3*num_subgraphs, in_attrs->at(2));
success = success &&
out_attrs->at(i) != -1 &&
out_attrs->at(i + num_subgraphs) != -1 &&
out_attrs->at(i + 2*num_subgraphs) != -1 &&
out_attrs->at(i + 3*num_subgraphs) != -1;
}
return success;
}
static void RandomSample(size_t set_size,
size_t num,
std::vector<size_t>* out,
unsigned int seed) {
std::mt19937 generator(seed);
std::unordered_set<size_t> sampled_idxs;
std::uniform_int_distribution<size_t> distribution(0, set_size - 1);
while (sampled_idxs.size() < num) {
sampled_idxs.insert(distribution(generator));
}
out->clear();
for (auto it = sampled_idxs.begin(); it != sampled_idxs.end(); it++) {
out->push_back(*it);
}
}
static void NegateSet(const std::vector<size_t> &idxs,
size_t set_size,
std::vector<size_t>* out) {
// idxs must have been sorted.
auto it = idxs.begin();
size_t i = 0;
CHECK_GT(set_size, idxs.back());
for (; i < set_size && it != idxs.end(); i++) {
if (*it == i) {
it++;
continue;
}
out->push_back(i);
}
for (; i < set_size; i++) {
out->push_back(i);
}
}
/*
* Uniform sample
*/
static void GetUniformSample(const dgl_id_t* val_list,
const dgl_id_t* col_list,
const size_t ver_len,
const size_t max_num_neighbor,
std::vector<dgl_id_t>* out_ver,
std::vector<dgl_id_t>* out_edge,
unsigned int seed) {
// Copy ver_list to output
if (ver_len <= max_num_neighbor) {
for (size_t i = 0; i < ver_len; ++i) {
out_ver->push_back(col_list[i]);
out_edge->push_back(val_list[i]);
}
return;
}
// If we just sample a small number of elements from a large neighbor list.
std::vector<size_t> sorted_idxs;
if (ver_len > max_num_neighbor * 2) {
sorted_idxs.reserve(max_num_neighbor);
RandomSample(ver_len, max_num_neighbor, &sorted_idxs, seed);
std::sort(sorted_idxs.begin(), sorted_idxs.end());
} else {
std::vector<size_t> negate;
negate.reserve(ver_len - max_num_neighbor);
RandomSample(ver_len, ver_len - max_num_neighbor,
&negate, seed);
std::sort(negate.begin(), negate.end());
NegateSet(negate, ver_len, &sorted_idxs);
}
// verify the result.
CHECK_EQ(sorted_idxs.size(), max_num_neighbor);
for (size_t i = 1; i < sorted_idxs.size(); i++) {
CHECK_GT(sorted_idxs[i], sorted_idxs[i - 1]);
}
for (auto idx : sorted_idxs) {
out_ver->push_back(col_list[idx]);
out_edge->push_back(val_list[idx]);
}
}
/*
* Non-uniform sample via ArrayHeap
*/
static void GetNonUniformSample(const float* probability,
const dgl_id_t* val_list,
const dgl_id_t* col_list,
const size_t ver_len,
const size_t max_num_neighbor,
std::vector<dgl_id_t>* out_ver,
std::vector<dgl_id_t>* out_edge,
unsigned int seed) {
// Copy ver_list to output
if (ver_len <= max_num_neighbor) {
for (size_t i = 0; i < ver_len; ++i) {
out_ver->push_back(col_list[i]);
out_edge->push_back(val_list[i]);
}
return;
}
// Make sample
std::vector<size_t> sp_index(max_num_neighbor);
std::vector<float> sp_prob(ver_len);
for (size_t i = 0; i < ver_len; ++i) {
sp_prob[i] = probability[col_list[i]];
}
ArrayHeap arrayHeap(sp_prob, seed);
arrayHeap.SampleWithoutReplacement(max_num_neighbor, &sp_index);
out_ver->resize(max_num_neighbor);
out_edge->resize(max_num_neighbor);
for (size_t i = 0; i < max_num_neighbor; ++i) {
size_t idx = sp_index[i];
out_ver->at(i) = col_list[idx];
out_edge->at(i) = val_list[idx];
}
sort(out_ver->begin(), out_ver->end());
sort(out_edge->begin(), out_edge->end());
}
/*
* Used for subgraph sampling
*/
struct neigh_list {
std::vector<dgl_id_t> neighs;
std::vector<dgl_id_t> edges;
neigh_list(const std::vector<dgl_id_t> &_neighs,
const std::vector<dgl_id_t> &_edges)
: neighs(_neighs), edges(_edges) {}
};
/*
* Sample sub-graph from csr graph
*/
static void SampleSubgraph(const NDArray &csr,
const NDArray &seed_arr,
const NDArray &sampled_ids,
const NDArray &sub_csr,
float* sub_prob,
const NDArray &sub_layer,
const float* probability,
int num_hops,
size_t num_neighbor,
size_t max_num_vertices,
unsigned int random_seed) {
size_t num_seeds = seed_arr.shape().Size();
CHECK_GE(max_num_vertices, num_seeds);
const dgl_id_t* val_list = csr.data().dptr<dgl_id_t>();
const dgl_id_t* col_list = csr.aux_data(csr::kIdx).dptr<dgl_id_t>();
const dgl_id_t* indptr = csr.aux_data(csr::kIndPtr).dptr<dgl_id_t>();
const dgl_id_t* seed = seed_arr.data().dptr<dgl_id_t>();
dgl_id_t* out = sampled_ids.data().dptr<dgl_id_t>();
dgl_id_t* out_layer = sub_layer.data().dptr<dgl_id_t>();
// BFS traverse the graph and sample vertices
// <vertex_id, layer_id>
std::unordered_set<dgl_id_t> sub_ver_mp;
std::vector<std::pair<dgl_id_t, dgl_id_t> > sub_vers;
sub_vers.reserve(num_seeds * 10);
// add seed vertices
for (size_t i = 0; i < num_seeds; ++i) {
auto ret = sub_ver_mp.insert(seed[i]);
// If the vertex is inserted successfully.
if (ret.second) {
sub_vers.emplace_back(seed[i], 0);
}
}
std::vector<dgl_id_t> tmp_sampled_src_list;
std::vector<dgl_id_t> tmp_sampled_edge_list;
// ver_id, position
std::vector<std::pair<dgl_id_t, size_t> > neigh_pos;
neigh_pos.reserve(num_seeds);
std::vector<dgl_id_t> neighbor_list;
size_t num_edges = 0;
// sub_vers is used both as a node collection and a queue.
// In the while loop, we iterate over sub_vers and new nodes are added to the vector.
// A vertex in the vector only needs to be accessed once. If there is a vertex behind idx
// isn't in the last level, we will sample its neighbors. If not, the while loop terminates.
size_t idx = 0;
while (idx < sub_vers.size() &&
sub_ver_mp.size() < max_num_vertices) {
dgl_id_t dst_id = sub_vers[idx].first;
int cur_node_level = sub_vers[idx].second;
idx++;
// If the node is in the last level, we don't need to sample neighbors
// from this node.
if (cur_node_level >= num_hops)
continue;
tmp_sampled_src_list.clear();
tmp_sampled_edge_list.clear();
dgl_id_t ver_len = *(indptr+dst_id+1) - *(indptr+dst_id);
if (probability == nullptr) { // uniform-sample
GetUniformSample(val_list + *(indptr + dst_id),
col_list + *(indptr + dst_id),
ver_len,
num_neighbor,
&tmp_sampled_src_list,
&tmp_sampled_edge_list,
random_seed);
} else { // non-uniform-sample
GetNonUniformSample(probability,
val_list + *(indptr + dst_id),
col_list + *(indptr + dst_id),
ver_len,
num_neighbor,
&tmp_sampled_src_list,
&tmp_sampled_edge_list,
random_seed);
}
CHECK_EQ(tmp_sampled_src_list.size(), tmp_sampled_edge_list.size());
size_t pos = neighbor_list.size();
neigh_pos.emplace_back(dst_id, pos);
// First we push the size of neighbor vector
neighbor_list.push_back(tmp_sampled_edge_list.size());
// Then push the vertices
for (size_t i = 0; i < tmp_sampled_src_list.size(); ++i) {
neighbor_list.push_back(tmp_sampled_src_list[i]);
}
// Finally we push the edge list
for (size_t i = 0; i < tmp_sampled_edge_list.size(); ++i) {
neighbor_list.push_back(tmp_sampled_edge_list[i]);
}
num_edges += tmp_sampled_src_list.size();
for (size_t i = 0; i < tmp_sampled_src_list.size(); ++i) {
// If we have sampled the max number of vertices, we have to stop.
if (sub_ver_mp.size() >= max_num_vertices)
break;
// We need to add the neighbor in the hashtable here. This ensures that
// the vertex in the queue is unique. If we see a vertex before, we don't
// need to add it to the queue again.
auto ret = sub_ver_mp.insert(tmp_sampled_src_list[i]);
// If the sampled neighbor is inserted to the map successfully.
if (ret.second)
sub_vers.emplace_back(tmp_sampled_src_list[i], cur_node_level + 1);
}
}
// Let's check if there is a vertex that we haven't sampled its neighbors.
for (; idx < sub_vers.size(); idx++) {
if (sub_vers[idx].second < num_hops) {
LOG(WARNING)
<< "The sampling is truncated because we have reached the max number of vertices\n"
<< "Please use a smaller number of seeds or a small neighborhood";
break;
}
}
// Copy sub_ver_mp to output[0]
// Copy layer
size_t num_vertices = sub_ver_mp.size();
std::sort(sub_vers.begin(), sub_vers.end(),
[](const std::pair<dgl_id_t, dgl_id_t> &a1, const std::pair<dgl_id_t, dgl_id_t> &a2) {
return a1.first < a2.first;
});
for (size_t i = 0; i < sub_vers.size(); i++) {
out[i] = sub_vers[i].first;
out_layer[i] = sub_vers[i].second;
}
// The last element stores the actual
// number of vertices in the subgraph.
out[max_num_vertices] = sub_ver_mp.size();
// Copy sub_probability
if (sub_prob != nullptr) {
for (size_t i = 0; i < sub_ver_mp.size(); ++i) {
dgl_id_t idx = out[i];
sub_prob[i] = probability[idx];
}
}
// Construct sub_csr_graph
mxnet::TShape shape_1(1, -1);
mxnet::TShape shape_2(1, -1);
shape_1[0] = num_edges;
shape_2[0] = max_num_vertices+1;
sub_csr.CheckAndAllocData(shape_1);
sub_csr.CheckAndAllocAuxData(csr::kIdx, shape_1);
sub_csr.CheckAndAllocAuxData(csr::kIndPtr, shape_2);
dgl_id_t* val_list_out = sub_csr.data().dptr<dgl_id_t>();
dgl_id_t* col_list_out = sub_csr.aux_data(1).dptr<dgl_id_t>();
dgl_id_t* indptr_out = sub_csr.aux_data(0).dptr<dgl_id_t>();
indptr_out[0] = 0;
size_t collected_nedges = 0;
// Both the out array and neigh_pos are sorted. By scanning the two arrays, we can see
// which vertices have neighbors and which don't.
std::sort(neigh_pos.begin(), neigh_pos.end(),
[](const std::pair<dgl_id_t, size_t> &a1, const std::pair<dgl_id_t, size_t> &a2) {
return a1.first < a2.first;
});
size_t idx_with_neigh = 0;
for (size_t i = 0; i < num_vertices; i++) {
dgl_id_t dst_id = *(out + i);
// If a vertex is in sub_ver_mp but not in neigh_pos, this vertex must not
// have edges.
size_t edge_size = 0;
if (idx_with_neigh < neigh_pos.size() && dst_id == neigh_pos[idx_with_neigh].first) {
size_t pos = neigh_pos[idx_with_neigh].second;
CHECK_LT(pos, neighbor_list.size());
edge_size = neighbor_list[pos];
CHECK_LE(pos + edge_size * 2 + 1, neighbor_list.size());
std::copy_n(neighbor_list.begin() + pos + 1,
edge_size,
col_list_out + collected_nedges);
std::copy_n(neighbor_list.begin() + pos + edge_size + 1,
edge_size,
val_list_out + collected_nedges);
collected_nedges += edge_size;
idx_with_neigh++;
}
indptr_out[i+1] = indptr_out[i] + edge_size;
}
for (size_t i = num_vertices+1; i <= max_num_vertices; ++i) {
indptr_out[i] = indptr_out[i-1];
}
}
/*
* Operator: contrib_csr_neighbor_uniform_sample
*/
static void CSRNeighborUniformSampleComputeExCPU(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<NDArray>& inputs,
const std::vector<OpReqType>& req,
const std::vector<NDArray>& outputs) {
const NeighborSampleParam& params = nnvm::get<NeighborSampleParam>(attrs.parsed);
int num_subgraphs = inputs.size() - 1;
CHECK_EQ(outputs.size(), 3 * num_subgraphs);
mshadow::Stream<cpu> *s = ctx.get_stream<cpu>();
mshadow::Random<cpu, unsigned int> *prnd = ctx.requested[0].get_random<cpu, unsigned int>(s);
unsigned int seed = prnd->GetRandInt();
#pragma omp parallel for
for (int i = 0; i < num_subgraphs; i++) {
SampleSubgraph(inputs[0], // graph_csr
inputs[i + 1], // seed vector
outputs[i], // sample_id
outputs[i + 1*num_subgraphs], // sub_csr
nullptr, // sample_id_probability
outputs[i + 2*num_subgraphs], // sample_id_layer
nullptr, // probability
params.num_hops,
params.num_neighbor,
params.max_num_vertices,
#if defined(_OPENMP)
seed + omp_get_thread_num());
#else
seed);
#endif
}
}
NNVM_REGISTER_OP(_contrib_dgl_csr_neighbor_uniform_sample)
.describe(R"code(This operator samples sub-graphs from a csr graph via an
uniform probability. The operator is designed for DGL.
The operator outputs three sets of NDArrays to represent the sampled results
(the number of NDArrays in each set is the same as the number of seed NDArrays):
1) a set of 1D NDArrays containing the sampled vertices, 2) a set of CSRNDArrays representing
the sampled edges, 3) a set of 1D NDArrays indicating the layer where a vertex is sampled.
The first set of 1D NDArrays have a length of max_num_vertices+1. The last element in an NDArray
indicate the acutal number of vertices in a subgraph. The third set of NDArrays have a length
of max_num_vertices, and the valid number of vertices is the same as the ones in the first set.
Example:
.. code:: python
shape = (5, 5)
data_np = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20], dtype=np.int64)
indices_np = np.array([1,2,3,4,0,2,3,4,0,1,3,4,0,1,2,4,0,1,2,3], dtype=np.int64)
indptr_np = np.array([0,4,8,12,16,20], dtype=np.int64)
a = mx.nd.sparse.csr_matrix((data_np, indices_np, indptr_np), shape=shape)
a.asnumpy()
seed = mx.nd.array([0,1,2,3,4], dtype=np.int64)
out = mx.nd.contrib.dgl_csr_neighbor_uniform_sample(a, seed, num_args=2, num_hops=1, num_neighbor=2, max_num_vertices=5)
out[0]
[0 1 2 3 4 5]
<NDArray 6 @cpu(0)>
out[1].asnumpy()
array([[ 0, 1, 0, 3, 0],
[ 5, 0, 0, 7, 0],
[ 9, 0, 0, 11, 0],
[13, 0, 15, 0, 0],
[17, 0, 19, 0, 0]])
out[2]
[0 0 0 0 0]
<NDArray 5 @cpu(0)>
)code" ADD_FILELINE)
.set_attr_parser(ParamParser<NeighborSampleParam>)
.set_num_inputs([](const NodeAttrs& attrs) {
const NeighborSampleParam& params =
nnvm::get<NeighborSampleParam>(attrs.parsed);
return params.num_args;
})
.set_num_outputs([](const NodeAttrs& attrs) {
const NeighborSampleParam& params =
nnvm::get<NeighborSampleParam>(attrs.parsed);
size_t num_subgraphs = params.num_args - 1;
return num_subgraphs * 3;
})
.set_attr<FInferStorageType>("FInferStorageType", CSRNeighborUniformSampleStorageType)
.set_attr<mxnet::FInferShape>("FInferShape", CSRNeighborUniformSampleShape)
.set_attr<nnvm::FInferType>("FInferType", CSRNeighborUniformSampleType)
.set_attr<FComputeEx>("FComputeEx<cpu>", CSRNeighborUniformSampleComputeExCPU)
.set_attr<FResourceRequest>("FResourceRequest", [](const NodeAttrs& attrs) {
return std::vector<ResourceRequest>{ResourceRequest::kRandom};
})
.add_argument("csr_matrix", "NDArray-or-Symbol", "csr matrix")
.add_argument("seed_arrays", "NDArray-or-Symbol[]", "seed vertices")
.set_attr<std::string>("key_var_num_args", "num_args")
.add_arguments(NeighborSampleParam::__FIELDS__());
/*
* Operator: contrib_csr_neighbor_non_uniform_sample
*/
static void CSRNeighborNonUniformSampleComputeExCPU(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<NDArray>& inputs,
const std::vector<OpReqType>& req,
const std::vector<NDArray>& outputs) {
const NeighborSampleParam& params = nnvm::get<NeighborSampleParam>(attrs.parsed);
int num_subgraphs = inputs.size() - 2;
CHECK_EQ(outputs.size(), 4 * num_subgraphs);
const float* probability = inputs[1].data().dptr<float>();
mshadow::Stream<cpu> *s = ctx.get_stream<cpu>();
mshadow::Random<cpu, unsigned int> *prnd = ctx.requested[0].get_random<cpu, unsigned int>(s);
unsigned int seed = prnd->GetRandInt();
#pragma omp parallel for
for (int i = 0; i < num_subgraphs; i++) {
float* sub_prob = outputs[i+2*num_subgraphs].data().dptr<float>();
SampleSubgraph(inputs[0], // graph_csr
inputs[i + 2], // seed vector
outputs[i], // sample_id
outputs[i + 1*num_subgraphs], // sub_csr
sub_prob, // sample_id_probability
outputs[i + 3*num_subgraphs], // sample_id_layer
probability,
params.num_hops,
params.num_neighbor,
params.max_num_vertices,
#if defined(_OPENMP)
seed + omp_get_thread_num());
#else
seed);
#endif
}
}
NNVM_REGISTER_OP(_contrib_dgl_csr_neighbor_non_uniform_sample)
.describe(R"code(This operator samples sub-graph from a csr graph via an
non-uniform probability. The operator is designed for DGL.
The operator outputs four sets of NDArrays to represent the sampled results
(the number of NDArrays in each set is the same as the number of seed NDArrays):
1) a set of 1D NDArrays containing the sampled vertices, 2) a set of CSRNDArrays representing
the sampled edges, 3) a set of 1D NDArrays with the probability that vertices are sampled,
4) a set of 1D NDArrays indicating the layer where a vertex is sampled.
The first set of 1D NDArrays have a length of max_num_vertices+1. The last element in an NDArray
indicate the acutal number of vertices in a subgraph. The third and fourth set of NDArrays have a length
of max_num_vertices, and the valid number of vertices is the same as the ones in the first set.
Example:
.. code:: python
shape = (5, 5)
prob = mx.nd.array([0.9, 0.8, 0.2, 0.4, 0.1], dtype=np.float32)
data_np = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20], dtype=np.int64)
indices_np = np.array([1,2,3,4,0,2,3,4,0,1,3,4,0,1,2,4,0,1,2,3], dtype=np.int64)
indptr_np = np.array([0,4,8,12,16,20], dtype=np.int64)
a = mx.nd.sparse.csr_matrix((data_np, indices_np, indptr_np), shape=shape)
seed = mx.nd.array([0,1,2,3,4], dtype=np.int64)
out = mx.nd.contrib.dgl_csr_neighbor_non_uniform_sample(a, prob, seed, num_args=3, num_hops=1, num_neighbor=2, max_num_vertices=5)
out[0]
[0 1 2 3 4 5]
<NDArray 6 @cpu(0)>
out[1].asnumpy()
array([[ 0, 1, 2, 0, 0],
[ 5, 0, 6, 0, 0],
[ 9, 10, 0, 0, 0],
[13, 14, 0, 0, 0],
[ 0, 18, 19, 0, 0]])
out[2]
[0.9 0.8 0.2 0.4 0.1]
<NDArray 5 @cpu(0)>
out[3]
[0 0 0 0 0]
<NDArray 5 @cpu(0)>
)code" ADD_FILELINE)
.set_attr_parser(ParamParser<NeighborSampleParam>)
.set_num_inputs([](const NodeAttrs& attrs) {
const NeighborSampleParam& params =
nnvm::get<NeighborSampleParam>(attrs.parsed);
return params.num_args;
})
.set_num_outputs([](const NodeAttrs& attrs) {
const NeighborSampleParam& params =
nnvm::get<NeighborSampleParam>(attrs.parsed);
size_t num_subgraphs = params.num_args - 2;
return num_subgraphs * 4;
})
.set_attr<FInferStorageType>("FInferStorageType", CSRNeighborNonUniformSampleStorageType)
.set_attr<mxnet::FInferShape>("FInferShape", CSRNeighborNonUniformSampleShape)
.set_attr<nnvm::FInferType>("FInferType", CSRNeighborNonUniformSampleType)
.set_attr<FComputeEx>("FComputeEx<cpu>", CSRNeighborNonUniformSampleComputeExCPU)
.set_attr<FResourceRequest>("FResourceRequest", [](const NodeAttrs& attrs) {
return std::vector<ResourceRequest>{ResourceRequest::kRandom};
})
.add_argument("csr_matrix", "NDArray-or-Symbol", "csr matrix")
.add_argument("probability", "NDArray-or-Symbol", "probability vector")
.add_argument("seed_arrays", "NDArray-or-Symbol[]", "seed vertices")
.set_attr<std::string>("key_var_num_args", "num_args")
.add_arguments(NeighborSampleParam::__FIELDS__());
///////////////////////// Create induced subgraph ///////////////////////////
struct DGLSubgraphParam : public dmlc::Parameter<DGLSubgraphParam> {
int num_args;
bool return_mapping;
DMLC_DECLARE_PARAMETER(DGLSubgraphParam) {
DMLC_DECLARE_FIELD(num_args).set_lower_bound(2)
.describe("Number of input arguments, including all symbol inputs.");
DMLC_DECLARE_FIELD(return_mapping)
.describe("Return mapping of vid and eid between the subgraph and the parent graph.");
}
}; // struct DGLSubgraphParam
DMLC_REGISTER_PARAMETER(DGLSubgraphParam);
static bool DGLSubgraphStorageType(const nnvm::NodeAttrs& attrs,
const int dev_mask,
DispatchMode* dispatch_mode,
std::vector<int> *in_attrs,
std::vector<int> *out_attrs) {
CHECK_EQ(in_attrs->at(0), kCSRStorage);
for (size_t i = 1; i < in_attrs->size(); i++)
CHECK_EQ(in_attrs->at(i), kDefaultStorage);
bool success = true;
*dispatch_mode = DispatchMode::kFComputeEx;
for (size_t i = 0; i < out_attrs->size(); i++) {
if (!type_assign(&(*out_attrs)[i], mxnet::kCSRStorage))
success = false;
}
return success;
}
static bool DGLSubgraphShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
const DGLSubgraphParam& params = nnvm::get<DGLSubgraphParam>(attrs.parsed);
CHECK_EQ(in_attrs->at(0).ndim(), 2U);
for (size_t i = 1; i < in_attrs->size(); i++)
CHECK_EQ(in_attrs->at(i).ndim(), 1U);
size_t num_g = params.num_args - 1;
for (size_t i = 0; i < num_g; i++) {
mxnet::TShape gshape(2, -1);
gshape[0] = in_attrs->at(i + 1)[0];
gshape[1] = in_attrs->at(i + 1)[0];
out_attrs->at(i) = gshape;
}
for (size_t i = num_g; i < out_attrs->size(); i++) {
mxnet::TShape gshape(2, -1);
gshape[0] = in_attrs->at(i - num_g + 1)[0];
gshape[1] = in_attrs->at(i - num_g + 1)[0];
out_attrs->at(i) = gshape;
}
return true;
}
static bool DGLSubgraphType(const nnvm::NodeAttrs& attrs,
std::vector<int> *in_attrs,
std::vector<int> *out_attrs) {
const DGLSubgraphParam& params = nnvm::get<DGLSubgraphParam>(attrs.parsed);
size_t num_g = params.num_args - 1;
for (size_t i = 0; i < num_g; i++) {
CHECK_EQ(in_attrs->at(i + 1), mshadow::kInt64);