test_subgraph_sampler.py 17.8 KB
Newer Older
1
2
from functools import partial

3
import dgl
4
import dgl.graphbolt as gb
5
6
import pytest
import torch
7
from torchdata.datapipes.iter import Mapper
8

9
10
from . import gb_test_utils

11

12
13
def test_SubgraphSampler_invoke():
    itemset = gb.ItemSet(torch.arange(10), names="seed_nodes")
14
    item_sampler = gb.ItemSampler(itemset, batch_size=2)
15
16

    # Invoke via class constructor.
17
    datapipe = gb.SubgraphSampler(item_sampler)
18
19
20
21
    with pytest.raises(NotImplementedError):
        next(iter(datapipe))

    # Invokde via functional form.
22
    datapipe = item_sampler.sample_subgraph()
23
24
25
26
27
28
    with pytest.raises(NotImplementedError):
        next(iter(datapipe))


@pytest.mark.parametrize("labor", [False, True])
def test_NeighborSampler_invoke(labor):
29
    graph = gb_test_utils.rand_csc_graph(20, 0.15, bidirection_edge=True)
30
    itemset = gb.ItemSet(torch.arange(10), names="seed_nodes")
31
    item_sampler = gb.ItemSampler(itemset, batch_size=2)
32
33
34
35
36
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]

    # Invoke via class constructor.
    Sampler = gb.LayerNeighborSampler if labor else gb.NeighborSampler
37
    datapipe = Sampler(item_sampler, graph, fanouts)
38
39
40
41
    assert len(list(datapipe)) == 5

    # Invokde via functional form.
    if labor:
42
        datapipe = item_sampler.sample_layer_neighbor(graph, fanouts)
43
    else:
44
        datapipe = item_sampler.sample_neighbor(graph, fanouts)
45
46
47
    assert len(list(datapipe)) == 5


48
49
@pytest.mark.parametrize("labor", [False, True])
def test_NeighborSampler_fanouts(labor):
50
    graph = gb_test_utils.rand_csc_graph(20, 0.15, bidirection_edge=True)
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
    itemset = gb.ItemSet(torch.arange(10), names="seed_nodes")
    item_sampler = gb.ItemSampler(itemset, batch_size=2)
    num_layer = 2

    # `fanouts` is a list of tensors.
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
    if labor:
        datapipe = item_sampler.sample_layer_neighbor(graph, fanouts)
    else:
        datapipe = item_sampler.sample_neighbor(graph, fanouts)
    assert len(list(datapipe)) == 5

    # `fanouts` is a list of integers.
    fanouts = [2 for _ in range(num_layer)]
    if labor:
        datapipe = item_sampler.sample_layer_neighbor(graph, fanouts)
    else:
        datapipe = item_sampler.sample_neighbor(graph, fanouts)
    assert len(list(datapipe)) == 5


72
73
@pytest.mark.parametrize("labor", [False, True])
def test_SubgraphSampler_Node(labor):
74
    graph = gb_test_utils.rand_csc_graph(20, 0.15, bidirection_edge=True)
75
76
    itemset = gb.ItemSet(torch.arange(10), names="seed_nodes")
    item_sampler = gb.ItemSampler(itemset, batch_size=2)
77
78
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
79
    Sampler = gb.LayerNeighborSampler if labor else gb.NeighborSampler
80
    sampler_dp = Sampler(item_sampler, graph, fanouts)
81
    assert len(list(sampler_dp)) == 5
82
83


84
def to_link_batch(data):
85
    block = gb.MiniBatch(node_pairs=data)
86
    return block
87
88


89
90
@pytest.mark.parametrize("labor", [False, True])
def test_SubgraphSampler_Link(labor):
91
    graph = gb_test_utils.rand_csc_graph(20, 0.15, bidirection_edge=True)
92
    itemset = gb.ItemSet(torch.arange(0, 20).reshape(-1, 2), names="node_pairs")
93
    datapipe = gb.ItemSampler(itemset, batch_size=2)
94
95
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
96
    Sampler = gb.LayerNeighborSampler if labor else gb.NeighborSampler
97
98
99
    datapipe = Sampler(datapipe, graph, fanouts)
    datapipe = datapipe.transform(partial(gb.exclude_seed_edges))
    assert len(list(datapipe)) == 5
