test_subgraph_sampler.py 27.5 KB
Newer Older
1
import unittest
2
3

from enum import Enum
4
5
from functools import partial

6
7
import backend as F

8
import dgl
9
import dgl.graphbolt as gb
10
11
import pytest
import torch
12
from torchdata.datapipes.iter import Mapper
13

14
15
from . import gb_test_utils

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
# Skip all tests on GPU.
pytestmark = pytest.mark.skipif(
    F._default_context_str != "cpu",
    reason="GraphBolt sampling tests are only supported on CPU.",
)


class SamplerType(Enum):
    Normal = 0
    Layer = 1
    Temporal = 2


def _get_sampler(sampler_type):
    if sampler_type == SamplerType.Normal:
        return gb.NeighborSampler
    if sampler_type == SamplerType.Layer:
        return gb.LayerNeighborSampler
    return partial(
        gb.TemporalNeighborSampler,
        node_timestamp_attr_name="timestamp",
        edge_timestamp_attr_name="timestamp",
    )


42
43
def test_SubgraphSampler_invoke():
    itemset = gb.ItemSet(torch.arange(10), names="seed_nodes")
44
    item_sampler = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
45
46

    # Invoke via class constructor.
47
    datapipe = gb.SubgraphSampler(item_sampler)
48
49
50
51
    with pytest.raises(NotImplementedError):
        next(iter(datapipe))

    # Invokde via functional form.
52
    datapipe = item_sampler.sample_subgraph()
53
54
55
56
57
58
    with pytest.raises(NotImplementedError):
        next(iter(datapipe))


@pytest.mark.parametrize("labor", [False, True])
def test_NeighborSampler_invoke(labor):
59
60
61
    graph = gb_test_utils.rand_csc_graph(20, 0.15, bidirection_edge=True).to(
        F.ctx()
    )
62
    itemset = gb.ItemSet(torch.arange(10), names="seed_nodes")
63
    item_sampler = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
64
65
66
67
68
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]

    # Invoke via class constructor.
    Sampler = gb.LayerNeighborSampler if labor else gb.NeighborSampler
69
    datapipe = Sampler(item_sampler, graph, fanouts)
70
71
72
73
    assert len(list(datapipe)) == 5

    # Invokde via functional form.
    if labor:
74
        datapipe = item_sampler.sample_layer_neighbor(graph, fanouts)
75
    else:
76
        datapipe = item_sampler.sample_neighbor(graph, fanouts)
77
78
79
    assert len(list(datapipe)) == 5


80
81
@pytest.mark.parametrize("labor", [False, True])
def test_NeighborSampler_fanouts(labor):
82
83
84
    graph = gb_test_utils.rand_csc_graph(20, 0.15, bidirection_edge=True).to(
        F.ctx()
    )
85
    itemset = gb.ItemSet(torch.arange(10), names="seed_nodes")
86
    item_sampler = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
    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


106
107
108
109
110
@pytest.mark.parametrize(
    "sampler_type",
    [SamplerType.Normal, SamplerType.Layer, SamplerType.Temporal],
)
def test_SubgraphSampler_Node(sampler_type):
111
112
113
    graph = gb_test_utils.rand_csc_graph(20, 0.15, bidirection_edge=True).to(
        F.ctx()
    )
114
115
116
117
118
119
120
121
122
123
    items = torch.arange(10)
    names = "seed_nodes"
    if sampler_type == SamplerType.Temporal:
        graph.node_attributes = {"timestamp": torch.arange(20).to(F.ctx())}
        graph.edge_attributes = {
            "timestamp": torch.arange(len(graph.indices)).to(F.ctx())
        }
        items = (items, torch.arange(10))
        names = ("seed_nodes", "timestamp")
    itemset = gb.ItemSet(items, names=names)
124
    item_sampler = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
125
126
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
127
128
    sampler = _get_sampler(sampler_type)
    sampler_dp = sampler(item_sampler, graph, fanouts)
129
    assert len(list(sampler_dp)) == 5
130
131


132
def to_link_batch(data):
133
    block = gb.MiniBatch(node_pairs=data)
134
    return block
135
136


137
138
139
140
141
@pytest.mark.parametrize(
    "sampler_type",
    [SamplerType.Normal, SamplerType.Layer, SamplerType.Temporal],
)
def test_SubgraphSampler_Link(sampler_type):
142
143
144
    graph = gb_test_utils.rand_csc_graph(20, 0.15, bidirection_edge=True).to(
        F.ctx()
    )
145
146
147
148
149
150
151
152
153
154
    items = torch.arange(20).reshape(-1, 2)
    names = "node_pairs"
    if sampler_type == SamplerType.Temporal:
        graph.node_attributes = {"timestamp": torch.arange(20).to(F.ctx())}
        graph.edge_attributes = {
            "timestamp": torch.arange(len(graph.indices)).to(F.ctx())
        }
        items = (items, torch.arange(10))
        names = ("node_pairs", "timestamp")
    itemset = gb.ItemSet(items, names=names)
155
    datapipe = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
156
157
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
158
159
    sampler = _get_sampler(sampler_type)
    datapipe = sampler(datapipe, graph, fanouts)
160
161
    datapipe = datapipe.transform(partial(gb.exclude_seed_edges))
    assert len(list(datapipe)) == 5
162
163


164
165
166
167
168
@pytest.mark.parametrize(
    "sampler_type",
    [SamplerType.Normal, SamplerType.Layer, SamplerType.Temporal],
)
def test_SubgraphSampler_Link_With_Negative(sampler_type):
169
170
171
    graph = gb_test_utils.rand_csc_graph(20, 0.15, bidirection_edge=True).to(
        F.ctx()
    )
172
173
174
175
176
177
178
179
180
181
    items = torch.arange(20).reshape(-1, 2)
    names = "node_pairs"
    if sampler_type == SamplerType.Temporal:
        graph.node_attributes = {"timestamp": torch.arange(20).to(F.ctx())}
        graph.edge_attributes = {
            "timestamp": torch.arange(len(graph.indices)).to(F.ctx())
        }
        items = (items, torch.arange(10))
        names = ("node_pairs", "timestamp")
    itemset = gb.ItemSet(items, names=names)
182
    datapipe = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
183
184
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
185
    datapipe = gb.UniformNegativeSampler(datapipe, graph, 1)
186
187
    sampler = _get_sampler(sampler_type)
    datapipe = sampler(datapipe, graph, fanouts)
188
189
    datapipe = datapipe.transform(partial(gb.exclude_seed_edges))
    assert len(list(datapipe)) == 5
190
191


192
193
194
195
196
197
198
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}
199
    etypes = {"n1:e1:n2": 0, "n2:e2:n1": 1}
200
201
202
203
    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])
204
    return gb.fused_csc_sampling_graph(
205
206
207
208
        indptr,
        indices,
        node_type_offset=node_type_offset,
        type_per_edge=type_per_edge,
209
210
        node_type_to_id=ntypes,
        edge_type_to_id=etypes,
211
    )
212
213


214
215
216
217
218
@pytest.mark.parametrize(
    "sampler_type",
    [SamplerType.Normal, SamplerType.Layer, SamplerType.Temporal],
)
def test_SubgraphSampler_Node_Hetero(sampler_type):
219
    graph = get_hetero_graph().to(F.ctx())
220
221
222
223
224
225
226
227
228
229
230
231
    items = torch.arange(3)
    names = "seed_nodes"
    if sampler_type == SamplerType.Temporal:
        graph.node_attributes = {
            "timestamp": torch.arange(graph.csc_indptr.numel() - 1).to(F.ctx())
        }
        graph.edge_attributes = {
            "timestamp": torch.arange(graph.indices.numel()).to(F.ctx())
        }
        items = (items, torch.randint(0, 10, (3,)))
        names = (names, "timestamp")
    itemset = gb.ItemSetDict({"n2": gb.ItemSet(items, names=names)})
232
    item_sampler = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
233
234
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
235
236
    sampler = _get_sampler(sampler_type)
    sampler_dp = sampler(item_sampler, graph, fanouts)
237
238
    assert len(list(sampler_dp)) == 2
    for minibatch in sampler_dp:
peizhou001's avatar
peizhou001 committed
239
        assert len(minibatch.sampled_subgraphs) == num_layer
240
241