100
101


102
@pytest.mark.parametrize("labor", [False, True])
103
def test_SubgraphSampler_Link_With_Negative(labor):
104
    graph = gb_test_utils.rand_csc_graph(20, 0.15, bidirection_edge=True)
105
    itemset = gb.ItemSet(torch.arange(0, 20).reshape(-1, 2), names="node_pairs")
106
    datapipe = gb.ItemSampler(itemset, batch_size=2)
107
108
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
109
    datapipe = gb.UniformNegativeSampler(datapipe, graph, 1)
110
    Sampler = gb.LayerNeighborSampler if labor else gb.NeighborSampler
111
112
113
    datapipe = Sampler(datapipe, graph, fanouts)
    datapipe = datapipe.transform(partial(gb.exclude_seed_edges))
    assert len(list(datapipe)) == 5
114
115


116
117
118
119
120
121
122
def get_hetero_graph():
    # COO graph:
    # [0, 0, 1, 1, 2, 2, 3, 3, 4, 4]
    # [2, 4, 2, 3, 0, 1, 1, 0, 0, 1]
    # [1, 1, 1, 1, 0, 0, 0, 0, 0] - > edge type.
    # num_nodes = 5, num_n1 = 2, num_n2 = 3
    ntypes = {"n1": 0, "n2": 1}
123
    etypes = {"n1:e1:n2": 0, "n2:e2:n1": 1}
124
125
126
127
    indptr = torch.LongTensor([0, 2, 4, 6, 8, 10])
    indices = torch.LongTensor([2, 4, 2, 3, 0, 1, 1, 0, 0, 1])
    type_per_edge = torch.LongTensor([1, 1, 1, 1, 0, 0, 0, 0, 0, 0])
    node_type_offset = torch.LongTensor([0, 2, 5])
128
    return gb.fused_csc_sampling_graph(
129
130
131
132
        indptr,
        indices,
        node_type_offset=node_type_offset,
        type_per_edge=type_per_edge,
133
134
        node_type_to_id=ntypes,
        edge_type_to_id=etypes,
135
    )
136
137


138
139
140
141
142
143
144
145
146
147
148
149
150
@pytest.mark.parametrize("labor", [False, True])
def test_SubgraphSampler_Node_Hetero(labor):
    graph = get_hetero_graph()
    itemset = gb.ItemSetDict(
        {"n2": gb.ItemSet(torch.arange(3), names="seed_nodes")}
    )
    item_sampler = gb.ItemSampler(itemset, batch_size=2)
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
    Sampler = gb.LayerNeighborSampler if labor else gb.NeighborSampler
    sampler_dp = Sampler(item_sampler, graph, fanouts)
    assert len(list(sampler_dp)) == 2
    for minibatch in sampler_dp:
peizhou001's avatar
peizhou001 committed
151
        assert len(minibatch.sampled_subgraphs) == num_layer
152
153


154
155
@pytest.mark.parametrize("labor", [False, True])
def test_SubgraphSampler_Link_Hetero(labor):
156
157
158
    graph = get_hetero_graph()
    itemset = gb.ItemSetDict(
        {
159
            "n1:e1:n2": gb.ItemSet(
160
161
                torch.LongTensor([[0, 0, 1, 1], [0, 2, 0, 1]]).T,
                names="node_pairs",
162
            ),
163
            "n2:e2:n1": gb.ItemSet(
164
165
                torch.LongTensor([[0, 0, 1, 1, 2, 2], [0, 1, 1, 0, 0, 1]]).T,
                names="node_pairs",
166
167
168
            ),
        }
    )
169

170
    datapipe = gb.ItemSampler(itemset, batch_size=2)
171
172
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
173
    Sampler = gb.LayerNeighborSampler if labor else gb.NeighborSampler
174
175
176
    datapipe = Sampler(datapipe, graph, fanouts)
    datapipe = datapipe.transform(partial(gb.exclude_seed_edges))
    assert len(list(datapipe)) == 5
177
178