242
243
244
245
246
@pytest.mark.parametrize(
    "sampler_type",
    [SamplerType.Normal, SamplerType.Layer, SamplerType.Temporal],
)
def test_SubgraphSampler_Link_Hetero(sampler_type):
247
    graph = get_hetero_graph().to(F.ctx())
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
    first_items = torch.LongTensor([[0, 0, 1, 1], [0, 2, 0, 1]]).T
    first_names = "node_pairs"
    second_items = torch.LongTensor([[0, 0, 1, 1, 2, 2], [0, 1, 1, 0, 0, 1]]).T
    second_names = "node_pairs"
    if sampler_type == SamplerType.Temporal:
        graph.node_attributes = {
            "timestamp": torch.arange(graph.csc_indptr.numel() - 1).to(F.ctx())
        }
        graph.edge_attributes = {
            "timestamp": torch.arange(graph.indices.numel()).to(F.ctx())
        }
        first_items = (first_items, torch.randint(0, 10, (4,)))
        first_names = (first_names, "timestamp")
        second_items = (second_items, torch.randint(0, 10, (6,)))
        second_names = (second_names, "timestamp")
263
264
    itemset = gb.ItemSetDict(
        {
265
            "n1:e1:n2": gb.ItemSet(
266
267
                first_items,
                names=first_names,
268
            ),
269
            "n2:e2:n1": gb.ItemSet(
270
271
                second_items,
                names=second_names,
272
273
274
            ),
        }
    )
275

276
    datapipe = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
277
278
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
279
280
    sampler = _get_sampler(sampler_type)
    datapipe = sampler(datapipe, graph, fanouts)
281
282
    datapipe = datapipe.transform(partial(gb.exclude_seed_edges))
    assert len(list(datapipe)) == 5
283
284


285
286
287
288
289
@pytest.mark.parametrize(
    "sampler_type",
    [SamplerType.Normal, SamplerType.Layer, SamplerType.Temporal],
)
def test_SubgraphSampler_Link_Hetero_With_Negative(sampler_type):
290
    graph = get_hetero_graph().to(F.ctx())
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
    first_items = torch.LongTensor([[0, 0, 1, 1], [0, 2, 0, 1]]).T
    first_names = "node_pairs"
    second_items = torch.LongTensor([[0, 0, 1, 1, 2, 2], [0, 1, 1, 0, 0, 1]]).T
    second_names = "node_pairs"
    if sampler_type == SamplerType.Temporal:
        graph.node_attributes = {
            "timestamp": torch.arange(graph.csc_indptr.numel() - 1).to(F.ctx())
        }
        graph.edge_attributes = {
            "timestamp": torch.arange(graph.indices.numel()).to(F.ctx())
        }
        first_items = (first_items, torch.randint(0, 10, (4,)))
        first_names = (first_names, "timestamp")
        second_items = (second_items, torch.randint(0, 10, (6,)))
        second_names = (second_names, "timestamp")
306
307
    itemset = gb.ItemSetDict(
        {
308
            "n1:e1:n2": gb.ItemSet(
309
310
                first_items,
                names=first_names,
311
            ),
312
            "n2:e2:n1": gb.ItemSet(
313
314
                second_items,
                names=second_names,
315
316
317
318
            ),
        }
    )

319
    datapipe = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
320
321
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
322
    datapipe = gb.UniformNegativeSampler(datapipe, graph, 1)
323
324
    sampler = _get_sampler(sampler_type)
    datapipe = sampler(datapipe, graph, fanouts)
325
326
    datapipe = datapipe.transform(partial(gb.exclude_seed_edges))
    assert len(list(datapipe)) == 5
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
@pytest.mark.parametrize(
    "sampler_type",
    [SamplerType.Normal, SamplerType.Layer, SamplerType.Temporal],
)
def test_SubgraphSampler_Link_Hetero_Unknown_Etype(sampler_type):
    graph = get_hetero_graph().to(F.ctx())
    first_items = torch.LongTensor([[0, 0, 1, 1], [0, 2, 0, 1]]).T
    first_names = "node_pairs"
    second_items = torch.LongTensor([[0, 0, 1, 1, 2, 2], [0, 1, 1, 0, 0, 1]]).T
    second_names = "node_pairs"
    if sampler_type == SamplerType.Temporal:
        graph.node_attributes = {
            "timestamp": torch.arange(graph.csc_indptr.numel() - 1).to(F.ctx())
        }
        graph.edge_attributes = {
            "timestamp": torch.arange(graph.indices.numel()).to(F.ctx())
        }
        first_items = (first_items, torch.randint(0, 10, (4,)))
        first_names = (first_names, "timestamp")
        second_items = (second_items, torch.randint(0, 10, (6,)))
        second_names = (second_names, "timestamp")
    # "e11" and "e22" are not valid edge types.
    itemset = gb.ItemSetDict(
        {
            "n1:e11:n2": gb.ItemSet(
                first_items,
                names=first_names,
            ),
            "n2:e22:n1": gb.ItemSet(
                second_items,
                names=second_names,
            ),
        }
    )

    datapipe = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
    sampler = _get_sampler(sampler_type)
    datapipe = sampler(datapipe, graph, fanouts)
    datapipe = datapipe.transform(partial(gb.exclude_seed_edges))
    assert len(list(datapipe)) == 5


@pytest.mark.parametrize(
    "sampler_type",
    [SamplerType.Normal, SamplerType.Layer, SamplerType.Temporal],
)
def test_SubgraphSampler_Link_Hetero_With_Negative_Unknown_Etype(sampler_type):
    graph = get_hetero_graph().to(F.ctx())
    first_items = torch.LongTensor([[0, 0, 1, 1], [0, 2, 0, 1]]).T
    first_names = "node_pairs"
    second_items = torch.LongTensor([[0, 0, 1, 1, 2, 2], [0, 1, 1, 0, 0, 1]]).T
    second_names = "node_pairs"
    if sampler_type == SamplerType.Temporal:
        graph.node_attributes = {
            "timestamp": torch.arange(graph.csc_indptr.numel() - 1).to(F.ctx())
        }
        graph.edge_attributes = {
            "timestamp": torch.arange(graph.indices.numel()).to(F.ctx())
        }
        first_items = (first_items, torch.randint(0, 10, (4,)))
        first_names = (first_names, "timestamp")
        second_items = (second_items, torch.randint(0, 10, (6,)))
        second_names = (second_names, "timestamp")
    # "e11" and "e22" are not valid edge types.
    itemset = gb.ItemSetDict(
        {
            "n1:e11:n2": gb.ItemSet(
                first_items,
                names=first_names,
            ),
            "n2:e22:n1": gb.ItemSet(
                second_items,
                names=second_names,
            ),
        }
    )

    datapipe = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
    datapipe = gb.UniformNegativeSampler(datapipe, graph, 1)
    sampler = _get_sampler(sampler_type)
    datapipe = sampler(datapipe, graph, fanouts)
    datapipe = datapipe.transform(partial(gb.exclude_seed_edges))
    assert len(list(datapipe)) == 5


418
419
420
421
@unittest.skipIf(
    F._default_context_str != "cpu",
    reason="Sampling with replacement not yet supported on GPU.",
)
422
423
424
425
426
@pytest.mark.parametrize(
    "sampler_type",
    [SamplerType.Normal, SamplerType.Layer, SamplerType.Temporal],
)
def test_SubgraphSampler_Random_Hetero_Graph(sampler_type):
427
428
429
430
431
432
433
434
435
    num_nodes = 5
    num_edges = 9
    num_ntypes = 3
    num_etypes = 3
    (
        csc_indptr,
        indices,
        node_type_offset,
        type_per_edge,
436
437
        node_type_to_id,
        edge_type_to_id,
438
439
440
    ) = gb_test_utils.random_hetero_graph(
        num_nodes, num_edges, num_ntypes, num_etypes
    )
441
    node_attributes = {}
442
443
444
445
    edge_attributes = {
        "A1": torch.randn(num_edges),
        "A2": torch.randn(num_edges),
    }
446
447
448
    if sampler_type == SamplerType.Temporal:
        node_attributes["timestamp"] = torch.randint(0, 10, (num_nodes,))
        edge_attributes["timestamp"] = torch.randint(0, 10, (num_edges,))
449
    graph = gb.fused_csc_sampling_graph(
450
451
        csc_indptr,
        indices,
452
453
454
455
        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,
456
        node_attributes=node_attributes,
457
        edge_attributes=edge_attributes,
458
    ).to(F.ctx())
459
460
461
462
463
464
465
466
467
    first_items = torch.tensor([0])
    first_names = "seed_nodes"
    second_items = torch.tensor([0])
    second_names = "seed_nodes"
    if sampler_type == SamplerType.Temporal:
        first_items = (first_items, torch.randint(0, 10, (1,)))
        first_names = (first_names, "timestamp")
        second_items = (second_items, torch.randint(0, 10, (1,)))
        second_names = (second_names, "timestamp")