179
@pytest.mark.parametrize("labor", [False, True])
180
def test_SubgraphSampler_Link_Hetero_With_Negative(labor):
181
182
183
    graph = get_hetero_graph()
    itemset = gb.ItemSetDict(
        {
184
            "n1:e1:n2": gb.ItemSet(
185
186
                torch.LongTensor([[0, 0, 1, 1], [0, 2, 0, 1]]).T,
                names="node_pairs",
187
            ),
188
            "n2:e2:n1": gb.ItemSet(
189
190
                torch.LongTensor([[0, 0, 1, 1, 2, 2], [0, 1, 1, 0, 0, 1]]).T,
                names="node_pairs",
191
192
193
194
            ),
        }
    )

195
    datapipe = gb.ItemSampler(itemset, batch_size=2)
196
197
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
198
    datapipe = gb.UniformNegativeSampler(datapipe, graph, 1)
199
    Sampler = gb.LayerNeighborSampler if labor else gb.NeighborSampler
200
201
202
    datapipe = Sampler(datapipe, graph, fanouts)
    datapipe = datapipe.transform(partial(gb.exclude_seed_edges))
    assert len(list(datapipe)) == 5
203
204
205
206
207
208
209
210
211
212
213
214
215


@pytest.mark.parametrize("labor", [False, True])
def test_SubgraphSampler_Random_Hetero_Graph(labor):
    num_nodes = 5
    num_edges = 9
    num_ntypes = 3
    num_etypes = 3
    (
        csc_indptr,
        indices,
        node_type_offset,
        type_per_edge,
216
217
        node_type_to_id,
        edge_type_to_id,
218
219
220
221
222
223
224
    ) = gb_test_utils.random_hetero_graph(
        num_nodes, num_edges, num_ntypes, num_etypes
    )
    edge_attributes = {
        "A1": torch.randn(num_edges),
        "A2": torch.randn(num_edges),
    }
225
    graph = gb.fused_csc_sampling_graph(
226
227
        csc_indptr,
        indices,
228
229
230
231
232
        node_type_offset=node_type_offset,
        type_per_edge=type_per_edge,
        node_type_to_id=node_type_to_id,
        edge_type_to_id=edge_type_to_id,
        edge_attributes=edge_attributes,
233
234
235
236
    )
    itemset = gb.ItemSetDict(
        {
            "n2": gb.ItemSet(torch.tensor([0]), names="seed_nodes"),
237
            "n1": gb.ItemSet(torch.tensor([0]), names="seed_nodes"),
238
239
240
241
242
243
244
245
246
247
248
        }
    )

    item_sampler = gb.ItemSampler(itemset, batch_size=2)
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
    Sampler = gb.LayerNeighborSampler if labor else gb.NeighborSampler
    sampler_dp = Sampler(item_sampler, graph, fanouts, replace=True)

    for data in sampler_dp:
        for sampledsubgraph in data.sampled_subgraphs:
249
            for _, value in sampledsubgraph.sampled_csc.items():
250
                assert torch.equal(
251
252
                    torch.ge(value.indices, torch.zeros(len(value.indices))),
                    torch.ones(len(value.indices)),
253
254
                )
                assert torch.equal(
255
256
                    torch.ge(value.indptr, torch.zeros(len(value.indptr))),
                    torch.ones(len(value.indptr)),
257
258
259
260
261
262
263
264
265
266
267
                )
            for _, value in sampledsubgraph.original_column_node_ids.items():
                assert torch.equal(
                    torch.ge(value, torch.zeros(len(value))),
                    torch.ones(len(value)),
                )
            for _, value in sampledsubgraph.original_row_node_ids.items():
                assert torch.equal(
                    torch.ge(value, torch.zeros(len(value))),
                    torch.ones(len(value)),
                )
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


@pytest.mark.parametrize("labor", [False, True])
def test_SubgraphSampler_without_dedpulication_Homo(labor):
    graph = dgl.graph(
        ([5, 0, 1, 5, 6, 7, 2, 2, 4], [0, 1, 2, 2, 2, 2, 3, 4, 4])
    )
    graph = gb.from_dglgraph(graph, True)
    seed_nodes = torch.LongTensor([0, 3, 4])

    itemset = gb.ItemSet(seed_nodes, names="seed_nodes")
    item_sampler = gb.ItemSampler(itemset, batch_size=len(seed_nodes))
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]

    Sampler = gb.LayerNeighborSampler if labor else gb.NeighborSampler
    datapipe = Sampler(item_sampler, graph, fanouts, deduplicate=False)

    length = [17, 7]
    compacted_indices = [
        torch.arange(0, 10) + 7,
        torch.arange(0, 4) + 3,
    ]
    indptr = [
        torch.tensor([0, 1, 2, 4, 4, 6, 8, 10]),
        torch.tensor([0, 1, 2, 4]),
    ]
    seeds = [torch.tensor([0, 3, 4, 5, 2, 2, 4]), torch.tensor([0, 3, 4])]
    for data in datapipe:
        for step, sampled_subgraph in enumerate(data.sampled_subgraphs):
            assert len(sampled_subgraph.original_row_node_ids) == length[step]
            assert torch.equal(
300
301
302
303
                sampled_subgraph.sampled_csc.indices, compacted_indices[step]
            )
            assert torch.equal(
                sampled_subgraph.sampled_csc.indptr, indptr[step]
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
            )
            assert torch.equal(
                sampled_subgraph.original_column_node_ids, seeds[step]
            )


@pytest.mark.parametrize("labor", [False, True])
def test_SubgraphSampler_without_dedpulication_Hetero(labor):
    graph = get_hetero_graph()
    itemset = gb.ItemSetDict(
        {"n2": gb.ItemSet(torch.arange(2), names="seed_nodes")}
    )
    item_sampler = gb.ItemSampler(itemset, batch_size=2)
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
    Sampler = gb.LayerNeighborSampler if labor else gb.NeighborSampler
    datapipe = Sampler(item_sampler, graph, fanouts, deduplicate=False)
    csc_formats = [
        {
            "n1:e1:n2": gb.CSCFormatBase(
                indptr=torch.tensor([0, 2, 4]),
                indices=torch.tensor([4, 5, 6, 7]),
            ),
            "n2:e2:n1": gb.CSCFormatBase(
                indptr=torch.tensor([0, 2, 4, 6, 8]),
                indices=torch.tensor([2, 3, 4, 5, 6, 7, 8, 9]),
            ),
        },
        {
            "n1:e1:n2": gb.CSCFormatBase(
                indptr=torch.tensor([0, 2, 4]),
                indices=torch.tensor([0, 1, 2, 3]),
            ),
            "n2:e2:n1": gb.CSCFormatBase(
                indptr=torch.tensor([0]),
                indices=torch.tensor([], dtype=torch.int64),
            ),
        },
    ]
    original_column_node_ids = [
        {
            "n1": torch.tensor([0, 1, 1, 0]),
            "n2": torch.tensor([0, 1]),
        },
        {
            "n1": torch.tensor([], dtype=torch.int64),
            "n2": torch.tensor([0, 1]),
        },
    ]
    original_row_node_ids = [
        {
            "n1": torch.tensor([0, 1, 1, 0, 0, 1, 1, 0]),
            "n2": torch.tensor([0, 1, 0, 2, 0, 1, 0, 1, 0, 2]),
        },
        {
            "n1": torch.tensor([0, 1, 1, 0]),
            "n2": torch.tensor([0, 1]),
        },
    ]

    for data in datapipe:
        for step, sampled_subgraph in enumerate(data.sampled_subgraphs):
            for ntype in ["n1", "n2"]:
                assert torch.equal(
                    sampled_subgraph.original_row_node_ids[ntype],
                    original_row_node_ids[step][ntype],
                )
                assert torch.equal(
                    sampled_subgraph.original_column_node_ids[ntype],
                    original_column_node_ids[step][ntype],
                )
            for etype in ["n1:e1:n2", "n2:e2:n1"]:
                assert torch.equal(
377
                    sampled_subgraph.sampled_csc[etype].indices,
378
379
380
                    csc_formats[step][etype].indices,
                )
                assert torch.equal(
381
                    sampled_subgraph.sampled_csc[etype].indptr,
382
383
                    csc_formats[step][etype].indptr,
                )
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