468
469
    itemset = gb.ItemSetDict(
        {
470
471
            "n2": gb.ItemSet(first_items, names=first_names),
            "n1": gb.ItemSet(second_items, names=second_names),
472
473
474
        }
    )

475
    item_sampler = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
476
477
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
478
    sampler = _get_sampler(sampler_type)
479

480
    sampler_dp = sampler(item_sampler, graph, fanouts, replace=True)
481
482
483

    for data in sampler_dp:
        for sampledsubgraph in data.sampled_subgraphs:
484
            for _, value in sampledsubgraph.sampled_csc.items():
485
                assert torch.equal(
486
487
                    torch.ge(value.indices, torch.zeros(len(value.indices))),
                    torch.ones(len(value.indices)),
488
489
                )
                assert torch.equal(
490
491
                    torch.ge(value.indptr, torch.zeros(len(value.indptr))),
                    torch.ones(len(value.indptr)),
492
493
494
495
496
497
498
499
500
501
502
                )
            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)),
                )
503
504


505
506
507
508
@unittest.skipIf(
    F._default_context_str != "cpu",
    reason="Fails due to randomness on the GPU.",
)
509
510
511
512
513
@pytest.mark.parametrize(
    "sampler_type",
    [SamplerType.Normal, SamplerType.Layer, SamplerType.Temporal],
)
def test_SubgraphSampler_without_dedpulication_Homo(sampler_type):
514
515
516
    graph = dgl.graph(
        ([5, 0, 1, 5, 6, 7, 2, 2, 4], [0, 1, 2, 2, 2, 2, 3, 4, 4])
    )
517
    graph = gb.from_dglgraph(graph, True).to(F.ctx())
518
    seed_nodes = torch.LongTensor([0, 3, 4])
519
520
521
522
523
524
525
526
527
    items = seed_nodes
    names = "seed_nodes"
    if sampler_type == SamplerType.Temporal:
        graph.node_attributes = {
            "timestamp": torch.zeros(graph.csc_indptr.numel() - 1).to(F.ctx())
        }
        graph.edge_attributes = {
            "timestamp": torch.zeros(graph.indices.numel()).to(F.ctx())
        }
528
        items = (items, torch.randint(1, 10, (3,)))
529
        names = (names, "timestamp")
530

531
    itemset = gb.ItemSet(items, names=names)
532
533
534
    item_sampler = gb.ItemSampler(itemset, batch_size=len(seed_nodes)).copy_to(
        F.ctx()
    )
535
536
537
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]

538
539
540
541
542
    sampler = _get_sampler(sampler_type)
    if sampler_type == SamplerType.Temporal:
        datapipe = sampler(item_sampler, graph, fanouts)
    else:
        datapipe = sampler(item_sampler, graph, fanouts, deduplicate=False)
543
544
545

    length = [17, 7]
    compacted_indices = [
546
547
        (torch.arange(0, 10) + 7).to(F.ctx()),
        (torch.arange(0, 4) + 3).to(F.ctx()),
548
549
    ]
    indptr = [
550
551
552
553
554
555
        torch.tensor([0, 1, 2, 4, 4, 6, 8, 10]).to(F.ctx()),
        torch.tensor([0, 1, 2, 4]).to(F.ctx()),
    ]
    seeds = [
        torch.tensor([0, 3, 4, 5, 2, 2, 4]).to(F.ctx()),
        torch.tensor([0, 3, 4]).to(F.ctx()),
556
557
558
559
560
    ]
    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(
561
562
563
564
                sampled_subgraph.sampled_csc.indices, compacted_indices[step]
            )
            assert torch.equal(
                sampled_subgraph.sampled_csc.indptr, indptr[step]
565
566
567
568
569
570
            )
            assert torch.equal(
                sampled_subgraph.original_column_node_ids, seeds[step]
            )


571
572
573
574
575
@pytest.mark.parametrize(
    "sampler_type",
    [SamplerType.Normal, SamplerType.Layer, SamplerType.Temporal],
)
def test_SubgraphSampler_without_dedpulication_Hetero(sampler_type):
576
    graph = get_hetero_graph().to(F.ctx())
577
578
579
580
581
582
583
584
585
    items = torch.arange(2)
    names = "seed_nodes"
    if sampler_type == SamplerType.Temporal:
        graph.node_attributes = {
            "timestamp": torch.zeros(graph.csc_indptr.numel() - 1).to(F.ctx())
        }
        graph.edge_attributes = {
            "timestamp": torch.zeros(graph.indices.numel()).to(F.ctx())
        }
586
        items = (items, torch.randint(1, 10, (2,)))
587
588
        names = (names, "timestamp")
    itemset = gb.ItemSetDict({"n2": gb.ItemSet(items, names=names)})
589
    item_sampler = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
590
591
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
592
593
594
595
596
    sampler = _get_sampler(sampler_type)
    if sampler_type == SamplerType.Temporal:
        datapipe = sampler(item_sampler, graph, fanouts)
    else:
        datapipe = sampler(item_sampler, graph, fanouts, deduplicate=False)
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
    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],
645
                    original_row_node_ids[step][ntype].to(F.ctx()),
646
647
648
                )
                assert torch.equal(
                    sampled_subgraph.original_column_node_ids[ntype],
649
                    original_column_node_ids[step][ntype].to(F.ctx()),
650
651
652
                )
            for etype in ["n1:e1:n2", "n2:e2:n1"]:
                assert torch.equal(
653
                    sampled_subgraph.sampled_csc[etype].indices,
654
                    csc_formats[step][etype].indices.to(F.ctx()),
655
656
                )
                assert torch.equal(
657
                    sampled_subgraph.sampled_csc[etype].indptr,
658
                    csc_formats[step][etype].indptr.to(F.ctx()),
659
                )
660
661


662
663
664
665
@unittest.skipIf(
    F._default_context_str != "cpu",
    reason="Fails due to randomness on the GPU.",
)
666
667
668
669
@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]))
670
    graph = gb.from_dglgraph(graph, True).to(F.ctx())
671
672
673
    seed_nodes = torch.LongTensor([0, 3, 4])

    itemset = gb.ItemSet(seed_nodes, names="seed_nodes")
674
675
676
    item_sampler = gb.ItemSampler(itemset, batch_size=len(seed_nodes)).copy_to(
        F.ctx()
    )
677
678
679
680
681
682
683
684
685
686
687
688
689
    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,
    )

    original_row_node_ids = [
690
691
        torch.tensor([0, 3, 4, 5, 2, 6, 7]).to(F.ctx()),
        torch.tensor([0, 3, 4, 5, 2]).to(F.ctx()),
692
693
    ]
    compacted_indices = [
694
695
        torch.tensor([3, 4, 4, 2, 5, 6]).to(F.ctx()),
        torch.tensor([3, 4, 4, 2]).to(F.ctx()),
696
697
    ]
    indptr = [
698
699
700
701
702
703
        torch.tensor([0, 1, 2, 4, 4, 6]).to(F.ctx()),
        torch.tensor([0, 1, 2, 4]).to(F.ctx()),
    ]
    seeds = [
        torch.tensor([0, 3, 4, 5, 2]).to(F.ctx()),
        torch.tensor([0, 3, 4]).to(F.ctx()),
704
705
706
707
708
709
710
711
    ]
    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(
712
713
714
715
                sampled_subgraph.sampled_csc.indices, compacted_indices[step]
            )
            assert torch.equal(
                sampled_subgraph.sampled_csc.indptr, indptr[step]
716
717
718
719
720
721
722
723
            )
            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):
724
    graph = get_hetero_graph().to(F.ctx())
725
726
727
    itemset = gb.ItemSetDict(
        {"n2": gb.ItemSet(torch.arange(2), names="seed_nodes")}
    )
728
    item_sampler = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
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
    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,
    )
    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],
786
                    original_row_node_ids[step][ntype].to(F.ctx()),
787
788
789
                )
                assert torch.equal(
                    sampled_subgraph.original_column_node_ids[ntype],
790
                    original_column_node_ids[step][ntype].to(F.ctx()),
791
792
793
                )
            for etype in ["n1:e1:n2", "n2:e2:n1"]:
                assert torch.equal(
794
                    sampled_subgraph.sampled_csc[etype].indices,
795
                    csc_formats[step][etype].indices.to(F.ctx()),
796
797
                )
                assert torch.equal(
798
                    sampled_subgraph.sampled_csc[etype].indptr,
799
                    csc_formats[step][etype].indptr.to(F.ctx()),
800
                )