@pytest.mark.parametrize("labor", [False, True])
def test_SubgraphSampler_unique_csc_format_Homo(labor):
    torch.manual_seed(1205)
    graph = dgl.graph(([5, 0, 6, 7, 2, 2, 4], [0, 1, 2, 2, 3, 4, 4]))
    graph = gb.from_dglgraph(graph, True)
    seed_nodes = torch.LongTensor([0, 3, 4])

    itemset = gb.ItemSet(seed_nodes, names="seed_nodes")
    item_sampler = gb.ItemSampler(itemset, batch_size=len(seed_nodes))
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]

    Sampler = gb.LayerNeighborSampler if labor else gb.NeighborSampler
    datapipe = Sampler(
        item_sampler,
        graph,
        fanouts,
        replace=False,
        deduplicate=True,
        output_cscformat=True,
    )

    original_row_node_ids = [
        torch.tensor([0, 3, 4, 5, 2, 6, 7]),
        torch.tensor([0, 3, 4, 5, 2]),
    ]
    compacted_indices = [
        torch.tensor([3, 4, 4, 2, 5, 6]),
        torch.tensor([3, 4, 4, 2]),
    ]
    indptr = [
        torch.tensor([0, 1, 2, 4, 4, 6]),
        torch.tensor([0, 1, 2, 4]),
    ]
    seeds = [torch.tensor([0, 3, 4, 5, 2]), torch.tensor([0, 3, 4])]
    for data in datapipe:
        for step, sampled_subgraph in enumerate(data.sampled_subgraphs):
            assert torch.equal(
                sampled_subgraph.original_row_node_ids,
                original_row_node_ids[step],
            )
            assert torch.equal(
428
429
430
431
                sampled_subgraph.sampled_csc.indices, compacted_indices[step]
            )
            assert torch.equal(
                sampled_subgraph.sampled_csc.indptr, indptr[step]
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
            )
            assert torch.equal(
                sampled_subgraph.original_column_node_ids, seeds[step]
            )


@pytest.mark.parametrize("labor", [False, True])
def test_SubgraphSampler_unique_csc_format_Hetero(labor):
    graph = get_hetero_graph()
    itemset = gb.ItemSetDict(
        {"n2": gb.ItemSet(torch.arange(2), names="seed_nodes")}
    )
    item_sampler = gb.ItemSampler(itemset, batch_size=2)
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
    Sampler = gb.LayerNeighborSampler if labor else gb.NeighborSampler
    datapipe = Sampler(
        item_sampler,
        graph,
        fanouts,
        deduplicate=True,
        output_cscformat=True,
    )
    csc_formats = [
        {
            "n1:e1:n2": gb.CSCFormatBase(
                indptr=torch.tensor([0, 2, 4]),
                indices=torch.tensor([0, 1, 1, 0]),
            ),
            "n2:e2:n1": gb.CSCFormatBase(
                indptr=torch.tensor([0, 2, 4]),
                indices=torch.tensor([0, 2, 0, 1]),
            ),
        },
        {
            "n1:e1:n2": gb.CSCFormatBase(
                indptr=torch.tensor([0, 2, 4]),
                indices=torch.tensor([0, 1, 1, 0]),
            ),
            "n2:e2:n1": gb.CSCFormatBase(
                indptr=torch.tensor([0]),
                indices=torch.tensor([], dtype=torch.int64),
            ),
        },
    ]
    original_column_node_ids = [
        {
            "n1": torch.tensor([0, 1]),
            "n2": torch.tensor([0, 1]),
        },
        {
            "n1": torch.tensor([], dtype=torch.int64),
            "n2": torch.tensor([0, 1]),
        },
    ]
    original_row_node_ids = [
        {
            "n1": torch.tensor([0, 1]),
            "n2": torch.tensor([0, 1, 2]),
        },
        {
            "n1": torch.tensor([0, 1]),
            "n2": torch.tensor([0, 1]),
        },
    ]

    for data in datapipe:
        for step, sampled_subgraph in enumerate(data.sampled_subgraphs):
            for ntype in ["n1", "n2"]:
                assert torch.equal(
                    sampled_subgraph.original_row_node_ids[ntype],
                    original_row_node_ids[step][ntype],
                )
                assert torch.equal(
                    sampled_subgraph.original_column_node_ids[ntype],
                    original_column_node_ids[step][ntype],
                )
            for etype in ["n1:e1:n2", "n2:e2:n1"]:
                assert torch.equal(
511
                    sampled_subgraph.sampled_csc[etype].indices,
512
513
514
                    csc_formats[step][etype].indices,
                )
                assert torch.equal(
515
                    sampled_subgraph.sampled_csc[etype].indptr,
516
517
                    csc_formats[step][etype].indptr,
                )